{"text": "function Offspring = Operator(Problem,Particle,Pbest,Gbest)\n% Particle swarm optimization in SMPSO\n\n%------------------------------- Copyright --------------------------------\n% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for\n% research purposes. All publications which use this platform or any code\n% in the platform should acknowledge the use of \"PlatEMO\" and reference \"Ye\n% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform\n% for evolutionary multi-objective optimization [educational forum], IEEE\n% Computational Intelligence Magazine, 2017, 12(4): 73-87\".\n%--------------------------------------------------------------------------\n\n %% Parameter setting\n ParticleDec = Particle.decs;\n PbestDec = Pbest.decs;\n GbestDec = Gbest.decs;\n [N,D] = size(ParticleDec);\n ParticleVel = Particle.adds(zeros(N,D));\n\n %% Particle swarm optimization\n W = repmat(unifrnd(0.1,0.5,N,1),1,D);\n r1 = repmat(rand(N,1),1,D);\n r2 = repmat(rand(N,1),1,D);\n C1 = repmat(unifrnd(1.5,2.5,N,1),1,D);\n C2 = repmat(unifrnd(1.5,2.5,N,1),1,D);\n OffVel = W.*ParticleVel + C1.*r1.*(PbestDec-ParticleDec) + C2.*r2.*(GbestDec-ParticleDec);\n phi = max(4,C1+C2);\n OffVel = OffVel.*2./abs(2-phi-sqrt(phi.^2-4*phi));\n delta = repmat((Problem.upper-Problem.lower)/2,N,1);\n OffVel = max(min(OffVel,delta),-delta);\n OffDec = ParticleDec + OffVel;\n \n %% Deterministic back\n Lower = repmat(Problem.lower,N,1);\n Upper = repmat(Problem.upper,N,1);\n repair = OffDec < Lower | OffDec > Upper;\n OffVel(repair) = 0.001*OffVel(repair);\n OffDec = max(min(OffDec,Upper),Lower);\n \n %% Polynomial mutation\n disM = 20;\n Site1 = repmat(rand(N,1)<0.15,1,D);\n Site2 = rand(N,D) < 1/D;\n mu = rand(N,D);\n temp = Site1 & Site2 & mu<=0.5;\n OffDec(temp) = OffDec(temp)+(Upper(temp)-Lower(temp)).*((2.*mu(temp)+(1-2.*mu(temp)).*...\n (1-(OffDec(temp)-Lower(temp))./(Upper(temp)-Lower(temp))).^(disM+1)).^(1/(disM+1))-1);\n temp = Site1 & Site2 & mu>0.5; \n OffDec(temp) = OffDec(temp)+(Upper(temp)-Lower(temp)).*(1-(2.*(1-mu(temp))+2.*(mu(temp)-0.5).*...\n (1-(Upper(temp)-OffDec(temp))./(Upper(temp)-Lower(temp))).^(disM+1)).^(1/(disM+1)));\n Offspring = Problem.Evaluation(OffDec,OffVel);\nend", "meta": {"author": "BIMK", "repo": "PlatEMO", "sha": "c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5", "save_path": "github-repos/MATLAB/BIMK-PlatEMO", "path": "github-repos/MATLAB/BIMK-PlatEMO/PlatEMO-c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5/PlatEMO/Algorithms/Multi-objective optimization/SMPSO/Operator.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358015, "lm_q2_score": 0.668880247169804, "lm_q1q2_score": 0.5499460746723713}} {"text": "function [association] = ft_nonlinearassociation(cfg, data)\n\n% NONLINEARASSOCIATION calculate the association coefficient as a\n% function of delay.\n%\n% In order to estimate the amount of association between all possible\n% pairs of MEG sensors the nonlinear association analysis is used.\n% It was first developed for EEG data analysis by Pijn and co-workers\n% (Lopes da Silva, et al. 1989; Pijn, et al. 1990). The basic principle\n% is similar to that of coherence and (cross) correlation, with the\n% exception that this nonlinear association method can be applied\n% independent of the type of relationship (linear or nonlinear) in\n% the data.\n% \n% The method is based on the idea that if two signals x and y are\n% correlated, a nonlinear regression curve can be calculated that\n% represents their relationship. In practice, that regression curve\n% is estimated by creating a scatterplot of y versus x, dividing the\n% data in segments and describing each segment with a linear regression\n% curve. The estimated correlation ratio h2, which gives the reduction\n% in variance of y as a result of predicting its values according to\n% the regression curve, can be calculated as follows:\n% \n% h^2 = (sum(Yi - mean(Y))^2 - sum(Yi - f(Xi))^2) / sum(Yi - mean(Y))^2\n% \n% With the sum going over N samples and f(Xi) the estimated value of\n% Yi according to the regression line. The h2 coefficient has values\n% between 0 (y is completely independent of x) and 1 (y is completely\n% determined by x). In the case of a linear relationship between x\n% and y, h2 is equal to the well known Pearson correlation coefficient\n% (r2). As is the case with cross-correlation, it is possible to\n% estimate h2 as a function of time shift () between the signals. The\n% h2 is then iteratively calculated for different values of , by\n% shifting the signals in comparison to each other, and the value for\n% which the maximal h2 is reached can be used as an estimate of the\n% time lag between both signals. In deciding what epoch length to use\n% in the association analysis, a trade-off has to be made between\n% successfully determining the correct delay and h2-value (for which\n% large epoch lengths are necessary) and a small enough time-resolution\n% (for which small epoch lengths are necessary).\n% \n% Use as\n% [association] = ft_nonlinearassociation(cfg, data)\n%\n% The input data should be organised in a structure as obtained from\n% the PREPROCESSING function.\n%\n% The configuration should contain\n% cfg.channel = Nx1 cell-array with selection of channels (default = 'all'), see CHANNELSELECTION for details\n% cfg.keeptrials = 'yes' or 'no', process the individual trials or the concatenated data (default = 'no')\n% cfg.trials = 'all' or a selection given as a 1xN vector (default = 'all')\n% cfg.fsample = 1200\n% cfg.maxdelay = 32/cfg.fsample\n% cfg.delaystep = 2/cfg.fsample\n% cfg.nr_bins = 7\n% cfg.offset = 0\n% cfg.order = 'Hxy'\n% cfg.timwin = 0.2\n% cfg.toi = []\n%\n% References\n% - Lopes da Silva F, Pijn JP, Boeijinga P. (1989): Interdependence of\n% EEG signals: linear vs. nonlinear associations and the significance\n% of time delays and phase shifts. Brain Topogr 2(1-2):9-18.\n% - Pijn JP, Vijn PC, Lopes da Silva FH, Van Ende Boas W, Blanes W.\n% (1990): Localization of epileptogenic foci using a new signal\n% analytical approach. Neurophysiol Clin 20(1):1-11.\n\n% Copyright (C) 2007, Inge Westmijse\n\nft_defaults\n\n% set the defaults\nif ~isfield(cfg, 'trials'), cfg.trials = 'all'; end\nif ~isfield(cfg, 'keeptrials'), cfg.keeptrials = 'no'; end\nif ~isfield(cfg, 'channel'), cfg.channel = 'all'; end\nif ~isfield(cfg, 'toi'), cfg.toi = []; end\nif ~isfield(cfg, 'timwin'), cfg.timwin = 0.2; end\nif ~isfield(cfg, 'fsample'), cfg.fsample = 1200; end\nif ~isfield(cfg, 'delaystep'), cfg.delaystep = 2/cfg.fsample; end\nif ~isfield(cfg, 'maxdelay'), cfg.maxdelay = 32/cfg.fsample; end\nif ~isfield(cfg, 'offset'), cfg.offset = 0; end\nif ~isfield(cfg, 'nr_bins'), cfg.nr_bins = 7; end\nif ~isfield(cfg, 'order'), cfg.order = 'Hxy'; end\nif ~isfield(cfg, 'feedback'), cfg.feedback = 'textbar'; end\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% do some bookkeeping on the data\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% select trials of interest\nif ~strcmp(cfg.trials, 'all')\n if islogical(cfg.trials), cfg.trials=find(cfg.trials); end\n fprintf('selecting %d trials\\n', length(cfg.trials));\n data.trial = data.trial(cfg.trials);\n data.time = data.time(cfg.trials);\nend\nNtrials = numel(data.trial);\n\n% select channels of interest\ncfg.channel = channelselection(cfg.channel, data.label);\nchansel = match_str(data.label, cfg.channel);\nfprintf('selecting %d channels\\n', length(chansel));\nfor trial=1:Ntrials\n data.trial{trial} = data.trial{trial}(chansel,:);\nend\ndata.label = data.label(chansel);\nNchans = length(chansel);\n\n% determine the size of each trial, they can be variable length\nNsamples = zeros(1,Ntrials);\nfor trial=1:Ntrials\n Nsamples(trial) = size(data.trial{trial},2);\nend\n\nif strcmp(cfg.keeptrials, 'no')\n % concatenate all the data into a 2D matrix\n fprintf('concatenating data');\n dat = zeros(Nchans, sum(Nsamples));\n for trial=1:Ntrials\n fprintf('.');\n begsample = sum(Nsamples(1:(trial-1))) + 1;\n endsample = sum(Nsamples(1:trial));\n dat(:,begsample:endsample) = data.trial{trial};\n end\n fprintf('\\n');\n fprintf('concatenated data matrix size %dx%d\\n', size(dat,1), size(dat,2));\n time = [1/cfg.fsample : size(dat,1)/cfg.fsample : size(dat,1)];\n data.trial = {dat};\n data.time = {time};\n Ntrials = 1;\nelse\n % replace the time axis, since shifted time-axes over trials are not supported\n for i = 1:Ntrials\n data.time{i} = [1/cfg.fsample : 1/cfg.fsample : size(data.trial{i},2) / cfg.fsample];\n end\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% prepare all data selection\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% item 1: channel combinations\nnumchannelcmb = Nchans*(Nchans-1)/2;\nchannelcmb = zeros(numchannelcmb, 2);\nk = 1;\n\nif (strcmp(cfg.order, 'Hxy'))\n for i=1:Nchans\n for j=(i+1):Nchans\n channelcmb(k, :) = [i j];\n k = k+1;\n end\n end\nelseif (strcmp(cfg.order, 'Hyx'))\n for i = Nchans:-1:1\n for j = Nchans : -1:(i+1)\n channelcmb(k,:) = [i j];\n k = k+1;\n end\n end\nend\nnumchannelcmb = size(channelcmb,1);\n\n% item 2: time windows\n% this requires\n% cfg.toi = [t1 t2 t3 t4] center time of each window\n% cfg.timwin = 0.2 in seconds\n% TODO implement \"time, offset, fsample\"\n\nfor j = 1:Ntrials\n time = data.time{j};\n numtimwin = size(cfg.toi,2); % initial guess, not all might fit in this trial\n timwin = zeros(numtimwin,2);\n sel = zeros(numtimwin,1);\n for i=1:numtimwin\n timwin(i,1) = cfg.toi(i) - cfg.timwin/2; % begin of time window\n timwin(i,2) = cfg.toi(i) + cfg.timwin/2; % end of time window\n sel(i) = timwin(i,1)>=time(1) && timwin(i,2)<=time(end); % does it fit in?\n end\n timwin = timwin(find(sel==1),:);\n toi_mat{j} = cfg.toi(find(sel == 1)); % update the configuration\n timwin_mat{j} = round((timwin - cfg.offset) * cfg.fsample); % convert to samples\nend\n\ntimwin = timwin_mat;\ncfg.toi = toi_mat;\n\n% item 3: delays within each timewindow\n% this requires\n% cfg.delaystep\n% cfg.maxdelay\ndelay = -cfg.maxdelay:cfg.delaystep:cfg.maxdelay;\nnumdelay = length(delay);\n% convert to samples\ndelay = round(delay * cfg.fsample);\n\nif strcmp(cfg.keeptrials, 'yes')\n for trllop=1:Ntrials\n association.trial(trllop) = Do_Association_Calculation( trllop , Ntrials , cfg , timwin , numchannelcmb , numdelay , data , channelcmb , delay );\n end % for each trial\nelse\n trllop = 1;\n association = Do_Association_Calculation( trllop , Ntrials , cfg , timwin , numchannelcmb , numdelay , data , channelcmb , delay );\nend\n\n% add the version details of this function call to the configuration\ntry\n % get the full name of the function\n cfg.version.name = mfilename('fullpath');\ncatch\n % required for compatibility with Matlab versions prior to release 13 (6.5)\n [st, i] = dbstack;\n cfg.version.name = st(i);\nend\ncfg.version.id = '$Id$';\n% remember the configuration details of the input data\ntry, cfg.previous = data.cfg; end\n% remember the exact configuration details in the output\nassociation.cfg = cfg;\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% SUBFUNCTION that does the computation for each trial\nfunction [association] = Do_Association_Calculation( trllop , Ntrials , cfg , timwin , numchannelcmb , numdelay , data , channelcmb , delay )\n\nfprintf('\\nprocessing trial %d from %d\\n', trllop, Ntrials);\n\nassociation = [];\nnumtimwin = size(timwin{trllop},1);\nh2 = zeros(numchannelcmb, numtimwin, numdelay);\n\nl = 0;\nmaxl = numchannelcmb*numtimwin*numdelay;\nprogress('init', cfg.feedback, 'Computing nonlinear association for each delay');\n\nfor i=1:numchannelcmb\n dat1_chan = data.trial{trllop}(channelcmb(i,1),:);\n dat2_chan = data.trial{trllop}(channelcmb(i,2),:);\n progress(l/maxl,'Computing nonlinear association %d from %d', l, maxl);\n\n for j=1:numtimwin\n dat1_timwin = dat1_chan(timwin{trllop}(j,1):timwin{trllop}(j,2));\n dat2_timwin = dat2_chan(timwin{trllop}(j,1):timwin{trllop}(j,2));\n\n for k=1:numdelay\n if delay(k)==0\n % select the complete (unshifted) window\n dat1_delay = dat1_timwin;\n dat2_delay = dat2_timwin;\n elseif delay(k)<0\n % channel 1 is shifted w.r.t. channel 2\n dat1_delay = dat1_timwin((abs(delay(k))+1):end);\n dat2_delay = dat2_timwin(1:(end-abs(delay(k))));\n elseif delay(k)>0\n % channel 2 is shifted w.r.t. channel 1\n dat1_delay = dat1_timwin(1:(end-delay(k)));\n dat2_delay = dat2_timwin((delay(k)+1):end);\n end\n\n % remove the mean of each snippet of data\n dat1_delay = dat1_delay - mean(dat1_delay);\n dat2_delay = dat2_delay - mean(dat2_delay);\n\n % do the computation\n\n [sorted_data1,id] = sort(dat1_delay);\n sorted_data2 = dat2_delay(id);\n\n data_is = sorted_data1;\n data_js = sorted_data2;\n\n % divided data_i in bins\n [H,mp_i] = hist(data_is,cfg.nr_bins);\n\n % Divide data_i and data_j in bins\n bp = 1;\n gem_j = zeros (cfg.nr_bins,1);\n for s = 1:cfg.nr_bins\n gem_j(s) = mean(data_js(bp:bp+H(s)-1));\n bp = bp + H(s);\n end\n\n % Calculation of line segment and variance per bin\n p=1;\n sp = 1;\n\n clear unex_var tot_var;\n\n for u = 1:cfg.nr_bins\n data_is_bin = data_is(sp:sp+H(u)-1)';\n data_js_bin = data_js(sp:sp+H(u)-1)';\n\n if u == 1\n fx1 = gem_j(u) + (gem_j(u+1) - gem_j(u))/(mp_i(u+1) - mp_i(u))*(data_is_bin(1:round(length(data_is_bin)/2)) - mp_i(u));\n else\n fx1 = gem_j(u-1) + (gem_j(u) - gem_j(u-1))/(mp_i(u) - mp_i(u-1))*(data_is_bin(1:round(length(data_is_bin)/2)) - mp_i(u-1));\n end\n if u == cfg.nr_bins\n fx2 = gem_j(u-1) + (gem_j(u) - gem_j(u-1))/(mp_i(u) - mp_i(u-1))*(data_is_bin(round(length(data_is_bin)/2)+1:end) - mp_i(u-1));\n else\n fx2 = gem_j(u) + (gem_j(u+1) - gem_j(u))/(mp_i(u+1) - mp_i(u))*(data_is_bin(round(length(data_is_bin)/2)+1:end) - mp_i(u));\n end\n\n % calculation unexplained variance\n ftot = [fx1; fx2];\n unex_var(p:p+length(data_js_bin)-1,:) = (data_js_bin - ftot).^2;\n\n % calculation total variance\n tot_var(p:p+length(data_js_bin)-1,:) = (data_js_bin - mean(data_js)).^2;\n\n p = p+length(data_is_bin);\n sp = sp + H(u);\n end\n\n % Calculation of association coefficient h2\n h2(i,j,k) = ((sum(tot_var) - sum(unex_var)) / sum(tot_var))*100;\n l=l+1;\n end\n end\nend\n\nprogress('close');\n\n% collect the results\nif (size(h2, 1) ~= numchannelcmb)\n error('number of channel combinations is not right');\nend\nif (size(h2, 2) ~= numtimwin)\n error('number of timewindows does not match input');\nend\nif (size(h2, 3) ~= numdelay)\n error('number of delays does not match input');\nend\nh2 = reshape(h2, numchannelcmb*numtimwin, numdelay);\n[m, indx] = max(h2, [], 2);\nh2 = reshape(m, numchannelcmb, numtimwin);\nd = (delay(indx)./cfg.fsample)*1000; % convert to miliseconds (to compare with original method)\nd = reshape(d, numchannelcmb, numtimwin);\n\n% FIXME this does not work: one is not supposed to rely on data.cfg.trl, use data.time please!\n% association.time = cfg.toi{trllop} + data.cfg.trl(trllop,1);\n\nassociation.h2 = h2;\nassociation.delay = d;\n\nreturn % from Do_Association_Calculation\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% SUBFUNCTION that computes the mean over all values without checking the dimensions\n% this function is approximately 2x faster on 1 dimensional data than the matlab version\nfunction y = mean(x)\ny = sum(x(:))./numel(x);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% SUBFUNCTION that bins the elements of Y into equally spaced containers\n% this function is approximately 2x faster on 1 dimensional data than the matlab version\nfunction [nn, x] = hist(y, x)\nminy = min(y);\nmaxy = max(y);\nbinwidth = (maxy - miny) ./ x;\nxx = miny:binwidth:maxy;\nx = xx(1:(end-1)) + binwidth/2;\n% Shift bins so the interval is ( ] instead of [ ).\nxx = full(real(xx)); y = full(real(y)); % For compatibility\nbins = xx + eps(xx);\nnn = histc(y',[-inf bins],1);\n% Combine first bin with 2nd bin and last bin with next to last bin\nnn(2,:) = nn(2,:)+nn(1,:);\nnn(end-1,:) = nn(end-1,:)+nn(end,:);\nnn = nn(2:end-1,:);\n\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/contrib/misc/ft_nonlinearassociation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.5499460742707919}} {"text": "classdef IMMOEA_F3 < 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 = 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 = (1+5*repmat(2:obj.D,size(X,1),1)/obj.D).*X(:,2:obj.D) - repmat(X(:,1),1,obj.D-1);\n g = 1 + 9*mean(t.^2,2);\n PopObj(:,1) = 1 - exp(-4*X(:,1)).*sin(6*pi*X(:,1)).^6;\n PopObj(:,2) = g.*(1-(PopObj(:,1)./g).^2);\n end\n %% Generate points on the Pareto front\n function R = GetOptimum(obj,N)\n minf1 = min(1-exp(-4*(0:1e-6:1)).*(sin(6*pi*(0:1e-6:1))).^6);\n R(:,1) = linspace(minf1,1,N)';\n R(:,2) = 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/IMMOEA_F3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.734119526900183, "lm_q2_score": 0.7490872075132152, "lm_q1q2_score": 0.5499195463865808}} {"text": "function handle = draw_waypoints(fig_handle, wpt_list, radius, handle, mode)\n% DRAW_WAYPOINTS - plot waypoints\n\n if wpt_list(1,4)==-9999 % check to see if Dubins paths\n XX = [wpt_list(:,1)];\n YY = [wpt_list(:,2)];\n ZZ = [wpt_list(:,3)];\n else\n XX = [];\n YY = [];\n ZZ = [];\n for i=2:size(wpt_list,1)\n dubinspath = compute_dubins_param(wpt_list(i-1,:),wpt_list(i,:),radius);\n [tmpX,tmpY,tmpZ] = points_along_dubins_path(dubinspath,0.1);\n XX = [XX; tmpX];\n YY = [YY; tmpY]; \n ZZ = [ZZ; tmpZ];\n end\n% ZZ = wpt_list(i,3)*ones(size(XX));\n end\n \n if isempty(handle)\n handle = plot3(fig_handle.Children, YY, XX, -ZZ, 'b');\n else\n set(handle,'XData', YY, 'YData', XX, 'ZData', -ZZ);\n drawnow\n end\nend \n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [X,Y,Z] = points_along_dubins_path(dubinspath,Del)\n% Points Along Dubins Path -\n% Find points along Dubin's path separted by Del (to be used in\n% collision detection)\n\n % points along start circle\n th1 = mod(atan2(dubinspath.ps(2)-dubinspath.cs(2),dubinspath.ps(1)-dubinspath.cs(1)),2*pi);\n th2 = mod(atan2(dubinspath.w1(2)-dubinspath.cs(2),dubinspath.w1(1)-dubinspath.cs(1)),2*pi);\n if dubinspath.lams>0\n if th1>=th2\n th = [th1:Del:2*pi,0:Del:th2];\n else\n th = [th1:Del:th2];\n end\n else\n if th1<=th2\n th = [th1:-Del:0,2*pi:-Del:th2];\n else\n th = [th1:-Del:th2];\n end\n end\n X = [];\n Y = [];\n Z = [];\n for i=1:length(th)\n X = [X; dubinspath.cs(1)+dubinspath.R*cos(th(i))]; \n Y = [Y; dubinspath.cs(2)+dubinspath.R*sin(th(i))];\n Z = [Z; dubinspath.cs(3)];\n end\n \n % points along straight line \n sig = 0;\n while sig<=1\n X = [X; (1-sig)*dubinspath.w1(1) + sig*dubinspath.w2(1)];\n Y = [Y; (1-sig)*dubinspath.w1(2) + sig*dubinspath.w2(2)];\n Z = [Z; (1-sig)*dubinspath.w1(3) + sig*dubinspath.w2(3)];\n sig = sig + Del;\n end\n \n % points along end circle\n th2 = mod(atan2(dubinspath.pe(2)-dubinspath.ce(2),dubinspath.pe(1)-dubinspath.ce(1)),2*pi);\n th1 = mod(atan2(dubinspath.w2(2)-dubinspath.ce(2),dubinspath.w2(1)-dubinspath.ce(1)),2*pi);\n if dubinspath.lame>0\n if th1>=th2\n th = [th1:Del:2*pi,0:Del:th2];\n else\n th = [th1:Del:th2];\n end\n else\n if th1<=th2\n th = [th1:-Del:0,2*pi:-Del:th2];\n else\n th = [th1:-Del:th2];\n end\n end\n for i=1:length(th)\n X = [X; dubinspath.ce(1)+dubinspath.R*cos(th(i))]; \n Y = [Y; dubinspath.ce(2)+dubinspath.R*sin(th(i))];\n Z = [Z; dubinspath.ce(3)];\n end\nend", "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/graphics/graphics_map/draw_waypoints.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5499033717957107}} {"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 % Examples:\n % C = graph_coloring(facet_adjacency_matrix(F),9);\n % tsurf(F,V,'CData',C);\n % colormap(cbrewer('Set1',max(C)));\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": "alecjacobson", "repo": "gptoolbox", "sha": "a0cb37d8edbcfb1e3587f793df8f24c76a2d7305", "save_path": "github-repos/MATLAB/alecjacobson-gptoolbox", "path": "github-repos/MATLAB/alecjacobson-gptoolbox/gptoolbox-a0cb37d8edbcfb1e3587f793df8f24c76a2d7305/matrix/graph_coloring.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5499033717957107}} {"text": "function varargout = pnes_master(fcn, x0, opt)\n%PNES_MASTER Parameterized Nonlinear Equation Solver wrapper function.\n% [X, F, EXITFLAG, OUTPUT, JAC] = PNES_MASTER(FCN, X0, OPT)\n% [X, F, EXITFLAG, OUTPUT, JAC] = PNES_MASTER(PROBLEM)\n% A common wrapper function for numerical continuation methods for\n% solving parameterized nonlinear equations. Traces the solutions of\n% a parameterized nonlinear equation f(x) = 0, beginning from a starting\n% point x0, where f(x) has dimension n and x has dimension n+1.\n%\n% In the current implementation, the last element of x is taken to be\n% the parameter lambda, where lambda = 0 corresponds to the base solution.\n%\n% Inputs:\n% FCN : handle to function that evaluates the function f(x) to\n% be solved and its Jacobian, J(x). Calling syntax for this\n% function is:\n% f = FCN(x)\n% [f, J] = FCN(x)\n% For a parameterized function, f is n x 1, x is (n+1) x 1,\n% and J is the n x (n+1) matrix of partial derivatives of\n% f (rows) w.r.t. x (cols).\n% X0 : starting value, x0, of vector x ((n+1) x 1)\n% OPT : optional options structure with the following fields,\n% all of which are also optional (default values shown in\n% parentheses)\n% alg ('DEFAULT') : determines which solver to use\n% 'DEFAULT' : automatic, currently there is only one\n% solver implementation, a predictor/corrector method\n% verbose (0) - controls level of progress output displayed\n% 0 = no progress output\n% 1-5 = increasing levels of progress output\n% nleqs_opt - options struct for NLEQS_MASTER used for\n% corrector stage (see NLEQS_MASTER for details), default\n% sets nleqs_opt.verbose to 0, otherwise to 2 if OPT.verbose > 4\n% solve_base (1) : 0/1 flag that determines whether or not to\n% run a corrector stage for initial solution point, x0\n% parameterization (3) - choice of parameterization\n% 1 - natural\n% 2 - arc len\n% 3 - pseudo arc len\n% stop_at ('NOSE') - determines stopping criterion\n% 'NOSE' - stop when limit or nose point is reached\n% 'FULL' - trace full continuation curve\n% - stop upon reaching specified target lambda value\n% max_it (2000) - maximum number of continuation steps\n% step (0.05) - continuation step size\n% adapt_step (0) - toggle adaptive step size feature\n% 0 - adaptive step size disabled\n% 1 - adaptive step size enabled\n% adapt_step_damping (0.7) - damping factor for adaptive step sizing\n% adapt_step_tol (1e-3) - tolerance for adaptive step sizing\n% adapt_step_ws (1) - scale factor for default initial step size\n% when warm-starting with adaptive step size enabled\n% step_min (1e-4) - minimum allowed step size\n% step_max (0.2) - maximum allowed step size\n% default_event_tol (1e-3) - default tolerance for event functions\n% target_lam_tol (0) - tolerance for target lambda detection, 0 means\n% use the value of default_event_tol\n% nose_tol (0) - tolerance for nose point detection, 0 means use\n% the value of default_event_tol\n% events () - cell array of specs for user-defined event\n% functions, passed as MY_EVENTS arg to PNE_REGISTER_EVENTS\n% (see PNE_REGISTER_EVENTS for details).\n% callbacks () - cell array of specs for user-defined callback\n% functions, to be passed as MY_CBACKS arg to\n% PNE_REGISTER_CALLBACKS (see PNE_REGISTER_CALLBACKS for details).\n% output_fcn () - handle to custom output function, called by\n% PNE_CALLBACK_DEFAULT\n% plot - options for plotting of continuation curve by\n% PNE_CALLBACK_DEFAULT\n% .level (0) - control plotting of continuation curve\n% 0 - do not plot continuation curve\n% 1 - plot when completed\n% 2 - plot incrementally at each continuation step\n% 3 - same as 2, with 'pause' at each continuation step\n% .idx () - index of quantity to plot, passed to yfcn()\n% .idx_default () - function to provide default value\n% for idx, if none provided\n% .xname ('lam') - name of output field holding values that\n% determine horizontal coordinates of plot\n% .yname ('x') - name of output field holding values that\n% determine vertical coordinates of plot\n% .xfcn () - handle to function that maps a value from\n% the field of the OUTPUT indicated by value of plot.xname\n% to a horizontal coordinate for plotting\n% .yfcn () - handle to function that maps a value from\n% the field of the OUTPUT indicated by value of plot.yname\n% and an index to be applied to that value into a vertical\n% coordinate for plotting\n% .xlabel ('\\lambda') - label for horizontal axis\n% .ylabel ('Variable Value') - label for vertical axis\n% .title ('Value of Variable %d') - plot title used for plot of\n% single variable, can use %d as placeholder for var index\n% .title2 ('Value of Multiple Variables') - plot title used for\n% plot of multiple variables\n% .legend ('Variable %d') - legend label, %d can be used as\n% placeholder for variable index\n% warmstart () - struct containing warm-start state, see\n% warmstart field in OUTPUT below for details of expected\n% fields\n% PROBLEM : The inputs can alternatively be supplied in a single\n% PROBLEM struct with fields corresponding to the input arguments\n% described above: fcn, x0, opt\n%\n% Outputs (all optional, except X):\n% X : solution vector x\n% F : final function value, f(x)\n% EXITFLAG : exit flag\n% 1 = succeeded\n% 0 = failed\n% OUTPUT : output struct with the following fields:\n% corrector - output return value from NLEQS_MASTER from final\n% corrector run (see NLEQS_MASTER for details)\n% iterations - N, total number of continuation steps performed\n% events - struct array of size NE of events detected with fields:\n% k - continuation step at which event was located\n% name - name of detected event\n% idx - index(es) of critical elements in corresponding event\n% function\n% msg - descriptive text detailing the event\n% done_msg - message describing cause of continuation termination\n% steps - (N+1) row vector of stepsizes taken at each continuation\n% step\n% lam_hat - (N+1) row vector of lambda values from prediction steps\n% lam - (N+1) row vector of lambda values from correction steps\n% max_lam - maximum value of parameter lambda (from OUTPUT.lam)\n% warmstart - optional output with information needed for\n% warm-starting an updated continuation problem, with fields:\n% cont_steps - current value of continuation step counter\n% direction - +1 or -1, for tracing of curve in same or\n% opposite direction, respectively\n% dir_from_jac_eigs - 0/1 flag to indicate whether to use\n% the sign of the smallest eigenvalue of the Jacobian to\n% determine the initial direction\n% x - current solution vector\n% z - current tangent vector\n% xp - previous step solution vector\n% zp - previous step tangent vector\n% parm - function handle for current parameterization function\n% default_parm - function handle for default parameterization fcn\n% default_step - default step size\n% events - current event log, same as OUTPUT.events\n% cbs - struct containing user state information for callbacks\n% see PNES_CALLBACK_DEFAULT for more details\n% (others) - depends on OPT.output_fcn, by default (i.e. with no\n% explicitly provided output function) includes fields:\n% x_hat - NX x (N+1) matrix of solution values from\n% prediction steps\n% x - NX x (N+1) matrix of solution values from correction\n% steps\n% JAC : final Jacobian matrix, J(x)\n%\n% Calling syntax options:\n% [x, f, exitflag, output, jac] = pnes_master(fcn, x0);\n% [x, f, exitflag, output, jac] = pnes_master(fcn, x0, opt);\n% x = pnes_master(problem);\n% where problem is a struct with fields: fcn, x0, opt\n% where opt is optional\n% x = pnes_master(...);\n% [x, f] = pnes_master(...);\n% [x, f, exitflag] = pnes_master(...);\n% [x, f, exitflag, output] = pnes_master(...);\n% [x, f, exitflag, output, jac] = pnes_master(...);\n%\n% Example: (based on https://www.chilimath.com/lessons/advanced-algebra/systems-non-linear-equations/)\n% function [f, J] = f1p(x)\n% f = [ x(1) + x(2) + 6*x(3) - 1;\n% -x(1)^2 + x(2) + 5 ];\n% if nargout > 1\n% J = [1 1 6; -2*x(1) 1 0];\n% end\n% end\n% problem = struct( ...\n% 'fcn', @(x)f1p(x), ...\n% 'x0', [-1; 0; 0], ...\n% 'opt', struct('verbose', 2, 'adapt_step', 1, 'step_max', 10) ...\n% );\n% [x, f, exitflag, output, jac] = pnes_master(problem);\n%\n% See also PNE_CALLBACK_DEFAULT, PNE_REGISTER_CALLBACKS, PNE_REGISTER_EVENTS\n\n% MP-Opt-Model\n% Copyright (c) 2013-2021, Power Systems Engineering Research Center (PSERC)\n% by Ray Zimmerman, PSERC Cornell,\n% Shrirang Abhyankar, Argonne National Laboratory,\n% and Alexander Flueck, IIT\n%\n% This file is part of MP-Opt-Model.\n% Covered by the 3-clause BSD License (see LICENSE file for details).\n% See https://github.com/MATPOWER/mp-opt-model for more info.\n\n%%----- input argument handling -----\n%% gather inputs\nif nargin == 1 && isstruct(fcn) %% problem struct\n p = fcn;\n fcn = p.fcn;\n x0 = p.x0;\n if isfield(p, 'opt'), opt = p.opt; else, opt = struct(); end\nelse %% individual args\n if nargin < 3\n opt = struct();\n end\nend\n\n%% default options\nif isfield(opt, 'verbose') && opt.verbose > 4\n nleqs_opt_verbose = 2;\nelse\n nleqs_opt_verbose = 0;\nend\ndopts = struct( ...\n 'alg', 'DEFAULT', ... %% algorithm\n 'verbose', 0, ...\n 'nleqs_opt', struct('verbose', nleqs_opt_verbose), ...\n 'solve_base', 1, ... %% run corrector for initial point\n 'parameterization', 3, ... %% 1 - natural, 2 - arc len, 3 - pseudo arc len\n 'stop_at', 'NOSE', ... %% 'NOSE', 'FULL', \n 'max_it', 2000, ... %% maximum number of continuation steps\n 'step', 0.05, ... %% continuation step size\n 'step_min', 1e-4, ... %% minimum allowed step size\n 'step_max', 0.2, ... %% maximum allowed step size\n 'adapt_step', 0, ... %% 0/1 toggle, adaptive step size\n 'adapt_step_ws', 1, ... %% warm start inital step size scale factor\n 'adapt_step_damping', 0.7, ... %% adaptive step sizing damping factor\n 'adapt_step_tol', 1e-3, ... %% adaptive step sizing tolerance\n 'default_event_tol',1e-3, ... %% default event function tolerance\n 'target_lam_tol', 0, ... %% event function tolerance for TARGET_LAM event\n 'nose_tol', 0, ... %% event function tolerance for NOSE event\n 'events', {{}}, ... %% user-defined event detection functions\n 'callbacks', {{}}, ... %% user-defined callback functions\n 'output_fcn', [], ... %% custom output fcn, default callback\n 'warmstart', [], ... %% struct containing warm-start state\n 'plot', struct( ... %% used by pne_callback_default() for plotting\n 'level', 0, ... %% 0 - no plot, 1 - final, 2 - steps, 3 - steps w/pause\n 'idx', [], ... %% index of quantity to plot, passed to yfcn()\n 'idx_default', [], ... %% fcn to provide default value for idx, if none provided\n 'xfcn', [], ... %% fcn to compute x-coord from data\n 'yfcn', [], ... %% fcn to compute x-coord from data, idx\n 'title', 'Value of Variable %d', ... %% plot title for single var plot\n 'title2', 'Value of Multiple Variables', ... %% plot title for multiple var plot\n 'xname', 'lam', ... %% name of output field holding x vals\n 'yname', 'x', ... %% name of output field holding y vals\n 'xlabel', '\\lambda', ... %% horizontal axis label\n 'ylabel', 'Variable Value', ... %% vertical axis label\n 'legend', 'Variable %d' ... %% legend label\n ) ...\n);\nopt = nested_struct_copy(dopts, opt);\n%% use opt.default_event_tol for NOSE and TARGET_LAM events, unless specified\nif opt.target_lam_tol == 0\n opt.target_lam_tol = opt.default_event_tol;\nend\nif opt.nose_tol == 0\n opt.nose_tol = opt.default_event_tol;\nend\nif opt.max_it == 0 %% zero means use the default\n opt.max_it == dopts.max_it; \nend\n\n%% initialize\nwarmstarted = ~isempty(opt.warmstart);\ns = struct( ... %% container struct for various variables, flags\n 'done', 0, ... %% flag indicating continuation has terminated\n 'done_msg', '', ... %% termination message\n 'warmstart',[], ... %% warm start state to return when done (to pass\n ...%% to subsequent warm-started call to PNES_MASTER)\n 'rollback', 0, ... %% flag to indicate a step must be rolled back\n 'events', [], ... %% struct array for detected events\n 'results', [] ); %% results struct\n\n%% register event and callback functions\nswitch opt.stop_at\n case 'NOSE'\n my_events = {{'NOSE', @pne_event_nose, opt.nose_tol}, opt.events{:}};\n my_cbacks = {{@pne_callback_nose, 51}, opt.callbacks{:}};\n case 'FULL'\n my_events = {{'TARGET_LAM', @pne_event_target_lam, opt.target_lam_tol}, opt.events{:}};\n my_cbacks = {{@pne_callback_target_lam, 50}, opt.callbacks{:}};\n otherwise %% numeric, stop at target lam or nose point, whichever is 1st\n my_events = {{'TARGET_LAM', @pne_event_target_lam, opt.target_lam_tol}, ...\n {'NOSE', @pne_event_nose, opt.nose_tol}, ...\n opt.events{:}};\n my_cbacks = {{@pne_callback_target_lam, 50}, ...\n {@pne_callback_nose, 51}, ...\n opt.callbacks{:}};\nend\nmy_cbacks{end+1} = {@pne_callback_default, 0};\nreg_ev = pne_register_events(my_events, opt); %% registered event functions\nreg_cb = pne_register_callbacks(my_cbacks); %% registered callback functions\nnef = length(reg_ev); %% number of registered event functions\nncb = length(reg_cb); %% number of registered callback functions\n\n%% initialize continuation step counter\nif warmstarted\n cont_steps = opt.warmstart.cont_steps + 1;\n if opt.verbose\n fprintf('... CONTINUATION RESUMED\\n');\n end\nelse\n cont_steps = 0;\n if opt.verbose\n v = mpomver('all');\n fprintf('\\nMP-Opt-Model Version %s, %s', v.Version, v.Date);\n fprintf(' -- Predictor/Corrector Continuation Method\\n');\n end\nend\n\n%% solve corrector step for base point\nif opt.solve_base && ~warmstarted\n cfcn = @(xx)pne_corrector_fcn(xx, fcn, @pne_pfcn_natural, x0, 0, []);\n [x, f, exitflag, out] = nleqs_master(cfcn, x0, opt.nleqs_opt);\n if exitflag\n if opt.verbose > 1\n fprintf('step %3d : lambda = %6.3f, %2d corrector steps\\n', cont_steps, x0(end), out.iterations);\n end\n else\n s.done = 1;\n s.done_msg = sprintf('base solution did not converge in %d iterations', out.iterations);\n if opt.verbose\n fprintf('%s\\n', s.done_msg);\n end\n end\nelse\n x = x0; %% ignored for warmstart, overwritten by warmstart.cx\nend\n\n%% initialize numerical continuation\nif ~s.done\n locating = 0; %% flag to indicate that an event interval was detected,\n %% but the event has not yet been located\n rb_cnt_ef = 0; %% counter for rollback steps triggered by event function intervals\n rb_cnt_cb = 0; %% counter for rollback steps triggered directly by callbacks\n\n if warmstarted\n manual_direction_switch = 0; %% set to 1 to manually prompt for\n %% direction change upon warmstart\n ws = opt.warmstart;\n x = ws.x; %% starting value solution vector\n z = ws.z; %% starting value of tangent vector\n step = 0; %% re-solve current point\n parm = ws.parm;\n direction = ws.direction;\n default_parm = ws.default_parm;\n default_step = ws.default_step;\n cbs = ws.cbs;\n event_log = ws.events;\n if manual_direction_switch\n %% decide whether to switch directions\n reply = input('Switch directions? Y/N [N]:','s');\n if strcmp(upper(reply), 'Y')\n direction = -direction;\n end\n elseif isfield(ws, 'dir_from_jac_eigs') && ws.dir_from_jac_eigs\n %% attempt to determine direction from smalles Jacobian eigenvalue\n [~, J] = fcn(x);\n eigs_opt.tol = 1e-3;\n eigs_opt.maxit = 2*length(x);\n direction = sign(z(end) * ...\n min(real(eigs(J(:,1:end-1), 1, 'sr', eigs_opt))));\n end\n\n if opt.adapt_step %% hey, maybe slow down, things might have changed\n default_step = default_step * opt.adapt_step_ws;\n end\n else\n %% initialize parameterization function\n switch opt.parameterization\n case 1\n parm = @pne_pfcn_natural; %% NAT\n case 2\n parm = @pne_pfcn_arc_len; %% ARC\n case 3\n parm = @pne_pfcn_pseudo_arc_len; %% PAL\n otherwise\n error('pnes_master: OPT.parameterization (= %d) must be 1, 2, or 3', opt.parameterization);\n end\n\n %% finish initializing tangent vector\n direction = 1;\n z0 = zeros(length(x), 1); z0(end) = direction; %% +ve lambda direction\n z = pne_tangent(x, x, z0, fcn, parm, direction);\n\n step = opt.step;\n default_step = step;\n default_parm = parm;\n cbs = [];\n event_log = [];\n end\n\n %% initialize state struct for current continuation step\n cx = struct( ... %% current state\n 'x_hat', x, ... %% predicted solution value\n 'x', x, ... %% corrected solution value\n 'z', z, ... %% normalized tangent vector\n 'default_step', default_step, ... %% default step size\n 'default_parm', default_parm, ... %% default parameterization\n 'this_step', [], ... %% step size for this step only\n 'this_parm', [], ... %% parameterization for this step only\n 'step', step, ... %% current step size\n 'parm', parm, ... %% current parameterization\n 'events', event_log, ... %% event log\n 'cbs', cbs, ... %% user-defined callback state\n 'efv', [] ... %% event function values\n );\n\n %% initialize event function values\n cx.efv = cell(nef, 1);\n for k = 1:nef\n cx.efv{k} = reg_ev(k).fcn(cx, opt);\n end\n\n if warmstarted %% no need to initialize callbacks\n %% initialize state for previous continuation step\n px = cx;\n px.x = ws.xp; %% use warm start value for solution value\n px.z = ws.zp; %% use warm start value for tangent\n else\n %% invoke callbacks - \"initialize\" context\n for k = 1:ncb\n [nx, cx, s] = reg_cb(k).fcn(cont_steps, cx, cx, cx, s, opt);\n end\n cont_steps = cont_steps + 1;\n\n %% check for case with base and target the same\n %% evaluate function at lambda = 0 (base)\n if opt.solve_base\n fb = f(1:end-1);\n else\n fb = fcn(x);\n exitflag = 1;\n end\n\n %% evaluate function at lambda = 1 (target)\n xt = x;\n xt(end) = 1;\n ft = fcn(xt);\n if norm(fb - ft, Inf) < 1e-12\n s.done = 1;\n s.done_msg = 'base and target functions are identical';\n end\n\n %% initialize state for previous continuation step\n px = cx;\n end\nend\n\n%%----- run numerical continuation -----\nwhile ~s.done\n %% initialize next candidate with current state\n nx = cx;\n\n %% predictor step\n nx.x_hat = cx.x + cx.step * cx.z;\n\n %% corrector step\n cfcn = @(xx)pne_corrector_fcn(xx, fcn, cx.parm, cx.x, cx.step, cx.z);\n [nx.x, f, exitflag, out] = nleqs_master(cfcn, nx.x_hat, opt.nleqs_opt);\n if ~exitflag %% corrector failed\n s.done = 1;\n s.done_msg = sprintf('Corrector did not converge in %d iterations.', out.iterations);\n if opt.verbose\n fprintf('step %3d : %s stepsize = %-9.3g lambda = %6.3f corrector did not converge in %d iterations\\n', cont_steps, pne_ptag(cx.parm), cx.step, nx.x(end), out.iterations);\n end\n cont_steps = max(cont_steps - 1, 1); %% go back to last step, but not to 0\n break;\n end\n\n %% compute new tangent direction, based on current or prev state: tx\n if nx.step == 0 %% if this is a re-do step, cx and nx are the same\n tx = px; %% so use px as the previous state\n else %% otherwise\n tx = cx; %% use cx as the previous state\n end\n nx.z = pne_tangent(nx.x, tx.x, tx.z, fcn, nx.parm, direction);\n direction = 1; %% continue in same direction\n\n %% detect events\n for k = 1:nef\n nx.efv{k} = reg_ev(k).fcn(nx, opt); %% update event function values\n end\n [s.rollback, s.events, nx.efv] = ...\n pne_detect_events(reg_ev, nx.efv, cx.efv, nx.step);\n\n %% adjust step-size to locate event function zero, if necessary\n if s.rollback %% current step overshot\n %% roll back & initialize next step size based on rollback and previous\n rx = nx; %% save state we're rolling back from\n rx_evnts = s.events; %% and critical event info\n cx.this_step = s.events.step_scale * rx.step;\n cx.this_parm = rx.parm; %% keep same parameterization as last step\n locating = 1; %% enter \"locating\" mode (or stay in it)\n rb_cnt_ef = rb_cnt_ef + 1; %% increment rollback counter for ef intervals\n if rb_cnt_ef > 26\n s.done = 1;\n s.done_msg = sprintf('Could not locate %s event!', s.events.name);\n end\n if opt.verbose > 3\n loc_msg = sprintf('OVERSHOOT : f = [%g, <<%g>>], step <-- %.4g', ...\n cx.efv{s.events.eidx}(s.events.idx(1)), ...\n rx.efv{s.events.eidx}(s.events.idx(1)), cx.this_step);\n end\n elseif locating\n if s.events(1).zero %% found the zero!\n %% step size will be reset to previously used default step size\n locating = 0; %% exit \"locating\" mode\n rb_cnt_ef = 0; %% reset rollback counter for ef intervals\n if opt.verbose > 3\n loc_msg = sprintf('ZERO! : f = %g, step <-- %.4g', ...\n nx.efv{rx_evnts.eidx}(rx_evnts.idx(1)), nx.default_step);\n end\n else %% prev rollback undershot\n %% initialize next step size based on critical event function\n %% values from prev rollback step and current step\n rx_efv = rx.efv{rx_evnts.eidx}(rx_evnts.idx(1));\n cx_efv = nx.efv{rx_evnts.eidx}(rx_evnts.idx(1));\n step_scale = cx_efv / (cx_efv - rx_efv);\n nx.this_step = step_scale * (rx.step - nx.step);\n rb_cnt_ef = 0; %% reset rollback counter for ef intervals\n if opt.verbose > 3\n loc_msg = sprintf('UNDERSHOOT : f [<<%g>>, %g], step <-- %.4g', ...\n cx_efv, rx_efv, nx.this_step);\n end\n end\n else %% normal step, not locating anything\n loc_msg = '';\n end\n\n %% invoke callbacks - \"iterations\" context\n rb = s.rollback;\n for k = 1:ncb\n [nx, cx, s] = reg_cb(k).fcn(cont_steps, nx, cx, px, s, opt);\n end\n if ~rb && s.rollback %% rollback triggered by callback (vs event function interval)\n rb_cnt_cb = rb_cnt_cb + 1; %% increment rollback counter for callbacks\n if rb_cnt_cb > 26\n s.done = 1;\n s.done_msg = 'Too many rollback steps triggered by callbacks!';\n end\n else\n rb_cnt_cb = 0; %% reset rollback counter for callbacks\n end\n\n %% print iteration information\n if opt.verbose > 1\n %% set label for rollback step counter\n if rb_cnt_ef\n sub_step = char('a' + rb_cnt_ef - 1);\n elseif rb_cnt_cb\n sub_step = char('A' + rb_cnt_cb - 1);\n else\n sub_step = ' ';\n end\n\n fprintf('step %3d%s : %s stepsize = %-9.3g lambda = %6.3f', cont_steps, sub_step, pne_ptag(cx.parm), cx.step, nx.x(end));\n if opt.verbose < 5\n fprintf(' %2d corrector steps', out.iterations);\n end\n if s.rollback\n fprintf(' ^ ROLLBACK\\n');\n else\n fprintf('\\n');\n end\n if opt.verbose > 3 && ~isempty(loc_msg)\n fprintf(' LOCATING -- %s\\n', loc_msg);\n end\n end\n\n %% log events\n for k = 1:length(s.events)\n if s.events(k).log\n e = struct( 'k', cont_steps, ...\n 'name', s.events(k).name, ...\n 'idx', s.events(k).idx, ...\n 'msg', s.events(k).msg );\n if isempty(nx.events)\n nx.events = e;\n else\n nx.events(end+1) = e;\n end\n end\n if (opt.verbose > 2 && s.events(k).log) || ...\n (opt.verbose > 3 && s.events(k).eidx)\n fprintf(' %s\\n', s.events(k).msg);\n end\n end\n\n %% adapt stepsize if requested and not terminating, locating a zero\n %% or warm starting\n if opt.adapt_step && ~s.done && ~locating && ~s.events(1).zero && nx.step ~= 0\n pred_error = norm(nx.x - nx.x_hat, Inf);\n\n %% new nominal step size is current size * tol/err, but we reduce\n %% the change from the current size by a damping factor and limit\n %% increases to a factor of 2\n step_scale = min(2, 1 + opt.adapt_step_damping * ...\n (opt.adapt_step_tol/pred_error - 1));\n nx.default_step = nx.step * step_scale;\n\n %% limit step-size\n if nx.default_step > opt.step_max\n nx.default_step = opt.step_max;\n end\n if nx.default_step < opt.step_min\n nx.default_step = opt.step_min;\n end\n end\n\n %% if this is a normal step\n if ~s.rollback\n px = cx; %% save current state before update\n cx = nx; %% update current state to next candidate\n if ~s.done\n if cont_steps >= opt.max_it\n s.done = 1;\n s.done_msg = sprintf('Reached maximun number of continuation steps (opt.max_it = %d)', opt.max_it);\n else\n cont_steps = cont_steps + 1;\n end\n end\n end\n\n %% set step size and parameterization, from one-time or defaults\n if isempty(cx.this_step)\n cx.step = cx.default_step;\n else\n cx.step = cx.this_step;\n cx.this_step = []; %% disable for next time\n end\n if isempty(cx.this_parm)\n cx.parm = cx.default_parm;\n else\n cx.parm = cx.this_parm;\n cx.this_parm = []; %% disable for next time\n end\nend %% while ~s.done\n\n%% invoke callbacks - \"final\" context\ns.results = struct(); %% initialize results struct\nfor k = 1:ncb\n [nx, cx, s] = reg_cb(k).fcn(-cont_steps, nx, cx, px, s, opt);\nend\noutput = s.results;\noutput.done_msg = s.done_msg;\noutput.events = cx.events; %% copy eventlog to results\noutput.corrector = out; %% output from last corrector run\n\n%% prepare to exit\nif isempty(s.warmstart)\n if opt.verbose\n fprintf('CONTINUATION TERMINATION: %s\\n', s.done_msg);\n end\nelse\n %% save warmstart values\n ws = s.warmstart;\n ws.cont_steps = cont_steps;\n ws.direction = direction;\n\n %% from state at current step\n ws.x = cx.x; %% state from current step\n ws.z = cx.z; %% tangent vector from current step\n ws.parm = cx.parm;\n ws.default_parm = cx.default_parm;\n ws.default_step = cx.default_step;\n ws.events = cx.events;\n ws.cbs = cx.cbs;\n\n %% from state at previous step\n ws.xp = px.x; %% state from previous step\n ws.zp = px.z; %% tangent vector from previous step\n\n output.warmstart = ws;\n\n if opt.verbose\n fprintf('%s : CONTINUATION SUSPENDED ...\\n', s.done_msg);\n end\nend\n\n%% output arguments\nif nargout > 4\n [f, J] = fcn(cx.x);\nelseif nargout > 1\n f = fcn(cx.x);\nend\nvarargout{1} = cx.x;\nif nargout > 1\n varargout{2} = f;\n if nargout > 2\n varargout{3} = exitflag;\n if nargout > 3\n varargout{4} = output;\n if nargout > 4\n varargout{5} = J;\n end\n end\n end\nend\n\n\n%%----- pne_corrector_fcn -----\n%% fcn(x) combined with parameterization constraint\nfunction [fp, dfp] = pne_corrector_fcn(x, fcn, parm, cx_x, step, z)\nif nargout < 2\n fp = [ fcn(x); parm(x, cx_x, step, z) ];\nelse\n [f, df] = fcn(x);\n [p, dp] = parm(x, cx_x, step, z);\n fp = [f; p];\n dfp = [df; dp];\nend\n\n\n%%----- pne_tangent -----\n%% find normalized tangent vector\nfunction z = pne_tangent(x, xp, zp, fcn, parm, direction)\n[f, df] = fcn(x);\n[p, dp] = parm(x, xp, 0, zp);\nrhs = [ zeros(length(f), 1); direction ];\nz = [df; dp] \\ rhs;\nz = z / norm(z); %% normalize it\n\n\n%%----- pne_ptag -----\n%% return 3-letter string to indicate parameterization scheme\n%% NAT - natural, ARC - arc length, PAL - pseudo arc length\nfunction ptag = pne_ptag(parm)\nswitch func2str(parm)\n case 'pne_pfcn_natural'\n ptag = 'NAT';\n case 'pne_pfcn_arc_len'\n ptag = 'ARC';\n case 'pne_pfcn_pseudo_arc_len'\n ptag = 'PAL';\nend\n", "meta": {"author": "MATPOWER", "repo": "matpower", "sha": "7da926d978824bf675a71e0a5cb91f8967f97007", "save_path": "github-repos/MATLAB/MATPOWER-matpower", "path": "github-repos/MATLAB/MATPOWER-matpower/matpower-7da926d978824bf675a71e0a5cb91f8967f97007/mp-opt-model/lib/pnes_master.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146848, "lm_q2_score": 0.6825737214979745, "lm_q1q2_score": 0.5499033677622486}} {"text": "function numLS=leapSecsOnDay(year,month,day)\n%%LEAPSECSONDAY Returns the number of leap seconds in a day for dates from\n% 1972 onward. Prior to 1972, non-integer leap second numbers\n% were used, meaning that the time of day matters. From 1972\n% onward, one could have a positive or negative leap second,\n% meaning that the last minute of the day in coordinated\n% universal time (UTC) might contain 59 or 61 seconds.\n%\n%INPUTS: year An integer year in the Gregorian calendar under UTC\n% time. year>= 1960 when UTC started.\n% month An integer month in the Gregorian calendar under UTC\n% time. 1<=month<=12\n% day An integer day in the Gregorian calendar under UTC\n% time. Days count from 1.\n%\n%OUTPUTS: numLS The number of leap seconds on the given day. This can be\n% 0, -1, or 1.\n%\n%This function calls the cumLeapSec function for the day in question and\n%for one day later to see what the difference is. The function cumLeapSec\n%relies on iaudat in the International Astronomical Union's (IAU)\n%Standard's of Fundamental Astronomy library. Note that leap second\n%information is not available for future dates as they can not be\n%accurately predicted.\n%\n%March 2014 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\n if(year<1972)\n error('Dates before 1972 have a more complicated leap second methodology than is used here');\n end\n\n%Determine the number of leap on the date.\n numSec=cumLeapSec(year,month,day);\n [Jul1,Jul2]=Cal2UTC(year,month,day,0,0,0);\n %Advance the UTC day count by one day.\n Jul1=Jul1+1;\n [year,month,day]=UTC2Cal(Jul1,Jul2,true);\n %Determine the number of leap seconds on day later.\n numSecNextDay=cumLeapSec(year,month,day);\n \n numLS=numSecNextDay-numSec;\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/leapSecsOnDay.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.5498439211344094}} {"text": "function rnrb = nrbreverse(nrb) \n% \n% Function Name: \n% \n% nrbreverse - Reverse the evaluation direction of a NURBS curve or surface. \n% \n% Calling Sequence: \n% \n% rnrb = nrbreverse(nrb); \n% \n% Parameters: \n% \n% nrb\t\t: NURBS data structure, see nrbmak. \n% \n% rnrb\t\t: Reversed NURBS. \n% \n% Description: \n% \n% Utility function to reverse the evaluation direction of a NURBS \n% curve or surface. \n \n% D.M. Spink \n% Copyright (c) 2000. \n \nif nargin ~= 1 \n error('Incorrect number of input arguments'); \nend \n \nif iscell(nrb.knots) \n \n % reverse a NURBS surface \n coefs = nrb.coefs(:,:,end:-1:1); \n rnrb = nrbmak(coefs(:,end:-1:1,:), {1.0-fliplr(nrb.knots{1}),... \n 1.0-fliplr(nrb.knots{2})}); \n \nelse \n \n % reverse a NURBS curve \n rnrb = nrbmak(fliplr(nrb.coefs), 1.0-fliplr(nrb.knots)); \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/26390-nurbs-toolbox-by-d-m-spink/nurbs_toolbox/nrbreverse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.7025300449389326, "lm_q1q2_score": 0.5498439065108236}} {"text": "function mpc = case15da\n%CASE15DA Power flow data for 15 bus distribution system from Das, et al\n% Please see CASEFORMAT for details on the case file format.\n%\n% Data from ...\n% Das D, Kothari DP, Kalam A (1995) Simple and efficient method for load\n% flow solution of radial distribution networks. Int J Electr Power\n% Energy Syst 17:335-346. doi: 10.1016/0142-0615(95)00050-0\n% URL: https://doi.org/10.1016/0142-0615(95)00050-0\n\n%% MATPOWER Case Format : Version 2\nmpc.version = '2';\n\n%%----- Power Flow Data -----%%\n%% system MVA base\nmpc.baseMVA = 1;\n\n%% bus data\n%\tbus_i\ttype\tPd\tQd\tGs\tBs\tarea\tVm\tVa\tbaseKV\tzone\tVmax\tVmin\nmpc.bus = [ %% (Pd and Qd are specified in kW & kVAr here, converted to MW & MVAr below)\n\t1\t3\t0\t0\t0\t0\t1\t1\t0\t11\t1\t1\t1;\n\t2\t1\t44.1\t44.991\t0\t0\t1\t1\t0\t11\t1\t1.1\t0.9;\n\t3\t1\t70\t71.4143\t0\t0\t1\t1\t0\t11\t1\t1.1\t0.9;\n\t4\t1\t140\t142.8286\t0\t0\t1\t1\t0\t11\t1\t1.1\t0.9;\n\t5\t1\t44.1\t44.991\t0\t0\t1\t1\t0\t11\t1\t1.1\t0.9;\n\t6\t1\t140\t142.8286\t0\t0\t1\t1\t0\t11\t1\t1.1\t0.9;\n\t7\t1\t140\t142.8286\t0\t0\t1\t1\t0\t11\t1\t1.1\t0.9;\n\t8\t1\t70\t71.4143\t0\t0\t1\t1\t0\t11\t1\t1.1\t0.9;\n\t9\t1\t70\t71.4143\t0\t0\t1\t1\t0\t11\t1\t1.1\t0.9;\n\t10\t1\t44.1\t44.991\t0\t0\t1\t1\t0\t11\t1\t1.1\t0.9;\n\t11\t1\t140\t142.8286\t0\t0\t1\t1\t0\t11\t1\t1.1\t0.9;\n\t12\t1\t70\t71.4143\t0\t0\t1\t1\t0\t11\t1\t1.1\t0.9;\n\t13\t1\t44.1\t44.991\t0\t0\t1\t1\t0\t11\t1\t1.1\t0.9;\n\t14\t1\t70\t71.4143\t0\t0\t1\t1\t0\t11\t1\t1.1\t0.9;\n\t15\t1\t140\t142.8286\t0\t0\t1\t1\t0\t11\t1\t1.1\t0.9;\n];\n\n%% generator data\n%\tbus\tPg\tQg\tQmax\tQmin\tVg\tmBase\tstatus\tPmax\tPmin\tPc1\tPc2\tQc1min\tQc1max\tQc2min\tQc2max\tramp_agc\tramp_10\tramp_30\tramp_q\tapf\nmpc.gen = [\n\t1\t0\t0\t10\t-10\t1\t100\t1\t10\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n];\n\n%% branch data\n%\tfbus\ttbus\tr\tx\tb\trateA\trateB\trateC\tratio\tangle\tstatus\tangmin\tangmax\nmpc.branch = [ %% (r and x specified in ohms here, converted to p.u. below)\n\t1\t2\t1.35309\t1.32349\t0\t0\t0\t0\t0\t0\t1\t-360\t360;\n\t2\t3\t1.17024\t1.14464\t0\t0\t0\t0\t0\t0\t1\t-360\t360;\n\t3\t4\t0.84111\t0.82271\t0\t0\t0\t0\t0\t0\t1\t-360\t360;\n\t4\t5\t1.52348\t1.0276\t0\t0\t0\t0\t0\t0\t1\t-360\t360;\n\t2\t9\t2.01317\t1.3579\t0\t0\t0\t0\t0\t0\t1\t-360\t360;\n\t9\t10\t1.68671\t1.1377\t0\t0\t0\t0\t0\t0\t1\t-360\t360;\n\t2\t6\t2.55727\t1.7249\t0\t0\t0\t0\t0\t0\t1\t-360\t360;\n\t6\t7\t1.0882\t0.734\t0\t0\t0\t0\t0\t0\t1\t-360\t360;\n\t6\t8\t1.25143\t0.8441\t0\t0\t0\t0\t0\t0\t1\t-360\t360;\n\t3\t11\t1.79553\t1.2111\t0\t0\t0\t0\t0\t0\t1\t-360\t360;\n\t11\t12\t2.44845\t1.6515\t0\t0\t0\t0\t0\t0\t1\t-360\t360;\n\t12\t13\t2.01317\t1.3579\t0\t0\t0\t0\t0\t0\t1\t-360\t360;\n\t4\t14\t2.23081\t1.5047\t0\t0\t0\t0\t0\t0\t1\t-360\t360;\n\t4\t15\t1.19702\t0.8074\t0\t0\t0\t0\t0\t0\t1\t-360\t360;\n];\n\n%%----- OPF Data -----%%\n%% generator cost data\n%\t1\tstartup\tshutdown\tn\tx1\ty1\t...\txn\tyn\n%\t2\tstartup\tshutdown\tn\tc(n-1)\t...\tc0\nmpc.gencost = [\n\t2\t0\t0\t3\t0\t20\t0;\n];\n\n\n%% convert branch impedances from Ohms to p.u.\n[PQ, PV, REF, NONE, BUS_I, BUS_TYPE, PD, QD, GS, BS, BUS_AREA, VM, ...\n VA, BASE_KV, ZONE, VMAX, VMIN, LAM_P, LAM_Q, MU_VMAX, MU_VMIN] = idx_bus;\n[F_BUS, T_BUS, BR_R, BR_X, BR_B, RATE_A, RATE_B, RATE_C, ...\n TAP, SHIFT, BR_STATUS, PF, QF, PT, QT, MU_SF, MU_ST, ...\n ANGMIN, ANGMAX, MU_ANGMIN, MU_ANGMAX] = idx_brch;\nVbase = mpc.bus(1, BASE_KV) * 1e3; %% in Volts\nSbase = mpc.baseMVA * 1e6; %% in VA\nmpc.branch(:, [BR_R BR_X]) = mpc.branch(:, [BR_R BR_X]) / (Vbase^2 / Sbase);\n\n%% convert loads from kW to MW\nmpc.bus(:, [PD, QD]) = mpc.bus(:, [PD, QD]) / 1e3;\n", "meta": {"author": "MATPOWER", "repo": "matpower", "sha": "7da926d978824bf675a71e0a5cb91f8967f97007", "save_path": "github-repos/MATLAB/MATPOWER-matpower", "path": "github-repos/MATLAB/MATPOWER-matpower/matpower-7da926d978824bf675a71e0a5cb91f8967f97007/data/case15da.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624688140726, "lm_q2_score": 0.7025300511670689, "lm_q1q2_score": 0.549843904262495}} {"text": "%nav formulas on a (non rotating flat earth)\n%vtyp==0->n frame vel, vtyp==1->b frame vel\nfunction [Cbn_new, Vx_new, pos_new]=strapdown_pln_dcm(Cbn, Vx, pos, a, w, g, dt, vtyp)\n\n%%%Update attitude\n%Part I:Body frame update\nrot=w*dt;\nrot_norm=norm(rot);\nsr_a=1-(rot_norm^2/6)+(rot_norm^4/120);\nsr_b=(1/2)-(rot_norm^2/24)+(rot_norm^4/720);\nmx_a=eye(3)+sr_a*skew(rot)+sr_b*skew(rot)*skew(rot);\n\nCbn_new=Cbn*mx_a;\n\n%%Update Velocity and position\nif (vtyp==0) %vel in n frame\n vel_inc=(Cbn*(a*dt))+[0;0;g]*dt;\n Vx_new=Vx+vel_inc;\n \n pos_new=pos+Vx*dt;\nelseif (vtyp==1) %vel in b frame\n vel_inc1=(a+(Cbn'*[0;0;g]))*dt;\n vel_inc2=(cross(Vx,w))*dt;\n Vx_new=Vx+vel_inc1+vel_inc2;\n \n pos_new=pos+Cbn*Vx*dt;\nend", "meta": {"author": "JzHuai0108", "repo": "ekfmonoslam", "sha": "443f6be744732453cdb90679abcaf5c962a6295e", "save_path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam", "path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam/ekfmonoslam-443f6be744732453cdb90679abcaf5c962a6295e/instk/INS/strapdown_pln_dcm_v000.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213772699435, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.5497066018662529}} {"text": "%*****************************************************************************\n% DSDP5: Dual Scaling Algorithm for Positive Semidefinite Programming\n% Copyright (c) 2002 by\n% S. J. Benson, Y. Ye\n% Last modified: 20 January 2004\n%*****************************************************************************\n%\n% Converts data from DSDP4 format to DSDP5 format, calls solver, and \n% and converts solution to DSDP4 format.\n%\n%\n% > DSDP(A,C,b) attempts to solve the positive semidefinite program\n% MINIMIZE trace(C*X) SUCH THAT trace(A_i*X) = b_i, i=1,...,m and X >= 0\n% using a dual scaling algorithm. For a problem with p blocks and m\n% constraints, A is a p x m cell array and C is a p x 1 cell array.\n% One block may contain LP variables, and the cells corresponding to\n% this block should be a one dimensional array. All other cells\n% must contain a square, symmetric, real valued matrix. The third \n% argument b is a dense column vector of length m. \n%\n% > DSDP(A,C,b,OPTIONS,y0) specifies an initial dual vector y0.\n%\n% > [STAT,y,X] = DSDP() returns a structure containing relevant statistics, \n% and approximate dual and primal solutions. \n%\n%*****************************************************************************\n\nfunction [STAT,y,XX] = dsdp4(A,C,b,OPTIONS,y0);\n\n p=length(C);\n m=length(b);\n\n AC=cell(p,3);\n for j=1:p,\n [n1,n2]=size(C{j});\n if (n1==1 | n2==1)\n AAC=sparse(n1*n2,m+1);\n for i=1:m, AAC=[AAC sparse(A{j,i})']; end;\n AAC=[AAC sparse(C{j})'];\n AC{j,1}='LP';\n AC{j,2}=length(C{j});\n AC{j,3}=AAC;\n else\n AAC=sparse(n1*(n1+1)/2,m+1);\n for i=1:m, AAC=[AAC dvec(A{j,i})]; end;\n AAC=[AAC dvec(C{j})];\n AC{j,1}='SDP';\n AC{j,2}=size(C{j},1);\n AC{j,3}=AAC;\n end;\n end;\n\n [STAT,y,X]=dsdp(b,AC,OPTIONS,y0);\n\n XX=cell(p,1);\n for j=1:p,\n [n1,n2]=size(C{j})\n if (n1==1 | n2==1)\n XX{j}=X{j};\n else\n XX{j}=dmat(X{j});\n end;\n end;\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/OptiToolbox/Solvers/dsdp/distribution/matlab/dsdp4.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.6513548782017746, "lm_q1q2_score": 0.5496751968539833}} {"text": "function [gx,dgdx,dgdp] = g_classif0(x,P,u,in)\n% logistic-like observation function for VBA_classification\n% function [gx,dgdx,dgdp] = g_classif0(x,P,u,in)\n% IN:\n% - x: [useless]\n% - P: classification weights\n% - u: [useless]\n% - in: contains design matrix (in.X) and sparsify flag (in.sparse)\n% OUT:\n% - gx: E[y|P]\n% - dgdx: [useless]\n% - dgdp: gradient of E[y|P] wrt P.\n\nif in.sparse\n [sP, dsdP] = VBA_sparsifyPrior(P); \nelse\n sP = P;\nend\ngx = sss(in.X'*sP);\ndgdx = [];\ndgdp = diag(gx.*(1-gx))*in.X';\ndgdp = dgdp';\nif in.sparse % for exploiting the analytical gradients from g_GLM\n dgdp = dsdP*dgdp;\nend\n\nfunction sx = sss(x)\nsx = 1./(1+exp(-x));\nsx(sx < 1e-8) = 1e-8;\nsx(sx > 1-1e-8) = 1-1e-8;\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/g_classif0.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.5496751854312549}} {"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 [Index SubIndex]=GetGridIndex(particle,G)\n\n c=particle.Cost;\n \n nobj=numel(c);\n ngrid=numel(G(1).Upper);\n \n str=['sub2ind(' mat2str(ones(1,nobj)*ngrid)];\n\n SubIndex=zeros(1,nobj);\n for j=1:nobj\n \n U=G(j).Upper;\n \n i=find(c(j) \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 = 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 = (1+5*repmat(2:obj.D,size(X,1),1)/obj.D).*X(:,2:obj.D) - repmat(X(:,1),1,obj.D-1);\n g = 1 + 9*mean(t.^2,2);\n PopObj(:,1) = X(:,1);\n PopObj(:,2) = g.*(1-(PopObj(:,1)./g).^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).^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/IMMOEA_F2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.7279754430043072, "lm_q1q2_score": 0.5495595719955524}} {"text": "function [stan,rtfr,hat] = tfrrstan(x,t,N,G,h,trace);\n%TFRRSTAN Reassigned Stankovic distribution.\n%\t[TFR,RTFR,HAT] = TFRRSTAN(X,T,N,H,TRACE) \n%\tcomputes the Stankovic distribution and 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% G : frequency averaging window\n%\th : stft window (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 TFRRSTAN 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 G=tftb_window(9,'hanning'); h=tftb_window(61,'hanning'); tfrrstan(sig,t,128,G,h,1);\n%\n%\tSee also all the time-frequency representations listed in\n%\t the file CONTENTS (TFR*)\n\n%\tF. Auger, August, September 1997.\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 <= 2),\n N=xrow;\nend;\n\nhlength=floor(N/4);\nhlength=hlength+1-rem(hlength,2);\n\nif (nargin == 1),\n t=1:xrow; G=[0.25; 0.5; 0.25]; h = tftb_window(hlength); trace=0;\nelseif (nargin == 2)|(nargin == 3),\n G=[0.25; 0.5; 0.25]; h = tftb_window(hlength); trace=0;\nelseif (nargin == 4),\n h = tftb_window(hlength); trace = 0;\nelseif (nargin == 5),\n trace = 0;\nend;\n\n[Grow,Gcol]=size(G); LG=(Grow-1)/2; \nif (Gcol~=1)|(rem(Grow,2)==0),\n error('G must be a smoothing window with odd length');\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; \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\nstan = zeros(N,tcol); \nrtfr = zeros(N,tcol); \nhat = zeros(N,tcol);\n\nif trace, disp('Stankovic distribution (with reassignement)'); end;\nEx=mean(abs(x(min(t):max(t))).^2); Threshold=1.0e-3*Ex;\nDh=dwindow(h); Th=h.*[-Lh:Lh]';\nfor icol=1:tcol,\n if trace, disprog(icol,tcol,10); end;\n ti= t(icol); \n tau=-min([round(N/2)-1,Lh,ti-1]):min([round(N/2)-1,Lh,xrow-ti]);\n indices= rem(N+tau,N)+1;\n tfr= zeros(N,3); \n tfr(indices,1)=x(ti+tau).*conj( h(Lh+1-tau));\n tfr(indices,2)=x(ti+tau).*conj(Th(Lh+1-tau));\n tfr(indices,3)=x(ti+tau).*conj(Dh(Lh+1-tau));\n tfr=fft(tfr); \n stan(:,icol)=G(LG+1) * abs(tfr(:,1)).^2;\n\n for jcol=1:N,\n stanTh=G(LG+1)*tfr(jcol,1)*conj(tfr(jcol,2));\n stanDh=G(LG+1)*tfr(jcol,1)*conj(tfr(jcol,3));\n for kstan=1:min(N/2-1,LG),\n stanbefore=rem(rem(jcol-kstan-1,N)+N,N)+1;\n stanafter =rem(rem(jcol+kstan-1,N)+N,N)+1;\n stan(jcol,icol)= stan(jcol,icol) ...\n + G(LG+1-kstan)*tfr(stanbefore,1)*conj(tfr(stanafter ,1)) ...\n + G(LG+1+kstan)*tfr(stanafter ,1)*conj(tfr(stanbefore,1));\n stanTh= stanTh + G(LG+1-kstan)*tfr(stanbefore,1)*conj(tfr(stanafter ,2)) ...\n + G(LG+1+kstan)*tfr(stanafter ,1)*conj(tfr(stanbefore,2));\n stanDh= stanDh + G(LG+1-kstan)*tfr(stanbefore,1)*conj(tfr(stanafter ,3)) ...\n + G(LG+1+kstan)*tfr(stanafter ,1)*conj(tfr(stanbefore,3));\n end;\n stan(jcol,icol)=real(stan(jcol,icol));\n if abs(stan(jcol,icol))>Threshold,\n icolhat = round(icol - real(stanTh/stan(jcol,icol))/Dt);\n jcolhat = round(jcol - N*imag(stanDh/stan(jcol,icol)/(2.0*pi)));\n \n jcolhat= rem(rem(jcolhat-1,N)+N,N)+1;\n icolhat= min(max(icolhat,1),tcol);\n \n rtfr(jcolhat,icolhat)=rtfr(jcolhat,icolhat) + stan(jcol,icol) ;\n hat(jcol,icol)= jcolhat + j * icolhat;\n %fprintf('%12.3f %12.3f , %12.3f %12.3f \\n',jcol,icol,jcolhat,icolhat);\n else\n rtfr(jcol,icol)=rtfr(jcol,icol) + stan(jcol,icol);\n hat(jcol,icol)= jcol + j * icol;\n end;\n end;\n\nend ;\n\nif trace, fprintf('\\n'); end;\n\nif (nargout==0),\n TFTBcontinue=1;\n while (TFTBcontinue==1),\n choice=menu ('Choose the representation:',...\n 'stop',...\n 'Stankovic distribution',...\n 'reassigned Stankovic distribution');\n if (choice==1), TFTBcontinue=0;\n elseif (choice==2), \n tfrqview(stan,x,t,'type1');\n elseif (choice==3),\n tfrqview(rtfr,x,t,'type1');\n end;\n end;\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/tfrrstan.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105941403651, "lm_q2_score": 0.6926419894793248, "lm_q1q2_score": 0.5493384771216976}} {"text": "function [c, frec, info] = multidgtrealmp(f,dicts,varargin)\n%MULTIDGTREALMP Matching Pursuit Decomposition with Multi-Gabor Dictionary\n% Usage: c = multidgtrealmp(f,dicts)\n% c = multidgtrealmp(f,dicts,errdb,maxit)\n% [c,frec,info] = multidgtrealmp(...)\n%\n% Input parameters:\n% f : Input signal\n% dicts : Dictionaries. Format {g1,a1,M1,g2,a2,M2,...}\n% errdb : Target normalized approximation error in dB\n% maxit : Maximum number of iterations.\n% Output parameters:\n% c : Sparse representation\n% frec : Reconstructed signal\n% info : Struct with additional output paramerets\n%\n% `multidgtrealmp(f,{g1,a1,M1,g2,a2,M2,...,gW,aW,MW})` returns sparse \n% representation of a signal in `W` Gabor dictionaries using the \n% fast matching pursuit algorithm. `gw` is a Gabor window defined\n% as in |dgt| and |dgtreal|, `aw` is a hop factor, `Mw` is the number of \n% frequency channels. All `aw` and `Mw` must be divisible by `min(a1,...,aW)`.\n% The algorithm will try to reach -40 dB relative approximation error\n% in at most `numel(f)` iterations.\n% The function returns a cell-array with elements storing coefficients\n% for individual Gabor systems such that they can be directly used in\n% |idgtreal|. \n%\n% `multidgtrealmp(f,dicts,errdb,maxit)` tries to reach normalized \n% approximation error *errdb* dB in at most *maxit* iterations.\n%\n% `[c,frec,info] = multidgtrealmp(...)` in addition returns the\n% aproximation *frec* and a struct `info` with the following fields:\n%\n% .iter Number of iterations done.\n%\n% .atoms Number of atoms selected.\n%\n% .relres Final approximation error. If resets are enabled, this is a\n% vector additionally containing the approximation error at \n% every reset.\n%\n% .g Cell array of numeric windows used in the multi-dictionary\n%\n% .a Array of hop factors for indivitual dictionaries\n%\n% .M Array of numbers of channels for individual dictionaries\n%\n% .synthetize Anonymous function which can be used to synthetize from\n% the (modified) coefficients as \n% `frec = sum(info.synthetize(c),dim)`\n% where `dim=2` if the input *f* was a column vector and\n% `dim=1` if it was a row vector. \n%\n% The normalized approximation error is computed as \n% `errdb=20*log10(norm(f-frec)/norm(f))`.\n%\n% The function takes the following optional parameters at the end of\n% the line of input arguments:\n%\n% 'kenrnthr',kt Kernel threshold. Must be in range ]0,1]. \n% Default is 1e-4.\n%\n% 'timeinv' Use the time invariant phase convention. The\n% default is 'freqinv'.\n%\n% 'pedanticsearch' Be pedantic about the energy of pairs of \n% conjugated atoms in the selection step. \n% Disabled by default.\n%\n% 'algorithm',alg Algorithm to use. Available: \n% 'mp'(default),'selfprojmp','cyclicmp'\n%\n% 'reset' Reset the decomposition until stopping criteria\n% are met. The reset means a complete synthesis and \n% re-analysis. Available: \n% 'noreset' (default), 'reset', 'quickreset'\n% Option 'quickreset' applies a heuristic to stop the \n% algorithm more quickly when the targer error is \n% reached.\n%\n% Reset conditions can be controlled by the following key-value pairs:\n%\n% 'resetit',it Reset the decomposition every `it` iteration.\n% Must be a positive integer.\n%\n% 'reseterrdb',err Reset the decomposition when the error estimate \n% in dB decreases below `err`. Must be negative. \n% Default is `10*log10(1.1*kv.kernthr)`.\n%\n% The computational routine is only available in C. Use |ltfatmex| to\n% to compile it.\n%\n% Algorithms\n% ----------\n%\n% By default, the function uses the fast MP using approximate update \n% in the coefficient domain as described in::\n% \n% \"Z. Prusa, N. Holighaus, P. Balazs: Fast Matching Pursuit with Multi-Gabor Dictionaries\"\n% \n% The kernel threshold limits the minimum approximation error which\n% can be reached. For example the default threshold 1e-4 in general \n% allows achieving at least -40 dB.\n% \n% Note that this algorithm internally computes the error as\n% `errdb = 10*log10(err(k)/norm(f)^2)`, with `err(0) = norm(f)^2` and \n% `err(k) = err(k-1) - abs(cselected(k))^2`. Here, `cselected(k)` is the\n% Gabor coefficient selected at the k-th MP step. This formula is exact \n% only if the kernel threshold equals 0. Otherwise it serves as a cheap\n% estimate. The exact error is only computed when this function is run\n% with resets enabled and only in between resets. \n% \n% Examples\n% --------\n%\n% The following example shows the decomposition in 3 dictionaries and\n% plots contributions from the individual dictionaries and the residual.:::\n%\n% [f,fs] = gspi;\n% [c, frec, info] = multidgtrealmp(f,...\n% {'blackman',128,512,'blackman',512,2048,'blackman',2048,8192});\n% frecd = info.synthetize(c);\n% figure(1); \n% xvals = (0:numel(f)-1)/fs;\n% subplot(4,1,1); plot(xvals,frecd(:,1));ylim([-0.5,0.5]);\n% subplot(4,1,2); plot(xvals,frecd(:,2));ylim([-0.5,0.5]);\n% subplot(4,1,3); plot(xvals,frecd(:,3));ylim([-0.5,0.5]);\n% subplot(4,1,4); plot(xvals,f-frec);ylim([-0.5,0.5]); xlabel('Time (s)');\n%\n% See also: dgtreal idgtreal\n%\n% References: ltfatnote052 mazh93 stchr10 rerose17\n\n%AUTHOR: Zdenek Prusa\n\nthismfile = upper(mfilename);\ncomplainif_notenoughargs(nargin,2,thismfile);\n% Define initial value for flags and key/value pairs.\ndefinput.keyvals.errdb=-40;\ndefinput.keyvals.maxit=[];\ndefinput.keyvals.resetit=0;\ndefinput.keyvals.reseterrdb = 0;\n%definput.keyvals.iterstep=[];\ndefinput.keyvals.kernthr = 1e-4;\n%definput.flags.print={'quiet','print'};\ndefinput.flags.algversion={'fast','slow'};\ndefinput.flags.algorithm={'mp','selfprojmp','cyclicmp'};\ndefinput.flags.search={'plainsearch','pedanticsearch'};\ndefinput.flags.phaseconv={'freqinv','timeinv'};\ndefinput.flags.reset={'noreset','reset','quickreset'};\n\n[flags,kv]=ltfatarghelper({'errdb','maxit'},definput,varargin);\n\nif exist('comp_multidgtrealmp','file') ~= 3 && flags.do_fast\n error(['%s: MEX/OCT file is missing. Either compile the MEX/OCT ',...\n 'interfaces or re-run the function with ''slow'''], thismfile);\nend\n\nif flags.do_slow\n error('%s: ''slow'' is not supported yet.',thismfile)\nend\n\nif flags.do_reset || flags.do_quickreset % Check reseterrdb or resetit\n if kv.reseterrdb == 0\n if kv.resetit == 0 % Set both to conservative default values depending on kernthr\n kv.reseterrdb = 10*log10(1.1*kv.kernthr);\n kv.resetit = round(1000/sqrt(kv.kernthr)); \n else % If only resetit is given, ignore reseterrdb\n kv.reseterrdb = -flintmax;\n end\n elseif kv.resetit == 0 % If only reseterrdb is given, ignore resetit\n kv.resetit = flintmax;\n end \n if kv.reseterrdb >= 0\n error('%s: Reset error tolerance must be negative.',thismfile);\n end\n if kv.resetit < 0 || kv.resetit ~= round(kv.resetit)\n error('%s: Number of iterations before reset must be a positive integer.',thismfile);\n end\nend\n\n%% ----- step 1 : Verify f and determine its length -------\n% Change f to correct shape.\n[f,~,Ls,W,dim,permutedsize,order]=assert_sigreshape_pre(f,[],[],upper(mfilename));\n\nif W>1\n error('%s: Input signal can be single channel only.',upper(mfilename));\nend\n\nif kv.errdb > 0\n error('%s: Target error must be lower than 0 dB.',upper(mfilename));\nend\n\nif ~(kv.kernthr > 0 && kv.kernthr <= 1)\n error('%s: Kernel threshold must be in range ]0,1].',upper(mfilename));\nend\n\nif ~iscell(dicts), error('%s: dicts must be cell',thismfile); end\nif rem(numel(dicts),3) ~= 0 || ~all(cellfun(@(x)isscalar(x), dicts([2:3:end,3:3:end])))\n error('%s: bad format of dicts. Check {g1,a1,M1,g2,a2,M2,...,gW,aW,MW}',...\n thismfile);\nend\n\ndictno = numel(dicts)/3;\ngin = dicts(1:3:end);\na = cell2mat(dicts(2:3:end));\nM = cell2mat(dicts(3:3:end));\n\nif any(rem(M,a) ~= 0) || any(M./a<2)\n error(['%s: Only integer oversampling greater than 1 is allowed ',...\n 'i.e. M/a must be an integer>=2.'],...\n upper(mfilename));\nend\n\nif dictno > 1\n asort = sort(a);\n Msort = sort(M);\n if any(rem(asort(2:end),asort(1:end-1)) ~= 0)\n error('%s: all au and av must be divisible by min(au,av)',thismfile);\n end\n if any(rem(Msort(2:end),Msort(1:end-1)) ~= 0)\n error('%s: all Mu and Mv must be divisible by min(Mu,Mv)',thismfile);\n end\nend\n\ninfo.a = a;\ninfo.M = M;\ninfo.iter = 0;\ninfo.relres = [];\nfnorm = norm(f);\n\nL = filterbanklength(Ls,[a(:);M(:)]);\nif isempty(kv.maxit), kv.maxit = L; end\n\ninfo.g = cell(dictno,1);\nfor dIdx = 1:dictno\n info.g{dIdx} = setnorm(gabwin(gin{dIdx},a(dIdx),M(dIdx),L),'2');\nend\n\nfor dIdx = 1:dictno\n condnum = gabframebounds(info.g{dIdx},a(dIdx),M(dIdx));\n if condnum > 1e3\n error('%s: Dictionary %d is badly conditioned.',dIdx,upper(mfilename));\n end\nend\n\n% Initial residuum\nfpad = postpad(f,L);\n\n% Determine reset/no reset mode and run MP decomposition \nif flags.do_noreset\n [c,info.atoms,info.iter,info.status] = ...\n comp_multidgtrealmp(fpad,info.g,a,M,flags.do_timeinv,...\n kv.kernthr,kv.errdb,kv.maxit,kv.maxit,...\n flags.do_pedanticsearch, flags.algorithm );\nelse\n c = cell(1,dictno);\n for dIdx = 1:dictno\n c{dIdx} = zeros(floor(M(dIdx)/2) + 1, L/a(dIdx),class(f));\n end\n\n remainingit = kv.maxit;\n currerrdb = kv.errdb;\n \n info.resets = -1;\n reseterrdb = kv.reseterrdb;\n\n while remainingit > 0 && currerrdb < 0\n info.resets = info.resets + 1;\n \n % Adjust number of iterations\n currit = min([remainingit,kv.resetit]);\n if flags.do_quickreset % Adjust reset error condition\n reseterrdb = max([1.2*currerrdb,kv.reseterrdb]);\n end\n\n [ctmp,info.atoms,info.iter,info.status] = ...\n comp_multidgtrealmp(fpad,info.g,a,M,flags.do_timeinv,...\n kv.kernthr,reseterrdb,currit,currit,...\n flags.do_pedanticsearch, flags.algorithm );\n\n c = cellfun(@(cEl,ctmpEl) cEl + ctmpEl, c(:)',ctmp(:)','UniformOutput', 0);\n\n remainingit = remainingit - info.iter;\n\n %The following means that some other stopping criterion has been reached\n if info.status ~=0 && info.status ~=3 && currit ~= info.iter, break; end\n\n if remainingit > 0\n % Recompute residuum\n frec = sum(cell2mat(cellfun(@(cEl,gEl,aEl,MEl) idgtreal(cEl,gEl,aEl,MEl,flags.phaseconv),...\n c(:)',info.g(:)',num2cell(a(:))',num2cell(M(:))','UniformOutput',0)),2);\n \n fpad = postpad(f,L) - frec;\n relres = norm(fpad(:)) / fnorm; \n % Since we are changing the residual, we must adjust the target error\n currerrdb = kv.errdb - 20*log10(relres); \n if currerrdb < 0\n info.relres(info.resets+1) = relres;\n end\n if info.resets >= 1 && info.relres(end) > info.relres(end-1)\n info.status = 6; \n break; \n end\n end\n end\n\n %Fix the info\n info.atoms = sum(cellfun(@(cEl) numel(find( abs(cEl) > 0 )), c));\n info.iter = kv.maxit - remainingit;\nend\n\n\nif nargout>1\n permutedsize2 = permutedsize; permutedsize2(2) = dictno;\n info.synthetize = @(c) ...\n assert_sigreshape_post(...\n postpad(cell2mat(cellfun(@(cEl,gEl,aEl,MEl) idgtreal(cEl,gEl,aEl,MEl,flags.phaseconv),...\n c(:)',info.g(:)',num2cell(a(:))',num2cell(M(:))','UniformOutput',0)),Ls),...\n dim,permutedsize2,order);\n dim2 = 2;\n if dim == 2, dim2 = 1; end\n frec = sum(info.synthetize(c),dim2);\n if fnorm == 0\n info.relres(end+1) = 0;\n else\n info.relres(end+1) = norm(frec(:)-f(:))/fnorm;\n end\n \n % Fix the status\n if info.relres(end) <= 10^(kv.errdb/20)\n info.status = 0;\n elseif info.iter == kv.maxit\n info.status = 2;\n end\n \n status_str = {...\n 'Target error reached',...\n 'Maximum number of atoms reached',...\n 'Maximum number of iterations reached',...\n 'Stalled (abs. norm. error estimate became negative)',...\n 'Selected coefficient tolerance reached',...\n 'All zeros',...\n 'Stalled (Residual has increased since last reset. Try to reduce resetit.)'...\n };\n info.message = status_str{1 + info.status};\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/multidgtrealmp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.6926419704455588, "lm_q1q2_score": 0.5493384688002625}} {"text": " function fit = de_ftab_fit(sl, fm, varargin)\n%function fit = de_ftab_fit(sl, fm, [options])\n%|\n%| Fit to DE table fm(), suitable for subsequent interpolation / extrapolation.\n%| Uses either classic polynomial basis functions,\n%| or an exponential model: -log(sum_k p_k exp(-m_k . s))\n%|\n%| in\n%|\tsl\t{L}\t\tsample locations for each of L materials\n%|\tfm\t[s1 ... sL M]\tDE tables f_m(s_1,...,s_L), size [(Ns) M]\n%|\n%| option\n%|\t'type'\t'poly' | 'exp'\ttype of fit (default 'poly') todo: change?\n%|\t'wt'\t{M}\t\tfit weighting for each of M energies.\n%|\t\t\t\t(default depends on 'type'; see code)\n%|\t'show'\t1|0\t\tplot? (default false)\n%|\t'ntype' ''\t\toptions for negative sl values (default '')\n%|\t\t\t\t'abs' - experimental symmetrizing option\n%| options for 'poly'\n%|\t'order'\t\t\tpolynomial order (default 3)\n%|\t'maxdegree'\t\targument for poly_string() (default [])\n%| options for 'exp'\n%|\t'kev'\t[Ne 1]\t\tkev *for fitting* (default [10:5:200]')\n%|\t'mac'\t[Ne L]\t\t*for fitting* (this or mtype are required)\n%|\t'mtype' {L}\t\tmaterial types\n%|\t'macbar' [M L]\t\tif nonempty, use it to match derivative at s=0.\n%|\t'wls_simplex_arg' {}\targuments for wls_simplex (default {})\n%|\n%| out\n%|\tfit\tstrum\t\tstrum object for fitted f_m(s_1,...,s_L)\n%|\t\t\t\tfit.coef is [nbasis M] for 'poly'\n%|\tmethods:\n%|\t\t\t\t(sll denotes stacked array [(Ns) L] or [*Ns L])\n%|\t.fmfun(sll [() L])\tfm function evaluation [() L] -> [() M]\n%|\t.fgrad(sll)\t\tfm gradient evaluation [() L] -> [() L M]\n%|\t.fhess(sll)\t\tfm hessian evaluation [() L] -> [() L L M]\n%|\t.show_sp([en, sp])\tplot true spectrum vs fitted spectrum\n%|\t.show_fm(sl, [fm])\tmesh plot of fm and its fit\n%|\t.show_err(sl, fm)\tmesh plot of fit error\n%|\t.mac_eff\t\teffective mass atten coef based on fit\n%|\t\t\t\t(valid for 'exp' only)\n%|\n%| Copyright 2006-3-3, Jeff Fessler, University of Michigan\n\nif nargin == 1 && streq(sl, 'test'), de_ftab_fit_test, return, end\nif nargin < 2, ir_usage, end\n\narg.show = false;\narg.type = '';\narg.mtype = {};\narg.ntype = ''; % how to handle negatives\narg.kev = [10:5:200]';\narg.mac = [];\narg.macbar = [];\narg.wls_simplex_arg = {}; % pass to wls_simplex which passes it to lsqlin\narg.order = 3;\narg.maxdegree = [];\narg.wt = {};\narg.dc = false; % default: exclude dc (constant) from (polynomial) fit\narg = vararg_pair(arg, varargin);\nif isempty(arg.type), arg.type = 'poly'; end\n\nLL = length(sl);\n\nif ndims(fm) == LL\n\tMM = 1;\nelseif ndims(fm) == LL + 1\n\tMM = size(fm,ndims(fm)); % last dimension is number of spectra\nelse\n\terror 'invalid fm size'\nend\n\nfor ll=1:LL % make sure arguments match table dimensions\n\tif length(sl{ll}) ~= size(fm, ll)\n\t\tfail('dim mismatch %d', ll)\n\tend\nend\n\nswitch arg.type\ncase 'poly'\n\t[fit fmfun fgrad fhess] = de_ftab_fit_poly(sl, fm, MM, arg.wt, ...\n\t\targ.order, arg.maxdegree, arg.dc);\n\ncase 'exp'\n\tfit = de_ftab_fit_exp(sl, fm, MM, arg.wt, ...\n\t\targ.mtype, arg.mac, arg.kev, arg.macbar, arg.wls_simplex_arg);\n\tfmfun = @de_ftab_fit_exp_eval;\n\tfgrad = @de_ftab_fit_exp_grad;\n\tfhess = @de_ftab_fit_exp_hess;\n\tfit.mac_eff = zeros(MM, LL); % [M L] mac effective\n\tfor mm=1:MM\n\t\tfit.mac_eff(mm,:) = fit.mac{mm}' * fit.coef{mm};\n\tend\n\notherwise\n\tfail('unknown fit type %s', arg.type)\nend\n\nfit.LL = LL;\nfit.MM = MM;\nfit.type = arg.type;\nfit.ntype = arg.ntype;\n\nmeth = {'fmfun', fmfun, '(sll [() L]) -> [() M]'; ...\n\t'fgrad', fgrad, '(sll [() L]) -> [() L M]'; ...\n\t'fhess', fhess, '(sll [() L]) -> [() L L M]'; ...\n\t'show_err', @de_ftab_fit_show_err, '(sl, fm)'; ...\n\t'show_fm', @de_ftab_fit_show_fm, '(sl, [fm])'; ...\n\t'show_sp', @de_ftab_fit_show_sp, '([en, sp])'; ...\n\t};\nfit = strum(fit, meth);\n\nif arg.show && im\n\tfit.show_fm(sl, fm);\nend\n\nend % de_ftab_fit()\n\n\n%\n% de_ftab_fit_poly()\n%\nfunction [fit, ffun, fgrad, fhess] = ...\n\t de_ftab_fit_poly(sl, fm, MM, wt, order, maxdegree, dc)\n\nsll = ndgrid_jf('mat', sl{:});\n\n% for fitting, up weight the no-bone part\n% because soft tissue is most prevalant\nif isempty(wt)\n\twt{1} = 1 ./ (stackpick(sll,2) + 1);\n\twt{2} = wt{1};\nend\n\nfit.basis_order = order;\nfit.basis_maxdegree = maxdegree;\nfit.basis_dc = dc;\n\n[fit.basis_func fit.basis_d1 fit.basis_d2] = ...\n\tir_poly2_fun(order, 'maxdegree', maxdegree, 'dc', dc);\n\nfit.nbasis = numel(fit.basis_func(0,0));\n\nss1 = col(stackpick(sll,1));\nss2 = col(stackpick(sll,2));\ntmp = fit.basis_func(ss1, ss2); % [*Ns nbasis]\nfit.coef = zeros(fit.nbasis, MM);\nfor mm=1:MM\n\tfit.coef(:,mm) = (diag_sp(wt{mm}(:)) * tmp) ...\n\t\t\\ (wt{mm}(:) .* col(fm(:,:,mm)));\nend\n\nffun = @(fit,sl) ...\n\treshape([fit.basis_func(sl{1}(:), sl{2}(:)) * fit.coef(:,1); ...\n\t\tfit.basis_func(sl{1}(:), sl{2}(:)) * fit.coef(:,2)], ...\n\t\t[size(sl{1}) 2]);\nffun = @de_ftab_fit_poly_eval;\nfgrad = @() error('not done');\nfhess = @() error('not done');\n\nend % de_ftab_fit_poly()\n\n\n%\n% de_ftab_fit_poly_eval()\n%\nfunction fm = de_ftab_fit_poly_eval(fit, sll)\n\n% if fit.MM ~= 2\ns1 = stackpick(sll,1);\ns2 = stackpick(sll,2);\nfm = [\tfit.basis_func(s1(:), s2(:)) * fit.coef(:,1);\n\tfit.basis_func(s1(:), s2(:)) * fit.coef(:,2)];\nfm = reshape(fm, [size(s1) 2]);\n\nend % de_ftab_fit_poly_eval()\n\n\n%\n% de_ftab_fit_exp()\n% todo: more documentation\n% todo: use a set of exponents, not \"mac\"\n%\nfunction fit = de_ftab_fit_exp(sl, fm, MM, wt, mtype, mac, kev, macbar, ...\n\twls_simplex_arg)\n\nsll = ndgrid_jf('mat', sl{:}); % [(Ns)]\n\nif isempty(mac)\n\tif isempty(mtype), error 'mac or mtype required', end\n\tmac = xray_read_atten(mtype, kev); % [Ne L]\nelse\n\tif size(mac,1) ~= length(kev), fail 'size mismatch', end\nend\n\nLL = length(sl);\n\nif isempty(wt), wt = num2cell(ones(MM,1)); end\n\nAb = exp(-reshapee(sll, [], LL) * mac'); % [*Ns Ne] \"over-complete\" basis\n\nfit.kev = cell(1,MM);\nfit.mac = cell(1,MM);\nfit.coef = cell(1,MM);\nfor mm=1:MM\n\twarg = wls_simplex_arg;\n\tif LL == 1 && ~isempty(macbar) % constrain deriv. at 0\n\t\twarg = {wls_simplex_arg{:}, 'inprodv', mac' / macbar(mm,1)};\n\tend\n\n\tif MM == 1 % todo: kludgy\n\t\tdat = fm;\n\telse\n\t\tdat = stackpick(fm,mm); % [(Ns)]\n\tend\n\ty = exp(-dat);\n\tWh = spdiag(sqrt(wt{mm}(:)), 'nowarn');\n\t% initial coefficients for each candidate energy\n\tx = wls_simplex(Ab, y(:), Wh, [], warg{:}); % [Ne 1]\n\n\tie = x > 1e-6; % find key energies\n\tfit.kev{mm} = kev(ie);\n\tfit.mac{mm} = mac(ie,:); % [Ne L] (now Ne may be smaller than before)\n\n\twarg = wls_simplex_arg;\n\tif LL == 1 && ~isempty(macbar) % constrain derivative at 0\n\t\twarg = {wls_simplex_arg{:}, 'inprodv', fit.mac{mm}' / macbar(mm,1)};\n\tend\n\n\tA = exp(-reshapee(sll, [], LL) * fit.mac{mm}'); % [*Ns Ne] final basis\n\t% final coefficients at key enerties:\n\tfit.coef{mm} = wls_simplex(A, y(:), Wh, [], warg{:}); % [Ne 1]\nend\n\nend % de_ftab_fit_exp()\n\n\n%\n% de_ftab_fit_exp_eval()\n% evaluate \n% in\n%\tsll\t[(Ns) L]\tstackup of s1,s2,...,s_L\n% out\n%\tf\t[(Ns) M]\tstackup of f1,f2,...,f_M\n%\nfunction f = de_ftab_fit_exp_eval(fit, sll)\nLL = fit.LL;\nif LL == 1\n\tNs = size(sll);\n\tif Ns(end) == 1, Ns = Ns(1:end-1); end\nelse\n\tNs = size(sll); if LL ~= Ns(end), fail 'bug', end; Ns = Ns(1:end-1);\nend\nsll = reshapee(sll, [], LL); % [*Ns L]\nMM = fit.MM;\n\npersistent warned\nif ~isvar('warned') || isempty(warned)\n\twarned = 0;\nend\n\nf = zeros(prod(Ns),MM);\nfor mm=1:MM\n\n\tswitch fit.ntype\n\tcase '' % standard\n\t\tA = exp(-sll * fit.mac{mm}'); % [*Ns Ne]\n\t\ttmp = -log(A * fit.coef{mm}); % [*Ns 1]\n\t\tf(:,mm) = tmp;\n\n\tcase 'abs' % trick for negatives\n\t\tif LL == 1\n\t\t\tA = exp(-abs(sll) * fit.mac{mm}'); % [*Ns Ne]\n\t\t\ttmp = -log(A * fit.coef{mm}); % [*Ns 1]\n\t\t\tf(:,mm) = -sign(sll) .* log(A * fit.coef{mm}); % [*Ns 1]\n%\t\t\tbad = sll < 0;\n%\t\t\tf(bad,mm) = sll(bad) * fit.mac_eff(mm,1);\n\t\telse\n\t\t\tif ~warned\n\t\t\t\twarned = 1;\n\t\t\t\twarn 'negative trick not done for L>1'\n\t\t\tend\n\t\tend\n\n\totherwise\n\t\tfail('bad ntype: %s', fit.ntype)\n\tend\n\nend\nf = reshape(f, [Ns MM]);\n\nend % de_ftab_fit_exp_eval()\n\n\n%\n% de_ftab_fit_exp_grad()\n% evaluate gradient of f for each of the given s vectors.\n% in\n%\tsll\t[(Ns) L]\tstackup of s1,s2,...,s_L\n% out\n%\tg\t[(Ns) L M]\tstackup of gradients of f(s)\n%\nfunction g = de_ftab_fit_exp_grad(fit, sll)\nLL = fit.LL;\nNs = size(sll);\nif LL == 1\n\tif Ns(end) == 1, Ns = Ns(1:end-1); end\nelse\n\tif LL ~= Ns(end); error 'bug', end\n\tNs = Ns(1:end-1);\nend\nsll = reshape(sll, [], LL); % [*Ns L]\nMM = fit.MM;\n\npersistent warned\nif ~isvar('warned') || isempty(warned)\n\twarned = 0;\nend\n\ng = zeros(prod(Ns), LL, MM);\nfor mm=1:fit.MM\n\talf = fit.coef{mm}; % [Ne 1]\n\tmac = fit.mac{mm}; % [Ne L]\n\tNe = length(alf); % # exponential terms in the fit\n\n\tswitch fit.ntype\n%\tcase '' % standard\n\tcase 'abs'\n\t\tif any(sll(:) < 0) % trick for negatives\n\t\t\tif LL == 1\n\t\t\t\tsll = abs(sll);\n%\t\t\t\tbad = sll < 0;\n%\t\t\t\tg(bad,1,mm) = fit.mac_eff(mm,1);\n\t\t\telse\n\t\t\t\tif ~warned\n\t\t\t\t\twarned = 1;\n\t\t\t\t\twarn 'negative trick not done for L>1'\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\tend\n\n\tA = exp(-sll * mac'); % [*Ns Ne]\n\tQ = A .* repmat(alf', [prod(Ns) 1]); % [*Ns Ne]\n\tdenom = sum(Q,2); % [*Ns 1]\n\tQ = Q ./ repmat(denom, [1 Ne]);\n\tg(:,:,mm) = Q * mac;\n\nend\ng = reshape(g, [Ns LL MM]);\n\nend % de_ftab_fit_exp_grad()\n\n\n%\n% de_ftab_fit_exp_hess()\n% evaluate hessian of f for each of the given s vectors.\n% in\n%\tsll\t[(Ns) L]\tstackup of s1,s2,...,s_L\n% out\n%\th\t[(Ns) L L M]\tstackup of hessians of f(s)\n%\nfunction h = de_ftab_fit_exp_hess(fit, sll)\nNs = size(sll); LL = Ns(end); Ns = Ns(1:end-1);\nsll = reshape(sll, [], LL); % [*Ns L]\nMM = fit.MM;\n\npersistent warned\nif ~isvar('warned') || isempty(warned)\n\twarned = 0;\nend\n\nh = zeros(prod(Ns), LL, LL, MM);\nfor mm=1:fit.MM\n\tmac = fit.mac{mm}; % [Ne L]\n\talf = fit.coef{mm}; % [Ne 1]\n\tNe = length(alf); % # exponential terms in the fit\n\n\tswitch fit.ntype\n%\tcase '' % standard\n\tcase 'abs'\n\t\tif any(sll(:) < 0) % trick for negatives\n\t\t\tif LL == 1\n\t\t\t\tsll_sign = sign(sll);\n\t\t\t\tsll = abs(sll);\n%\t\t\t\tbad = sll < 0;\n%\t\t\t\thm(bad,1,1) = 0;\n\t\t\telse\n\t\t\t\tif ~warned\n\t\t\t\t\twarned = 1;\n\t\t\t\t\twarn 'negative trick not done for L>1'\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\tend\n\n\tA = exp(-sll * fit.mac{mm}'); % [*Ns Ne]\n\n\tQ = A .* repmat(alf', [prod(Ns) 1]); % [*Ns Ne]\n\tdenom = sum(Q,2); % [*Ns 1]\n\tQ = Q ./ repmat(denom, [1 Ne]);\n\tg = Q * mac; % [*Ns L] gradient\n\n\t% loop over LL because it is smaller than *Ns or Ne\n\thm = zeros(prod(Ns), LL, LL);\n\tfor l1=1:LL\n\t\tfor l2=1:LL\n\t\t\thm(:,l1,l2) = g(:,l1) .* g(:,l2) ...\n\t\t\t\t- Q * (mac(:,l1) .* mac(:,l2));\n\t\tend\n\tend\n\n\tswitch fit.ntype\n%\tcase '' % standard\n\tcase 'abs'\n\t\tif any(sll(:) < 0) % trick for negatives\n\t\t\tif LL == 1\n\t\t\t\thm(:,1,1) = hm(:,1,1) .* sll_sign;\n%\t\t\t\tbad = sll < 0;\n%\t\t\t\thm(bad,1,1) = 0;\n\t\t\tend\n\t\tend\n\tend\n\n\th(:,:,:,mm) = hm;\n\nend\nh = reshape(h, [Ns LL LL MM]);\n\nend % de_ftab_fit_exp_hess()\n\n\n%\n% de_ftab_fit_show_sp()\n% compare true spectra to fitted spectra\n%\nfunction out = de_ftab_fit_show_sp(fit, en, sp)\nif nargin < 1, fail 'de_ftab_fit_show_sp(fit, en, sp)', end\n\nif ~streq(fit.type, 'exp'), printm 'show_sp only done for exp', return, end\nif im\n\tclf, pl = (fit.MM+1)*100 + 10 + 1;\n\tif nargin > 1\n\t\tsubplot(pl)\n\t\tplot(en, sp * diag(1 ./ max(sp)))\n\t\ttmp = num2cell(char([1:fit.MM] + '0'));\n\t\tlegend(tmp{:})\n\t\taxisx(minmax(en))\n\tend\n\n\tif isfield(fit, 'kev')\n\t\tfor mm=1:fit.MM\n\t\t\tsubplot(pl+mm)\n\t\t\tbar(fit.kev{mm}, fit.coef{mm})\n\t\t\txtick(fit.kev{mm}(fit.coef{mm} > 0))\n\t\t\taxis tight\n\t\t\tif nargin > 1, axisx(minmax(en)), end\n\t\tend\n\telse\n\t\twarn 'kev unknown'\n\tend\nend\n\nif nargout, out = []; end\n\nend % de_ftab_fit_show_sp()\n\n\n%\n% de_ftab_fit_show_fm()\n% compare fit to sampled fm\n%\nfunction out = de_ftab_fit_show_fm(fit, sl, fm, sll)\nif nargin < 2, error 'de_ftab_fit_show_fm(fit, sl, fm)', end\n\ndo_fm = nargin > 2;\nif ~isvar('sll') || isempty(sll)\n\tsll = ndgrid_jf('mat', sl{:});\nend\n\nfh = fit.fmfun(sll);\n\nif ~iscell(sl), fail 'sl must be cell', end\nswitch length(sl) % LL\ncase 1\n\ts1 = sl{1};\n\tim clf\n\targ = {};\n\tleg = {};\n\torder = 'bgrcm';\n\tif do_fm\n\t\tfor mm=1:fit.MM\n\t\t\targ = {arg{:}, s1, fm(:,mm), [order(mm) '.']};\n\t\t\tleg = {leg{:}, sprintf('true m=%d', mm)};\n\t\tend\n\tend\n\tfor mm=1:fit.MM\n\t\targ = {arg{:}, sll, fh(:,mm), [order(mm) '-']};\n\t\tleg = {leg{:}, sprintf('fit m=%d', mm)};\n\tend\n\tplot(arg{:})\n\txlabel 's1'\n\tylabel 'fm(s1)'\n\tlegend(leg{:}, 4)\n\ncase 2\n\ts1 = sl{1};\n\ts2 = sl{2};\n\tsmax(1) = max(s1);\n\tsmax(2) = max(s2);\n\tif do_fm\n\t\tfmax = max(fm(:));\n\telse\n\t\tfmax = max(fh(:));\n\tend\n\n\tax = [0 smax(1) 0 smax(2) 0 fmax];\n\tcax = [0 fmax];\n\n\tim clf\n\tim('pl', 2, fit.MM)\n\tfor mm=1:fit.MM\n\t\tif do_fm\n\t\tshow(mm, s1, s2, fm(:,:,mm), ax, cax, sprintf('f_%d(s)', mm))\n\t\tend\n\t\tm0 = mm + fit.MM;\n\t\tshow(m0, s1, s2, fh(:,:,mm), ax, cax, sprintf('f_%d fit', mm))\n\tend\n%\t% text(-60, 10, '[cm^2/g]')\n\ncase 3\n\ts1 = sl{1};\n\ts2 = sl{2};\n\ts3 = sl{3};\n\tsmax(1) = max(s1);\n\tsmax(2) = max(s2);\n\tsmax(3) = max(s3);\n\tif do_fm\n\t\tfmax = max(fm(:));\n\telse\n\t\tfmax = max(fh(:));\n\tend\n\n\tax = [0 smax(2) 0 smax(3) 0 fmax];\n\tcax = [0 fmax];\n\n\tim clf\n\tim('pl', 2, fit.MM)\n\tfor mm=1:fit.MM\n\t\tif do_fm\n\t\tshow(mm, s2, s3, fm(1,:,:,mm), ax, cax, sprintf('f_%d(s)', mm))\n\t\tend\n\t\tm0 = mm + fit.MM;\n\t\tshow(m0, s2, s3, fh(1,:,:,mm), ax, cax, sprintf('f_%d fit', mm))\n\tend\n%\t% text(-60, 10, '[cm^2/g]')\n\notherwise\n\tfail 'not done'\nend\n\nif nargout, out = []; end\n\nend % de_ftab_fit_show_fm()\n\n\n%\n% de_ftab_fit_show_err()\n% show fit errors, and relate to HU\n% f = mac s, mac(70kev,H2O) = 0.2 cm^2 / g = 1000 HU\n% mh = mac * 1000 HU / (0.2 g/cm^2)\n% so Df/Dmh = Df/Dmac * Dmac/Dmh = (50 g/cm^2) (0.2 cm^2/g) / 1000 HU = 1/100 HU\n% so Dmh = 100 HU * Df for 50 cm of H2O.\n%\nfunction out = de_ftab_fit_show_err(fit, sl, fm)\nif nargin < 3, error 'de_ftab_fit_show_err(fit, sl, fm)', end\n\nsll = ndgrid_jf('mat', sl{:});\n\nfh = fit.fmfun(sll);\nerr = fh - fm;\nprintm('worst model error = %g of %g', max(abs(err(:))), max(fm(:)))\nprintm('worst model error = %g HU over 50cm H2O', 100*max(abs(err(:))))\nfor mm=1:fit.MM\n\tee = stackpick(err,mm);\n\tprintm('worst error (mm=%d): %g', mm, max(abs(ee(:))))\nend\n\nif max(abs(err(:))) == 0\n\tif nargout, out = []; end\nreturn\nend\n\nif 0\n\te1 = err(:,:,1);\n\te2 = err(:,:,2);\n\tdisp([minmax(e1); minmax(e2)]')\n\tprintm('worst error1 %g', max(col(abs(err(:,1,:)))))\n\tprintm('worst error2 %g', max(col(abs(err(:,2,:)))))\nend\n%err = abs(err);\n\nswitch length(sl) % LL\ncase 1\n\ts1 = sl{1};\n\targ = {};\n\tleg = {};\n\torder = 'bgrcm';\n\tfor mm=1:fit.MM\n\t\targ = {arg{:}, s1, err(:,mm), [order(mm) '-']};\n\t\tleg = {leg{:}, sprintf('m=%d', mm)};\n\tend\n\tplot(arg{:})\n\txlabel 's1'\n\tylabel 'error'\n\tlegend(leg{:}, 4)\n\ncase 2\n\ts1 = sl{1};\n\ts2 = sl{2};\n\n\telim = minmax(err(:))';\n\t%elim = [-1 1] * 0.01; % +/- 1 HU\n\tax = [0 max(s1) 0 max(s2) elim];\n\tim clf, im('pl', 1, fit.MM)\n\tfor mm=1:fit.MM\n\t\tshow(mm, s1, s2, err(:,:,mm), ax, elim, sprintf('f_%d error', mm))\n\tend\n\ncase 3\n\ts1 = sl{1};\n\ts2 = sl{2};\n\ts3 = sl{3};\n\n\telim = minmax(err(:))';\n\tax = [0 max(s2) 0 max(s3) elim];\n\tim clf, im('pl', 1, fit.MM)\n\tfor mm=1:fit.MM\n\t\tshow(mm, s2, s3, err(1,:,:,mm), ax, elim, sprintf('f_%d error', mm))\n\tend\n\notherwise\n\tfail 'not done'\nend\n\nif nargout, out = []; end\n\nend % de_ftab_fit_show_err()\n\n\n%\n% show()\n%\nfunction show(pl, x, y, f, ax, cax, ti)\nf = squeeze(f); % for LL=3 case\nif ~im, return, end\nim('subplot', pl)\nif 1\n\tmesh(x,y,f')\n\tcolormap hsv, caxis(cax), cbar\n\taxis(ax)\n\txtick, ytick, ztick, zwhite\nelse\n\tim(x,y,f), cbar\n\txtick, ytick\nend\nxlabel 's_1', ylabel 's_2', title(ti)\n\nend % show()\n\n\n%\n% de_ftab_fit_test()\n%\nfunction de_ftab_fit_test\n\n%stype = 'mono,70,100,160';\n%stype = 'ps1';\n%stype = 'poly1,60';\nstype = 'poly1,80,100,160'; % stress test\nxrs = xray_read_spectra(stype);\n\nlist.sl{1} = linspace(0, 50, 26); % coarse for fast fitting\nlist.sl{2} = linspace(0, 30, 31);\nlist.sl{3} = linspace(0, 2, 11);\nlist.mtype = {'water', 'bone', 'iodine'};\nlist.wls_simplex_arg = {{'reg', 1e-16}, {'reg', 1e-9}, {'reg', 1e-4}}; % more reg for LL>1 case\n\nif 0 % look at derivatives\n\tLL = 2;\n\tsl = {list.sl{1:LL}};\n\tmtype = {list.mtype{1:LL}};\n\twarg = list.wls_simplex_arg{LL};\n\tmas = xray_read_mac(mtype);\n\tmac = mas.mac(xrs.en);\n\tsll = ndgrid_jf('mat', sl{:});\n\tfm = de_ftab_fm(sll, mac, xrs.Ide);\n\tfit = de_ftab_fit(sl, fm, 'show', 1, 'type', 'exp', 'mtype', mtype, ...\n\t\t'wls_simplex_arg', warg); \n\tg = fit.fgrad(sll);\nend\n\n%for LL=1:3\nfor LL=2\n\tsl = {list.sl{1:LL}};\n\tmtype = {list.mtype{1:LL}};\n\twarg = list.wls_simplex_arg{LL};\n\n\tmas = xray_read_mac(mtype);\n\tmac = mas.mac(xrs.en);\n\tif im\n\t\tclf, semilogy(xrs.en, mac), legend(mtype{:})\n\tend\n\tsll = ndgrid_jf('mat', sl{:});\n\tfm = de_ftab_fm(sll, mac, xrs.Ide);\n%\tfit = de_ftab_fit(sl, fm, 'show', 1, 'type', 'poly')\n\tfit = de_ftab_fit(sl, fm, 'show', 1, 'type', 'exp', 'mtype', mtype, ...\n\t\t'wls_simplex_arg', warg); \n\n\tfh = fit.fmfun(sll);\n\tg = fit.fgrad(sll);\n\th = fit.fhess(sll);\n\n\tif 1 && LL == 2 % test gradient (for yong)\n\t\tif 1 % for gradient graphically\n\t\t\tlist.slfine{1} = linspace(0, 90, 261); % fine for evaluating\n\t\t\tlist.slfine{2} = linspace(0, 90, 511);\n\t\telse\n\t\t\tlist.slfine{1} = linspace(0, 5, 261); % fine for evaluating\n\t\t\tlist.slfine{2} = linspace(0, 3, 511);\n\t\tend\n%\t\tlist.slfine{3} = linspace(0, 2, 201);\n\t\tslfine = {list.slfine{1:LL}};\n\t\tslf = ndgrid_jf('mat', slfine{:});\n\t\tfh = fit.fmfun(slf);\n\t\tgr = fit.fgrad(slf); % [261 511 L M]\n\t\tif im % examine gradient values graphically\n\t\t\tpl = @(mm) subplot(100 + 10 * fit.MM + mm);\n\t\t\tfor mm=1:fit.MM\n\t\t\t\tpl(mm)\n\t\t\t\ttmp = gr(:,:,:,mm);\n\t\t\t\tplot(tmp(:,:,1), tmp(:,:,2), '.')\n\t\t\t\ttitlef('%d kvp', xrs.kvp(mm))\n\t\t\t\txlabel 'g1', ylabel 'g2'\n\t\t\t\taxis([0 max(col(tmp(:,:,1))) 0 max(col(tmp(:,:,2)))])\n\t\t\tend\n\t\treturn\n\t\tend\n\t\ti1 = 5;\n\t\ti2 = 9;\n\t\td1 = slfine{1}(i1+1) - slfine{1}(i1);\n\t\td2 = slfine{2}(i2+1) - slfine{2}(i2);\n\t\tgh(:,1) = (fh(i1+1,i2,:) - fh(i1,i2,:)) / d1;\n\t\tgh(:,2) = (fh(i1,i2+1,:) - fh(i1,i2,:)) / d2;\n\t\tpr transpose(gh)\n\t\tgg = squeeze(gr(i1,i2,:,:));\n\t\tpr gg\n\t\tpr transpose(fit.mac_eff) % at origin\n%\t\tgg - fit.mac_eff'\n\treturn\n\tend\n\n\tif im\n\t\tfit.show_sp(xrs.en, xrs.sp);\n\t\tprompt\n\t\tfit.show_fm(sl, fm);\n\t\tprompt\n\t\tfit.show_err(sl, fm);\n\t\tprompt\n\tend\n\nend\n\nend % de_ftab_fit_test()\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/ct/de_ftab_fit.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677622198946, "lm_q2_score": 0.6477982315512489, "lm_q1q2_score": 0.5493120167785177}} {"text": "%\n% MODEL REDUCTION BY THE ALGORITHMS LRSRM AND DSPMR. THE GOAL IS TO\n% GENERATE A \"NUMERICALLY MINIMAL REALIZATION\" OF THE GIVEN SYSTEM\n% AS WELL AS A REDUCED SYSTEM OF RELATIVELY SMALL ORDER. \n%\n% This demo program shows how the model reduction routines 'lp_lrsrm'\n% and 'lp_dspmr' work. Also, the use of 'lp_lradi', supplementary \n% routines, and user-supplied functions is demonstrated.\n\n% ----------------------------------------------------------------------- \n% Generate test problem \n% ----------------------------------------------------------------------- \n%\n% As test example, we use an FEM-semidiscretized problem, which leads to\n% a generalized system where M (the mass matrix) and N (the negative\n% stiffness matrix) are sparse, symmetric, and definite. \n\nload rail821 % load the matrices M N Btilde Ctilde of the generalized\n % system\n\n%load rail3113 % Uncomment this to get an example of larger order.\n\ndisp('Problem dimensions:')\n\nn = size(M,1) % problem order (number of states)\nm = size(Btilde,2) % number of inputs\nq = size(Ctilde,1) % number of outputs\n\n% ----------------------------------------------------------------------- \n% Initialization/generation of data structures used in user-supplied \n% functions and computation of ADI shift parameters\n% ----------------------------------------------------------------------- \n%\n% See 'demo_u1', 'demo_u2', 'demo_u3', and 'demo_l1' for more detailed\n% comments.\n\nname = 'msns'; \n[M0,MU,N0,B0,C0,prm,iprm] = msns_pre(M,N,Btilde,Ctilde); % preprocessing\nmsns_m_i(M0,MU,N0); % initialization for multiplication with A0\nmsns_l_i; % initialization for solving systems with A0\n\ndisp('Parameters for heuristic algorithm which computes ADI parameters:')\nl0 = 20 % desired number of distinct shift parameters \nkp = 50 % number of steps of Arnoldi process w.r.t. A0\nkm = 25 % number of steps of Arnoldi process w.r.t. inv(A0)\n\nb0 = ones(n,1); % This is just one way to choose the Arnoldi start \n % vector. \n\np = lp_para(name,[],[],l0,kp,km,b0); % computation of ADI shift \n % parameters\n\ndisp('Actual number of ADI shift parameters:');\nl = length(p)\n\ndisp('ADI shift parameters:');\np\n\nmsns_s_i(p) % initialization for shifted systems of linear equations \n % with A0+p(i)*I (i = 1,...,l)\n\n\n% ----------------------------------------------------------------------- \n% Solution of Lyapunov equations A0*X0+X0*A0' = -B0*B0' and\n% A0'*X0+X0*A0 = -C0'*C0\n% ----------------------------------------------------------------------- \n\ndisp('Parameters for stopping criteria in LRCF-ADI iteration:')\nmax_it = 200 % (large value)\nmin_res = 0 % (avoided)\nwith_rs = 'S' % (\"activated\")\nmin_in = 0 % (avoided)\n\nzk = 'Z';\nrc = 'C';\nBf = [];\nKf = [];\ninfo = 3;\n\ndisp('... solving A0*XB0+XB0*A0'' = - B0*B0''...');\ntp = 'B';\n\nfigure(1), hold off; clf; % (lp_lradi will plot residual history.)\n\n[ZB0,flag_B] = lp_lradi(tp,zk,rc,name,Bf,Kf,B0,p,max_it,min_res,...\n with_rs,min_in,info); \n % compute ZB0\n\ntitle('LRCF-ADI for CALE A_0X_{B0}+X_{B0}A_0^T = -B_0B_0^T')\ndisp('Termination flag:')\nflag_B \ndisp('Size of ZB0:');\nsize_ZB0 = size(ZB0)\n\ndisp('... solving A0''*XC0+XC0*A0 = - C0''*C0...');\ntp = 'C';\n\nfigure(2), hold off; clf; % (lp_lradi will plot residual history.)\n\n[ZC0,flag_C] = lp_lradi(tp,zk,rc,name,Bf,Kf,C0,p,max_it,min_res,...\n with_rs,min_in,info); \n % compute ZC0\n\ntitle('LRCF-ADI for CALE A_0^T X_{C0} + X_{C0} A_0 = -C_0^TC_0')\ndisp('Termination flag:')\nflag_C \ndisp('Size of ZC0:');\nsize_ZC0 = size(ZC0)\n\n\n% ----------------------------------------------------------------------- \n% Plot the transfer function of the system for a certain frequency range\n% ----------------------------------------------------------------------- \n\ndisp('... computing transfer function of original system ...'); \n\nfreq = lp_lgfrq(1e-10,1e10,200); % generate a set of 200 \"frequency\n % sampling points\" in the interval\n % [10^-10,10^+10]. \nG = lp_trfia(freq,N,Btilde,Ctilde,[],M); % compute \"transfer function \n % sample\" for these frequency \n % points\nnrm_G = lp_gnorm(G,m,q); % compute norms of the \"transfer function\n % sample\" for these frequency points\n \nfigure(3); hold off; clf; \nloglog(freq,nrm_G,'k:'); \nxlabel('\\omega');\nylabel('Magnitude');\nt_text = 'dotted: ||G||';\ntitle(t_text);\npause(1)\n\n\n% ----------------------------------------------------------------------- \n% Generate reduced systems of high accuracy and possibly high order\n% ----------------------------------------------------------------------- \n\ndisp(' ')\ndisp('Generate reduced systems of high accuracy and possibly high order')\ndisp('-----------------------------------------------------------------')\n\ndisp('Parameters for model reduction:')\nmax_ord = [] % (avoided)\ntol = 1e-14 % (This criterion determines the reduced order. The very \n % small value is chosen to generate a \"numerically minimal \n % realization\".)\n\n\ndisp('... computing reduced system by LRSRM ...');\n[Ars,Brs,Crs] = lp_lrsrm(name,B0,C0,ZB0,ZC0,max_ord,tol); % run LRSRM\n\ndisp('Reduced order:')\ndisp(length(Ars))\n\nGrs = lp_trfia(freq,Ars,Brs,Crs,[],[]); % compute \"transfer function\n % sample\" for reduced system\nnrm_dGrs = lp_gnorm(G-Grs,m,q); % compute norm of DIFFERENCE of \n % transfer function samples of original \n % and reduced system.\nfigure(3); hold on\nloglog(freq,nrm_dGrs,'r-'); \nt_text = [t_text, ', solid: ||G-G_{LRSRM}||'];\ntitle(t_text); pause(1)\n\n\ndisp('... computing reduced system by DSPMR ...');\n[Ard,Brd,Crd] = lp_dspmr(name,B0,C0,ZB0,ZC0,max_ord,tol); % run DSPMR\n\ndisp('Reduced order:')\ndisp(length(Ard))\n\nGrd = lp_trfia(freq,Ard,Brd,Crd,[],[]); % compute \"transfer function\n % sample\" for reduced system\nnrm_dGrd = lp_gnorm(G-Grd,m,q); % compute norm of DIFFERENCE of \n % transfer function samples of original \n % and reduced system.\nfigure(3); hold on\nloglog(freq,nrm_dGrd,'b--'); pause(1)\nt_text = [t_text, ', dashed: ||G-G_{DSPMR}||'];\ntitle(t_text); pause(1)\n\n\n% ----------------------------------------------------------------------- \n% Generate reduced systems of low order\n% ----------------------------------------------------------------------- \n\ndisp(' ')\ndisp('Generate reduced systems of low order')\ndisp('-------------------------------------')\n\ndisp('Parameters for model reduction:')\nmax_ord = 25 % (This criterion determines the reduced order.)\ntol = 0 % (avoided)\n\n\ndisp('... computing reduced system by LRSRM ...');\n[Ars,Brs,Crs] = lp_lrsrm(name,B0,C0,ZB0,ZC0,max_ord,tol); % run LRSRM\n\ndisp('Reduced order:')\ndisp(length(Ars))\n\nGrs = lp_trfia(freq,Ars,Brs,Crs,[],[]); % compute \"transfer function\n % sample\" for reduced system\nnrm_dGrs = lp_gnorm(G-Grs,m,q); % compute norm of DIFFERENCE of \n % transfer function samples of original \n % and reduced system.\nfigure(3); hold on\nloglog(freq,nrm_dGrs,'r-'); \n\n\ndisp('... computing reduced system by DSPMR ...');\n[Ard,Brd,Crd] = lp_dspmr(name,B0,C0,ZB0,ZC0,max_ord,tol); % run DSPMR\n\ndisp('Reduced order:')\ndisp(length(Ard))\n\nGrd = lp_trfia(freq,Ard,Brd,Crd,[],[]); % compute \"transfer function\n % sample\" for reduced system\nnrm_dGrd = lp_gnorm(G-Grd,m,q); % compute norm of DIFFERENCE of \n % transfer function samples of original \n % and reduced system.\nfigure(3); hold on\nloglog(freq,nrm_dGrd,'b--'); \n\n\n% ----------------------------------------------------------------------- \n% Destroy global data structures\n% ----------------------------------------------------------------------- \n\nmsns_m_d;\nmsns_l_d;\nmsns_s_d(p);\n\n\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/21-lyapack/lyapack/demos/demo_m2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619633, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5493120077357718}} {"text": "function [ xpoly, ypoly, zpoly, avg_resid ] = sv2poly( xpos, ypos, zpos, ...\n times, xvel, yvel, zvel )\n%SV2POLY Compute best fit polynomials from 3D state vectors\n%\n% This function determines a polynomial order that achieves good precision\n% without being unreasonably high or overfitting. One would generally only\n% use this function on state vectors from an orbital system, where the\n% positions/velocity would reasonably follow a smooth path.\n%\n% \"Optimal\" polynomial order depends on both the length of the collect\n% around its orbit and the noise in the state vector data.\n%\n% Written by: Wade Schwartzkopf, NGA/R\n%\n% //////////////////////////////////////////\n% /// CLASSIFICATION: UNCLASSIFIED ///\n% //////////////////////////////////////////\n\n% Check arguments\nif ~isequal(size(xpos), size(ypos), size(zpos), size(times)) || ...\n (exist('zvel','var') && ...\n ~isequal(size(xvel), size(yvel), size(zvel), size(times)))\n error('SV2POLY:INVALID_INPUT_ARGS','All state vector components must be same size/shape.');\nend\n% Vectorize inputs to assure column vectors\ntimes = times(:);\nxpos = xpos(:);\nypos = ypos(:);\nzpos = zpos(:);\nif exist('zvel', 'var')\n xvel = xvel(:);\n yvel = yvel(:);\n zvel = zvel(:);\nend\n\n% Because of the scale of the values used in orbital state vectors,\n% MATLAB's polyfit oftens detects them as badly conditioned, but results\n% work out OK anyway for reasonable polynomail orders. We will assure in\n% this function that polynomial order is reasonable.\nold_state = warning('off','MATLAB:polyfit:RepeatedPointsOrRescale');\n\n%% Method 1. Naive approach.\n% Hardcode polynomial order. This is usually sufficient. 5th order\n% generally works well for most spaceborne SAR collects of typical length\n% (< 200 s), often putting evaluation of the polynomials well within 1 mm\n% of error.\n% polyorder = min(5, numel(times) - 1);\n\nif exist('zvel', 'var')\n %% Method 2. Cross check with velocity.\n % One could also find the order of polynomial that most accurately\n % describes this position, but use velocity (which is presumably\n % measured independently) as cross-validation so that the data is not\n % being overfit.\n for polyorder = 1:(numel(times)-1)\n xpoly = polyfit(times, xpos, polyorder);\n ypoly = polyfit(times, ypos, polyorder);\n zpoly = polyfit(times, zpos, polyorder);\n error_list(polyorder) = mean(sqrt(sum(([xvel, yvel, zvel] - ...\n [polyval(polyder(xpoly), times), ...\n polyval(polyder(ypoly), times), ...\n polyval(polyder(zpoly), times)]).^2, 2)));\n end\n % Increase order only as long as it results in a \"significant\" decrease\n % (half) in the error of the velocity.\n polyorder = find(error_list(1:(end-1))<(2*error_list(2:end)), 1, 'first');\n if isempty(polyorder), polyorder = numel(error_list); end % All orders improve quality\nelse\n %% Method 3. \"Significant\" improvement.\n % One could also use the lowest order of polynomial that significantly\n % reduces the error of the position fit.\n for polyorder = 1:(numel(times)-2) % polyorder of n-1 will always be exact match\n % mu term used for error computation in loop since we are\n % potentially computing high order polynomials, generally well\n % beyond what is required for a good fit, and these will likely be\n % badly conditioned. For our final fit, after the polynomial order\n % is determined, we will assume order and fit is reasonable-- even\n % if MATLAB would have thrown a warning.\n [xpoly, ~, xmu] = polyfit(times, xpos, polyorder);\n [ypoly, ~, ymu] = polyfit(times, ypos, polyorder);\n [zpoly, ~, zmu] = polyfit(times, zpos, polyorder);\n error_list(polyorder) = mean(sqrt(sum(([xpos, ypos, zpos] - ...\n [polyval(xpoly, times, [], xmu), ...\n polyval(ypoly, times, [], ymu), ...\n polyval(zpoly, times, [], zmu)]).^2, 2)));\n end\n % Increasing polynomial order by one must result in error being cut in\n % half in order to be considered \"significant\".\n polyorder = find(error_list(1:(end-1))<(2*error_list(2:end)), 1, 'first');\n if isempty(polyorder), polyorder = numel(error_list); end % All orders improve quality\nend\n\n% Once optimal polynomial order is determined, do actual polynomial fit\nxpoly = polyfit(times, xpos, polyorder);\nypoly = polyfit(times, ypos, polyorder);\nzpoly = polyfit(times, zpos, polyorder);\n\nwarning(old_state);\n\n% Compute final residuals if requested\nif nargout>3\n avg_resid = mean(sqrt(sum(([xpos, ypos, zpos] - ...\n [polyval(xpoly, times), ...\n polyval(ypoly, times), ...\n polyval(zpoly, times)]).^2, 2)));\nend\n\n% //////////////////////////////////////////\n% /// CLASSIFICATION: UNCLASSIFIED ///\n% //////////////////////////////////////////", "meta": {"author": "ngageoint", "repo": "MATLAB_SAR", "sha": "6291feff8e200d387e271f49ec09b1acd5514c4e", "save_path": "github-repos/MATLAB/ngageoint-MATLAB_SAR", "path": "github-repos/MATLAB/ngageoint-MATLAB_SAR/MATLAB_SAR-6291feff8e200d387e271f49ec09b1acd5514c4e/IO/complex/sicd/sv2poly.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778258, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5493120027580012}} {"text": "function e = R2e(R)\n\n% R2E Rotation matrix to Euler angles conversion.\n% R2E(R) returns the euler angles vector [roll;pitch;yaw] corresponding\n% to the orientation of the rotation matrix R. The result is such that\n% E2R(R2E(R)) = R and R2E(E2R(E)) = E.\n%\n% See also E2R, FRAME.\n\n% Copyright 2008-2009 Joan Sola @ LAAS-CNRS.\n\ns = whos('R');\n\nif (strcmp(s.class,'sym'))\n roll = atan(R(3,2)/R(3,3));\n pitch = asin(-R(3,1));\n yaw = atan(R(2,1)/R(1,1));\nelse\n roll = atan2(R(3,2),R(3,3));\n pitch = atan2(-R(3,1), sqrt(R(1,1)^2+R(2,1)^2));\n yaw = atan2(R(2,1),R(1,1));\nend\n\ne = [roll;pitch;yaw];\n\n\n\n% ========== End of function - Start GPL license ==========\n\n\n% # START GPL LICENSE\n\n%---------------------------------------------------------------------\n%\n% This file is part of SLAMTB, a SLAM toolbox for Matlab.\n%\n% SLAMTB is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% SLAMTB is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with SLAMTB. If not, see .\n%\n%---------------------------------------------------------------------\n\n% SLAMTB is Copyright:\n% Copyright (c) 2008-2010, Joan Sola @ LAAS-CNRS,\n% Copyright (c) 2010-2013, Joan Sola,\n% Copyright (c) 2014-2015, Joan Sola @ IRI-UPC-CSIC,\n% SLAMTB is Copyright 2009 \n% by Joan Sola, Teresa Vidal-Calleja, David Marquez and Jean Marie Codol\n% @ LAAS-CNRS.\n% See on top of this file for its particular copyright.\n\n% # END GPL LICENSE\n\n", "meta": {"author": "joansola", "repo": "slamtb", "sha": "b4767f6bf38bceed205abb85f1aed12422c9a972", "save_path": "github-repos/MATLAB/joansola-slamtb", "path": "github-repos/MATLAB/joansola-slamtb/slamtb-b4767f6bf38bceed205abb85f1aed12422c9a972/FrameTransforms/Rotations/R2e.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673223709251, "lm_q2_score": 0.6757645879592642, "lm_q1q2_score": 0.5493069511675386}} {"text": "function [f1,f2,DialedNum] = DecodedFrequencies(E);\n\n%Computes the energy of the Signal\n%Input Variables\n% E = Energy Matrix of the Filtered Signals\n%\n% Output Variables\n% f1 = first decoded frequency \n% f2 = second decoded frequency\n\nFmat = [697 770 852 941 1209 1336 1477 1633];\n\nLowEnergyMatrix = E(1:4);\nHighEnergyMatrix = E(5:8);\n\n[e1,e1Index]=max(LowEnergyMatrix);\n[e2,e2Index]=max(HighEnergyMatrix);\n\nf1 = Fmat(e1Index);\nf2 = Fmat(4+e2Index);\n\nif f1 == Fmat(1) && f2 == Fmat(5) \n DialedNum = '1';\n elseif f1 == Fmat(1) && f2 == Fmat(6) \n DialedNum = '2';\n elseif f1 == Fmat(1) && f2 == Fmat(7) \n DialedNum = '3';\n elseif f1 == Fmat(1) && f2 == Fmat(8) \n DialedNum = 'A';\n elseif f1 == Fmat(2) && f2 == Fmat(5) \n DialedNum = '4';\n elseif f1 == Fmat(2) && f2 == Fmat(6) \n DialedNum = '5';\n elseif f1 == Fmat(2) && f2 == Fmat(7) \n DialedNum = '6';\n elseif f1 == Fmat(2) && f2 == Fmat(8) \n DialedNum = 'B';\n elseif f1 == Fmat(3) && f2 == Fmat(5) \n DialedNum = '7';\n elseif f1 == Fmat(3) && f2 == Fmat(6) \n DialedNum = '8';\n elseif f1 == Fmat(3) && f2 == Fmat(7) \n DialedNum = '9';\n elseif f1 == Fmat(3) && f2 == Fmat(8) \n DialedNum = 'C';\n elseif f1 == Fmat(4) && f2 == Fmat(5) \n DialedNum = '*';\n elseif f1 == Fmat(4) && f2 == Fmat(6) \n DialedNum = '0';\n elseif f1 == Fmat(4) && f2 == Fmat(7) \n DialedNum = '#';\n elseif f1 == Fmat(4) && f2 == Fmat(8) \n DialedNum = 'D';\nelse\n DialedNum = 'p';\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/20552-dtmf-filtering-and-noise-simulator/DTMF/DecodedFrequencies.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278540866548, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5492754518886669}} {"text": "function [nfm_Sharp_lunwrap, mask_sharp] = backgroundRemovalSharp(phase_lunwrap, mask_pad, filterMode)\n%BACKGROUNDREMOVALSHARP Background phase removal using SHARP (Sophisticated harmonic artifact reduction for phase data)\n% Code refractored from Berkin Bilgic's scripts: \"script_Laplacian_unwrap_Sharp_Fast_TV_gre3D.m\" \n% and \"script_Laplacian_unwrap_Sharp_Fast_TV_gre3D.m\"\n% Original source: https://martinos.org/~berkin/software.html\n%\n% phase_lunwrap: unwrapped phase volume\n% mask_pad: zero-padded mask volume\n% filterMode: 'once' or 'iterative'\n%\n% Original reference: \n% Bilgic et al. (2014), Fast quantitative susceptibility mapping with \n% L1-regularization and automatic parameter selection. Magn. Reson. Med.,\n% 72: 1444-1459. doi:10.1002/mrm.25029\n%\n% ... which references:\n%\n% Li W, Wu B, Liu C. Quantitative susceptibility mapping of \n% human brain reflects spatial variation in tissue composition. \n% NeuroImage 2011; 55(4): 1645?1656.\n%\n\n\n if nargin < 4\n filterMode = 'once';\n end\n switch filterMode\n case 'once'\n [nfm_Sharp_lunwrap, mask_sharp] = sharp_once(phase_lunwrap, mask_pad);\n case 'iterative'\n [nfm_Sharp_lunwrap, mask_sharp] = sharp_iterative(phase_lunwrap, mask_pad);\n end\n\nend\n\nfunction [nfm_Sharp_lunwrap, mask_sharp] = sharp_once(phase_lunwrap, mask_pad)\n\n N = size(mask_pad);\n\n ksize = [9, 9, 9]; % Sharp kernel size\n threshold = .05; % truncation level\n\n % calculate del kernel and its inverse\n del_sharp = calc_del_kernel(ksize, N);\n\n delsharp_inv = zeros(size(del_sharp));\n delsharp_inv( abs(del_sharp) > threshold ) = 1 ./ del_sharp( abs(del_sharp) > threshold );\n\n % erode mask to remove convolution artifacts\n mask_sharp = erode_mask(mask_pad, ksize);\n\n % apply Sharp to Laplacian wrapped phase\n phase_del = ifftn(fftn(phase_lunwrap) .* del_sharp);\n Phase_Del = phase_del .* mask_sharp;\n\n phase_Sharp_lunwrap = real( ifftn(fftn(Phase_Del) .* delsharp_inv) .* mask_sharp );\n\n nfm_Sharp_lunwrap = phase_Sharp_lunwrap;\nend\n\n\nfunction [nfm_Sharp_lunwrap, mask_sharp] = sharp_iterative(phase_lunwrap, mask_pad)\n\n N = size(mask_pad);\n\n threshold = .05; % truncation level\n\n Kernel_Sizes = 9:-2:3;\n\n % initiate volumes\n Phase_Del = zeros(N);\n mask_prev = zeros(N);\n\n for k = 1:length(Kernel_Sizes)\n\n disp(['Kernel size: ', num2str(Kernel_Sizes(k))])\n\n Kernel_Size = Kernel_Sizes(k);\n ksize = [Kernel_Size, Kernel_Size, Kernel_Size]; % Sharp kernel size\n\n % calculate del kernel and its inverse\n del_sharp = calc_del_kernel(ksize, N);\n\n if k == 1\n delsharp_inv = zeros(size(del_sharp));\n delsharp_inv( abs(del_sharp) > threshold ) = 1 ./ del_sharp( abs(del_sharp) > threshold );\n end\n\n % erode mask to remove convolution artifacts\n mask_sharp = erode_mask(mask_pad, ksize);\n\n % apply Sharp to Laplacian unwrapped phase\n phase_del = ifftn(fftn(phase_lunwrap) .* del_sharp);\n Phase_Del = Phase_Del + phase_del .* (mask_sharp - mask_prev);\n\n mask_prev = mask_sharp;\n\n end\n\n phase_Sharp_lunwrap = real( ifftn(fftn(Phase_Del) .* delsharp_inv) .* mask_sharp );\n nfm_Sharp_lunwrap = phase_Sharp_lunwrap;\n\nend\n\nfunction del_sharp = calc_del_kernel(ksize, N)\n\n khsize = (ksize-1)/2;\n [a,b,c] = meshgrid(-khsize(2):khsize(2), -khsize(1):khsize(1), -khsize(3):khsize(3));\n\n kernel = (a.^2 / khsize(1)^2 + b.^2 / khsize(2)^2 + c.^2 / khsize(3)^2 ) <= 1;\n kernel = -kernel / sum(kernel(:));\n kernel(khsize(1)+1,khsize(2)+1,khsize(3)+1) = 1 + kernel(khsize(1)+1,khsize(2)+1,khsize(3)+1);\n\n Kernel = zeros(N);\n Kernel( 1+N(1)/2 - khsize(1) : 1+N(1)/2 + khsize(1), 1+N(2)/2 - khsize(2) : 1+N(2)/2 + khsize(2), 1+N(3)/2 - khsize(3) : 1+N(3)/2 + khsize(3) ) = -kernel;\n\n del_sharp = fftn(fftshift(Kernel));\n\nend\n\nfunction mask_sharp = erode_mask(mask_pad, ksize)\n\n erode_size = ksize + 1;\n\n mask_sharp = imerode(mask_pad, strel('line', erode_size(1), 0));\n mask_sharp = imerode(mask_sharp, strel('line', erode_size(2), 90));\n mask_sharp = permute(mask_sharp, [1,3,2]);\n mask_sharp = imerode(mask_sharp, strel('line', erode_size(3), 0));\n mask_sharp = permute(mask_sharp, [1,3,2]);\n\nend", "meta": {"author": "qMRLab", "repo": "qMRLab", "sha": "036ff20b47e939877f746940a969494b55911636", "save_path": "github-repos/MATLAB/qMRLab-qMRLab", "path": "github-repos/MATLAB/qMRLab-qMRLab/qMRLab-036ff20b47e939877f746940a969494b55911636/src/Models_Functions/QSM/backgroundRemovalSharp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310357, "lm_q2_score": 0.6370308082623216, "lm_q1q2_score": 0.5488263819027259}} {"text": "function [channels,overall_amplitude] = eeg_amplitudearea(EEG, channels, resrate, wstart, wend)\n% EEG_AMPLITUDEAREA - Resamples an ERP average using spline interpolation \n% at a new sample rate (resrate) in Hz to get the exact limits \n% of the window of integration. Finely samples the window \n% and adds together very narrow rectangles capped by \n% right-angled triangles under the window. Output is in uV. \n% Trade-off between speed and number of resamples and number of \n% channels selected occurs.\n% Usage:\n% >> [channels, amplitude] = eeg_amplitudearea(EEG,channels, resrate, wstart, wend);\n% Inputs:\n% EEG - EEGLAB data struct containing a (3-D) epoched data matrix \n% channels - vector of channel indices\n% resrate - resampling rate for window of integration in Hz\n% wstart - start of window of integration in ms post stimulus-onset\n% wend - end of window of integration in ms post stimulus-onset\n%\n% Outputs:\n% channels - a vector of channel indices.\n% amplitude - 1-dimensional array in uV for the channels\n%\n% Example\n% >> [channels, amplitude] = eeg_amplitudearea(EEG,[12 18 25 29], 2000, 90.52, 120.52);\n%\n% Author: Tom Campbell, Helsinki Collegium for Advanced Studies, Biomag Laboratory, \n% Engineering Centre, Helsinki University Central Hospital Helsinki Brain \n% Research Centre (tom.campbell@helsinki.fi) Spartam nanctus es: Hanc exorna. \n% Combined with AMPLITUDEAREA_MSUV by Darren Weber, UCSF 28/1/05\n% Retested and debugged Tom Campbell 2/2/05\n% Reconceived, factored somewhat, tested and debugged Tom Campbell 13:24 23.3.2005\n\nif wstart > wend\n error ('ERROR: wstart must be greater than wend')\nelse\n [channels, overall_amplitude] = eeg_amplitudearea_msuV (EEG,channels, resrate, wstart, wend);\n overall_amplitude = overall_amplitude/(wend - wstart);\nend\n\nreturn\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [channels, overall_area] = eeg_amplitudearea_msuV (EEG, channels, resrate, wstart, wend)\n\n%if ndim(EEG.data) ~= 3\n% error('EEG.data must be 3-D data epochs');\n%end\nerp = mean(EEG.data,3);\n\n[tmp ind1] =min( abs( EEG.times - wstart ) ); % closest time index to wstart\n[tmp ind2] =min( abs( EEG.times - wend ) ); % closest time index to wend\nrestep = 1/resrate;\n\nif EEG.times(ind1) > wstart \n ind1= ind1 -1;\nend\n\nif EEG.times(ind2) < wend \n ind2= ind2 +1;\nend \n\nfor x= ind1:ind2\n t = (x -ind1)+1;\n tim(t) = EEG.times(x);\nend\n\ntr = 1;\ntimr(tr) = wstart;\nwhile timr(tr) < wend\n tr = tr + 1;\n timr(tr) = timr(tr-1)+ restep;\nend\n\nfor x = 1:size(channels,2)\n channel = channels(x);\n %resamples\n rerp(x, 1:tr) = spline(tim(:),erp(channel, ind1:ind2), timr(1:tr));\n pent = timr(tr - 1);\n overall_area(x) = 0;\n for y = 1:(tr -1)\n v1 = rerp(x,(y));\n v2 = rerp(x,(y+1));\n if ((v1 > 0) && (v2 < 0)) || ((v1 < 0) && (v2 > 0))\n if (y == (tr-1)) && (timr(y+1)> wend)\n area1 = zero_crossing_truncated(v1, v2, restep, wend, pent);\n else \n area1 = zero_crossing(v1, v2, restep);\n end\n else\n if( y == (tr-1)) && (timr(y+1)> wend)\n area1 = rect_tri_truncated(v1, v2, restep,wend,pent);\n else\n area1 = rect_tri(v1, v2, restep);\n end\n end\n overall_area(x) = overall_area(x) + area1;\n end\nend\n\nreturn\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [area] = zero_crossing(v1,v2,step)\n if (v1 > v2)\n T1 = v1;\n T2 = v2;\n else\n T1 = v2;\n T2 = v1;\n end\n tantheta = (abs(T1)+ abs(T2))/step;\n if (v1 > v2)\n %decline\n z = abs(T1)/tantheta;\n tr1= abs(T1)*(z/2);\n tr2= abs(T2)*((step-z)/2);\n else\n %incline\n z = abs(T2)/tantheta;\n tr2= abs(T2)*(z/2);\n tr1= abs(T1)*((step-z)/2);\n end\n [area] = (tr1 - tr2);\nreturn\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [area] = zero_crossing_truncated(v1,v2,step,wend,pent)\n if (v1 > v2)\n T1 = v1;\n T2 = v2;\n else\n T1 = v2;\n T2 = v1;\n end\n tantheta = (abs(T1)+ abs(T2))/step;\n s = wend - pent;\n if (v1 > v2)\n z = abs(T1)/tantheta\n if s < z \n %decline,truncated before zerocrossing\n t1 = tantheta * s;\n r1 = abs(T1)-abs(t1);\n tr1= abs(t1)*(s/2);\n tr2= 0;\n rect1 = r1*s;\n rect2 = 0;\n else\n %decline,truncated after zerocrossing\n t2= tantheta*(s-z);\n tr1= abs(T1)*(z/2);\n tr2 = abs(t2)*((s-z)/2);\n rect1 = 0;\n rect2 = 0;\n end \n else\n z = abs(T2)/tantheta;\n if s < z\n %incline,truncated before zerocrossing\n t2 = tantheta * s;\n r2 = abs(T2)-abs(t2);\n tr1= 0;\n tr2= abs(t2)*(s/2);\n rect1 = 0;\n rect2 = r2*s;\n else\n %incline,truncated after zerocrossing\n t1= tantheta*(s-z);\n tr1 = abs(t1)*((s-z)/2);\n tr2 = abs(T2) * (z/2);\n rect1 = 0;\n rect2 = 0;\n end\n end\n\n[area] = ((rect1 + tr1) - (rect2 + tr2));\nreturn\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [area] = rect_tri(v1,v2,step)\n if (abs(v1) > abs(v2))\n T = abs(v1)-abs(v2);\n R = abs(v2);\n else\n T = abs(v2)-abs(v1);\n R = abs(v1);\n end\n rect = R*step;\n tri = T*(step/2);\n if v1 > 0\n area = 1* (rect+tri);\n else\n area = -1 * (rect+tri);\n end\nreturn\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [area] = rect_tri_truncated(v1,v2,step,wend,pent)\n if (abs(v1) > abs(v2))\n T = abs(v1)-abs(v2);\n R = abs(v2);\n else\n T = abs(v2)-abs(v1);\n R = abs(v1);\n end\n \n tantheta = abs(T)/step;\n s = wend -pent;\n \n if (v1>0)\n if v1 >v2\n %positive decline\n t = tantheta*s;\n e = abs(T)-abs(t);\n rect = s*R;\n exrect = s*e;\n tri = (s/2)*R;\n else\n %positive incline\n t = tantheta*s;\n rect = s*R;\n exrect = 0;\n tri = (s/2)*R;\n end\n else\n if v1 >v2\n %negative decline\n t = tantheta*s;\n rect = s*R;\n exrect = 0;\n tri = (s/2)*R;\n else\n %negative incline \n t = tantheta*s;\n e = abs(T)-abs(t);\n rect = s*R;\n exrect = s*e;\n tri = (s/2)*R;\n end\n end\n tri = T*(step/2);\n if v1 > 0\n area = 1* (rect+exrect+tri);\n else\n area = -1 * (rect+exrect+tri);\n end\nreturn\n", "meta": {"author": "sccn", "repo": "eeglab", "sha": "36d3982a63cde83fb279ab465b7a026ec2807c0a", "save_path": "github-repos/MATLAB/sccn-eeglab", "path": "github-repos/MATLAB/sccn-eeglab/eeglab-36d3982a63cde83fb279ab465b7a026ec2807c0a/functions/popfunc/eeg_amplitudearea.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8615382094310357, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.5488263700290594}} {"text": "% Compute h-step Weisfeiler-Lehman shortest path delta kernel for a set of graphs\n% Author: Nino Shervashidze - nino.shervashidze@tuebingen.mpg.de\n% Copyright 2010 Nino Shervashidze\n% Input: Graphs - a 1xN array of graphs\n% \t\t Graphs(i).am is the adjacency matrix of the i'th graph, \n% \t\t Graphs(i).al is the adjacency list of the i'th graph, \n% Graphs(i).nl.values is a column vector of node\n% labels for the i'th graph.\n% Graphs(i).sp (may be missing) is the shortest\n% path length matrix of the i'th graph\n% Graphs(i) may have other fields, but they will not be\n% used here.\n%\t h - a natural number: number of iterations of WL\n%\t nl - a boolean: 1 if we want to use original node labels, 0 otherwise\n% spprec - a boolean: 1 if shortest paths are precomputed, 0\n% otherwise. Default: 0\n% Output: K - a h+1-element cell array of NxN kernel matrices K for\n% each iter = 0,...,h\n% runtime - scalar (total runtime in seconds)\n\nfunction [K,runtime] = WLspdelta(Graphs,h,nl,spprec)\n% THIS SOURCE CODE IS SUPPLIED \"AS IS\" WITHOUT WARRANTY OF ANY KIND, AND\n% ITS AUTHOR AND THE JOURNAL OF MACHINE LEARNING RESEARCH (JMLR) AND\n% JMLR'S PUBLISHERS AND DISTRIBUTORS, DISCLAIM ANY AND ALL WARRANTIES,\n% INCLUDING BUT NOT LIMITED TO ANY IMPLIED WARRANTIES OF MERCHANTABILITY\n% AND FITNESS FOR A PARTICULAR PURPOSE, AND ANY WARRANTIES OR NON \n% INFRINGEMENT. THE USER ASSUMES ALL LIABILITY AND RESPONSIBILITY FOR \n% USE OF THIS SOURCE CODE, AND NEITHER THE AUTHOR NOR JMLR, NOR JMLR'S\n% PUBLISHERS AND DISTRIBUTORS, WILL BE LIABLE FOR DAMAGES OF ANY KIND\n% RESULTING FROM ITS USE. Without limiting the generality of the foregoing, \n% neither the author, nor JMLR, nor JMLR's publishers and distributors,\n% warrant that the Source Code will be error-free, will operate without\n% interruption, or will meet the needs of the user.\n\nN=size(Graphs,2);\nLists = cell(1,N);\nK = cell(1,h+1);\nif nargin<4 spprec=0; end\nn_nodes=0;\n% compute adjacency lists and n_nodes, the total number of nodes in the dataset\nfor i=1:N\n Lists{i}=Graphs(i).al;\n n_nodes=n_nodes+size(Graphs(i).am,1);\nend\n% compute/copy shortest path matrices\nmaxpath = 0;\nif ~spprec\n disp('computing shortest paths...');\n for i=1:N\n Ds{i}=floydwarshall(Graphs(i).am);\n aux=max(Ds{i}(~isinf(Ds{i})));\n if aux > maxpath\n maxpath=aux;\n end\n end\nelse\n for i=1:N\n Ds{i}=Graphs(i).sp;\n aux=max(Ds{i}(~isinf(Ds{i})));\n if aux > maxpath\n maxpath=aux;\n end\n end\nend \nt=cputime; % for measuring runtime\n\n%%% INITIALISATION\n% initialize the node labels for each graph with their labels or \n% with degrees (for unlabeled graphs).\nlabel_lookup=containers.Map();\nlabel_counter=uint32(1);\n% label_lookup is an associative array, which will contain the\n% mapping from multiset labels (strings) to short labels (integers)\nif nl==1\n for i=1:N\n % the type of labels{i} is uint32, meaning that it can only handle\n % 2^32 labels and compressed labels over all iterations. If\n % more is needed, switching (all occurences of uint32) to\n % uint64 is a possibility\n labels{i}=zeros(size(Graphs(i).nl.values,1),1,'uint32');\n for j=1:length(Graphs(i).nl.values)\n str_label=num2str(Graphs(i).nl.values(j));\n % str_label is the node label of the current node of the\n % current graph converted into a string\n if ~isKey(label_lookup, str_label)\n %str_label\n %label_counter\n label_lookup(str_label)=label_counter;\n labels{i}(j)=label_counter;\n label_counter=label_counter+1;\n else\n labels{i}(j)=label_lookup(str_label);\n end\n end\n end\nelse\n for i=1:N\n labels{i}=uint32(full(sum(Graphs(i).am,2)));\n for j=1:length(labels{i})\n str_label=num2str(labels{i}(j));\n % str_label is the node label of the current node of the\n % current graph converted into a string\n if ~isKey(label_lookup, str_label)\n label_lookup(str_label)=label_counter;\n labels{i}(j)=label_counter; \n label_counter=label_counter+1;\n else\n labels{i}(j)=label_lookup(str_label);\n end\n end\n end\nend\nL=double(label_counter)-1;\nclear Graphs;\ndisp(['Number of original labels: ',num2str(L)]);\ndisp(['Number of potential shortest path features: ',num2str((maxpath+1)*L*(L+1)/2)]);\nsp=sparse((maxpath+1)*L*(L+1)/2,N);\nfor i=1:N\n labels_aux=repmat(double(labels{i}),1,length(labels{i}));\n a=min(labels_aux, labels_aux');\n b=max(labels_aux, labels_aux');\n I=triu(~(isinf(Ds{i})));\n Ind=Ds{i}(I)*L*(L+1)/2+(a(I)-1).*(2*L+2-a(I))/2+b(I)-a(I)+1;\n minind=min(Ind);\n diff=max(Ind)-minind;\n aux=accumarray(Ind,ones(nnz(I),1),[],[],[],(minind > 5000 || diff > 3000));\n % sparse of full accumarray depending on the range of values in Ind\n % (and based on empirical observations on the speed of accumarray)\n sp(Ind,i)=aux(Ind);\nend\nsp=sp(sum(sp,2)~=0,:);\nK{1}=full(sp'*sp);\n\n%%% MAIN LOOP\niter=1;\nnew_labels=labels;\nwhile iter<=h\n disp(['iter=',num2str(iter)]);\n % create an empty lookup table\n label_lookup=containers.Map();\n label_counter=uint32(1);\n for i=1:N\n for v=1:length(Lists{i})\n % form a multiset label of the node v of the i'th graph\n % and convert it to a string\n long_label=[labels{i}(v), sort(labels{i}(Lists{i}{v}))'];\n long_label_2bytes=typecast(long_label,'uint16');\n long_label_string=char(long_label_2bytes);\n % if the multiset label has not yet occurred, add it to the\n % lookup table and assign a number to it\n if ~isKey(label_lookup, long_label_string)\n label_lookup(long_label_string)=label_counter;\n new_labels{i}(v)=label_counter;\n label_counter=label_counter+1;\n else\n new_labels{i}(v)=label_lookup(long_label_string);\n end\n end\n end\n L=double(label_counter)-1;\n disp(['Number of compressed labels: ',num2str(L)]);\n disp(['Number of potential shortest path features: ',num2str((maxpath+1)*L*(L+1)/2)]);\n labels=new_labels;\n sp=sparse((maxpath+1)*L*(L+1)/2,N);\n for i=1:N\n labels_aux=repmat(double(labels{i}),1,length(labels{i}));\n a=min(labels_aux, labels_aux');\n b=max(labels_aux, labels_aux');\n I=triu(~(isinf(Ds{i})));\n Ind=Ds{i}(I)*L*(L+1)/2+(a(I)-1).*(2*L+2-a(I))/2+b(I)-a(I)+1;\n minind=min(Ind);\n diff=max(Ind)-minind;\n aux=accumarray(Ind,ones(nnz(I),1),[],[],[],(minind > 5000 || diff > 3000));\n % sparse of full accumarray depending on the range of values in Ind\n % (and based on empirical observations on the speed of accumarray)\n sp(Ind,i)=aux(Ind);\n end\n sp=sp(sum(sp,2)~=0,:);\n K{iter+1}=K{iter}+full(sp'*sp);\n iter=iter+1;\nend\nruntime=cputime-t; % computation time of K\nend\n\nfunction [D] = floydwarshall(A, sym, w)\n% Input: A - nxn adjacency matrix,\n% sym - boolean, 1 if A and w symmetric\n%\t w - nxn weight matrix\n% Output: D - nxn distance matrix\n\nn = size(A,1); % number of nodes\nD=zeros(n,n);\n\nif nargin<2 % if the graph is not weighted and we have no information about sym, then \n sym=1;\n w=A;\nend\n\nif nargin<3 % if the graph is not weighted, then\n w=A;\nend\n\nD=w.*A;\nD(A+diag(repmat(Inf,n,1))==0)=Inf; \nD=full(D.*(ones(n)-eye(n))); % set the diagonal to zero\n\nif sym % then it is a bit faster\n for k=1:n\n Daux=repmat(full(D(:,k)),1,n);\n Sumdist=Daux+Daux';\n D(Sumdist \n% Artificial bee colony algorithm\n% limit --- 20 --- The number of trials for releasing a food source\n\n%------------------------------- Reference --------------------------------\n% D. Karaboga, An idea based on honey bee swarm for numerical optimization,\n% Erciyes University, Tech. Rep. tr06, 2005.\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 limit = Algorithm.ParameterSet(20);\n \n %% Generate random population\n Population = Problem.Initialization();\n Limit = zeros(1,Problem.N);\n \n %% Optimization\n while Algorithm.NotTerminated(Population)\n % Employed bees\n Pdec = Population.decs;\n Odec = Pdec + (rand(size(Pdec))*2-1).*(Pdec-Pdec(randi(end,1,end),:));\n Offspring = Problem.Evaluation(Odec);\n replace = FitnessSingle(Population) > FitnessSingle(Offspring);\n Population(replace) = Offspring(replace);\n Limit(~replace) = Limit(~replace) + 1;\n \n % Onlooker bees\n Q = RouletteWheelSelection(Problem.N,exp(Population.objs/mean(abs(Population.objs+1e-6))));\n Pdec = Population.decs;\n Odec = Pdec(Q,:) + (rand(size(Pdec))*2-1).*(Pdec(Q,:)-Pdec(randi(end,1,end),:));\n Offspring = Problem.Evaluation(Odec);\n replace = FitnessSingle(Population) > FitnessSingle(Offspring);\n Population(replace) = Offspring(replace);\n Limit(~replace) = Limit(~replace) + 1;\n\n % Scout bees\n Q = Limit > limit;\n if any(Q)\n Population(Q) = Problem.Initialization(sum(Q));\n Limit(Q) = 0;\n end\n end\n end\n end\nend", "meta": {"author": "BIMK", "repo": "PlatEMO", "sha": "c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5", "save_path": "github-repos/MATLAB/BIMK-PlatEMO", "path": "github-repos/MATLAB/BIMK-PlatEMO/PlatEMO-c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5/PlatEMO/Algorithms/Single-objective optimization/ABC/ABC.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245911726382, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.5486754833054945}} {"text": "function out = EN_DistributionEntropy(y,histOrKS,numBins,olremp)\n% EN_DistributionEntropy Distributional entropy.\n%\n% Estimates of entropy from the distribution of a data vector. The\n% distribution is estimated either using a histogram with numBins bins, or as a\n% kernel-smoothed distribution, using the ksdensity function from Matlab's\n% Statistics Toolbox with width parameter, w (specified as the iunput numBins).\n%\n% An optional additional parameter can be used to remove a proportion of the\n% most extreme positive and negative deviations from the mean as an initial\n% pre-processing.\n%\n%---INPUTS:\n%\n% y, the input time series\n%\n% histOrKS: 'hist' for histogram, or 'ks' for ksdensity\n%\n% numBins: (*) (for 'hist'): an integer, uses a histogram with that many bins\n% (*) (for 'ks'): a positive real number, for the width parameter for\n% ksdensity (can also be empty for default width\n% parameter, optimum for Gaussian)\n%\n% olremp [opt]: the proportion of outliers at both extremes to remove\n% (e.g., if olremp = 0.01; keeps only the middle 98% of data; 0\n% keeps all data. This parameter ought to be less than 0.5, which\n% keeps none of the data).\n% If olremp is specified, returns the difference in entropy from\n% removing the outliers.\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 = 0; % plot outputs to figure\n\n% ------------------------------------------------------------------------------\n%% Check inputs\n% ------------------------------------------------------------------------------\nif nargin < 2 || isempty(histOrKS)\n histOrKS = 'hist'; % use histogram by default\nend\nif nargin < 3 % (can be empty for default width for ksdensity)\n numBins = 10; % use 10 bins\nend\nif nargin < 4\n olremp = 0;\nend\n\n% ------------------------------------------------------------------------------\n% (1) Remove outliers?\n% ------------------------------------------------------------------------------\nif olremp ~= 0\n yHat = y(y >= quantile(y,olremp) & y <= quantile(y,1-olremp));\n if isempty(yHat)\n % removed the entire time series?!\n % shouldn't be possible for good values of olremp with equality\n % in the above inequalities\n out = NaN; return\n else\n % Return the difference in entropy from removing outliers\n out = EN_DistributionEntropy(y,histOrKS,numBins) - ...\n EN_DistributionEntropy(yHat,histOrKS,numBins);\n return\n end\nend\n\n% ------------------------------------------------------------------------------\n% (2) Form the histogram\n% ------------------------------------------------------------------------------\nswitch histOrKS\ncase 'hist' % Use histogram to calculate pdf\n if isnumeric(numBins)\n [px,binEdges] = histcounts(y,numBins,'Normalization','probability');\n else\n [px,binEdges] = histcounts(y,'BinMethod',numBins,'Normalization','probability');\n end\n % Compute bin centers:\n xr = mean([binEdges(1:end-1); binEdges(2:end)]);\n % Compute bin widths:\n binWidths = diff(binEdges);\n\ncase 'ks' % Use ksdensity to calculate pdf\n if isempty(numBins)\n [px, xr] = ksdensity(y,'function','pdf'); % selects optimal width\n else\n [px, xr] = ksdensity(y,'width',numBins,'function','pdf'); % uses specified width\n end\n binWidths = ones(1,length(px))*(xr(2)-xr(1));\n\notherwise\n error('Unknown distribution method -- specify ''ks'' or ''hist''') % error; must specify 'ks' or 'hist'\nend\n\nif doPlot\n figure('color','w'); box('on');\n plot(xr,px,'k')\nend\n\n% ------------------------------------------------------------------------------\n% (3) Compute the entropy sum and return it as output\n% ------------------------------------------------------------------------------\n% 0*log0 = 0:\nout = -sum(px(px>0).*log(px(px>0)./binWidths(px>0)));\n\nend\n", "meta": {"author": "benfulcher", "repo": "hctsa", "sha": "919f2aed7cc8e1a3a03304c1ade573fa664c73f8", "save_path": "github-repos/MATLAB/benfulcher-hctsa", "path": "github-repos/MATLAB/benfulcher-hctsa/hctsa-919f2aed7cc8e1a3a03304c1ade573fa664c73f8/Operations/EN_DistributionEntropy.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.5486066041568843}} {"text": "function []=stvoldisp(beta_median,beta_std,beta_lbound,beta_ubound,sigma_median,sigma_t_median,sigma_t_lbound,sigma_t_ubound,gamma_median,X,Y,n,m,p,k,T,stvol,bex,ar,lambda1,lambda2,lambda3,lambda4,lambda5,gamma,alpha0,delta0,gamma0,zeta0,IRFt,const,endo,exo,startdate,enddate,stringdates1,decimaldates1,pref,PriorExcel)\n\n\n\n\n\n\n\n\n\n\n% before displaying and saving the results, start estimating the evaluation measures for the model\n\n\n% obtain first a point estimate betatilde of the VAR coefficients\n% this is simply the median\nbetatilde=beta_median;\nBtilde=reshape(betatilde,k,n);\n% use this estimate to produce predicted values for the model, following (a.8.2)\nYtilde=X*Btilde;\n% then produce the corresponding residuals, using (a.8.3)\nEPStilde=Y-Ytilde;\n\n\n% check first whether the model is stationary, using (a.7.2)\n[stationary eigmodulus]=bear.checkstable(betatilde,n,p,k);\n\n\n% Compute then the sum of squared residuals\n% compute first the RSS matrix, defined in (a.8.4)\nRSS=EPStilde'*EPStilde;\n% retain only the diagonal elements to get the vector of RSSi values\nrss=diag(RSS);\n\n\n% Go on calculating R2\n% generate Mbar\nMbar=eye(T)-ones(T,T)/T;\n% then compute the TSS matrix, defined in (a.8.7)\nTSS=Y'*Mbar*Y;\n% generate the R2 matrix in (a.8.8)\nR2=eye(n)-RSS./TSS;\n% retain only the diagonal elements to get the vector of R2 values\nr2=diag(R2);\n\n\n% then calculate the adjusted R2, using (a.8.9)\nR2bar=eye(n)-((T-1)/(T-k))*(eye(n)-R2);\n% retain only the diagonal elements to get the vector of R2bar values\nr2bar=diag(R2bar);\n\n\n\n\n\n\n\n% now start displaying and saving the results\n\n\n% preliminary task: create and open the txt file used to save the results\n\nfilelocation=fullfile(pref.results_path, [pref.results_sub '.txt']);\nfid=fopen(filelocation,'wt');\n\n% print toolbox header\n\nfprintf('%s\\n','');\nfprintf(fid,'%s\\n','');\n\n% print the list of contributors\nbear.printcontributors(fid);\n\n% print then estimation results\n\nfprintf('%s\\n','');\nfprintf(fid,'%s\\n','');\nfprintf('%s\\n','');\nfprintf(fid,'%s\\n','');\n\ntoolboxinfo='BEAR toolbox estimates';\nfprintf('%s\\n',toolboxinfo);\nfprintf(fid,'%s\\n',toolboxinfo);\n\ntime=clock;\ndatestring=datestr(time);\ndateinfo=['Date: ' datestring(1,1:11) ' Time: ' datestring(1,13:17)];\nfprintf('%s\\n',dateinfo);\nfprintf(fid,'%s\\n',dateinfo);\n\nfprintf('%s\\n','');\nfprintf(fid,'%s\\n','');\nfprintf('%s\\n','');\nfprintf(fid,'%s\\n','');\n\nVARtypeinfo='Stochastic volatility BVAR';\nfprintf('%s\\n',VARtypeinfo);\nfprintf(fid,'%s\\n',VARtypeinfo);\n\n\nif stvol==1\n modelinfo='Stochastic volatility model: standard';\nelseif stvol==2\n modelinfo='Stochastic volatility model: random inertia';\nelseif stvol==3\n modelinfo='Stochastic volatility model: large BVAR';\nend\nfprintf('%s\\n',modelinfo);\nfprintf(fid,'%s\\n',modelinfo);\n\n\nif IRFt==1\n SVARinfo='structural decomposition: none';\nelseif IRFt==2\n SVARinfo='structural decomposition: choleski factorisation';\nelseif IRFt==3\n SVARinfo='structural decomposition: triangular factorisation';\nelseif IRFt==4\n SVARinfo='structural decomposition: sign restrictions';\nend\nfprintf('%s\\n',SVARinfo);\nfprintf(fid,'%s\\n',SVARinfo);\n\ntemp='endogenous variables: ';\nfor ii=1:n\n temp=[temp ' ' endo{ii,1} ' '];\nend\nendoinfo=temp;\nfprintf('%s\\n',endoinfo);\nfprintf(fid,'%s\\n',endoinfo);\n\ntemp='exogenous variables: ';\nif const==0 && m==0\n temp=[temp ' none'];\nelseif const==1 && m==1\n temp=[temp ' constant '];\nelseif const==0 && m>0\n for ii=1:m-1\n temp=[temp ' ' exo{ii,1} ' '];\n end\nelseif const==1 && m>1\n temp=[temp ' constant '];\n for ii=1:m-1\n temp=[temp ' ' exo{ii,1} ' '];\n end\nend\nexoinfo=temp;\nfprintf('%s\\n',exoinfo);\nfprintf(fid,'%s\\n',exoinfo);\n\nsampledateinfo=['estimation sample: ' startdate '-' enddate];\nfprintf('%s\\n',sampledateinfo);\nfprintf(fid,'%s\\n',sampledateinfo);\n\nsamplelengthinfo=['sample size (omitting initial conditions): ' num2str(T)];\nfprintf('%s\\n',samplelengthinfo);\nfprintf(fid,'%s\\n',samplelengthinfo);\n\nlaginfo=['number of lags included in regression: ' num2str(p)];\nfprintf('%s\\n',laginfo);\nfprintf(fid,'%s\\n',laginfo);\n\nif PriorExcel==1\n arprint=[];\n for ii=1:n\n arprint=[arprint num2str(ar(ii,1)) ' '];\n end\n hyperparam2=['autoregressive coefficients (ar): ' arprint];\nelse\n hyperparam2=['autoregressive coefficients (ar): ' num2str(ar(1,1))];\nend\nfprintf('%s\\n',hyperparam2);\nfprintf(fid,'%s\\n',hyperparam2);\n\nhyperparam3=['overall tightness (lambda1): ' num2str(lambda1)];\nfprintf('%s\\n',hyperparam3);\nfprintf(fid,'%s\\n',hyperparam3);\n\nif stvol==1||stvol==2\n hyperparam4=['cross-variable weighting (lambda2): ' num2str(lambda2)];\n fprintf('%s\\n',hyperparam4);\n fprintf(fid,'%s\\n',hyperparam4);\nend\n\nhyperparam5=['lag decay (lambda3): ' num2str(lambda3)];\nfprintf('%s\\n',hyperparam5);\nfprintf(fid,'%s\\n',hyperparam5);\n\n%hyperparam6=['exogenous variable tightness (lambda4): ' num2str(lambda4)];\n%fprintf('%s\\n',hyperparam6);\n%fprintf(fid,'%s\\n',hyperparam6);\n\nif bex==1\n hyperparam7=['block exogeneity shrinkage (lambda5): ' num2str(lambda5)];\n fprintf('%s\\n',hyperparam7);\n fprintf(fid,'%s\\n',hyperparam7);\nend\n\nif stvol==1||stvol==3\n hyperparam8=['AR coefficient on residual variance (gamma): ' num2str(gamma)];\n fprintf('%s\\n',hyperparam8);\n fprintf(fid,'%s\\n',hyperparam8);\nend\n\nhyperparam9=['IG shape on residual variance (alpha0): ' num2str(alpha0)];\nfprintf('%s\\n',hyperparam9);\nfprintf(fid,'%s\\n',hyperparam9);\n\nhyperparam10=['IG scale on residual variance (delta0): ' num2str(alpha0)];\nfprintf('%s\\n',hyperparam10);\nfprintf(fid,'%s\\n',hyperparam10);\n\nif stvol==2\n hyperparam11=['Prior mean on inertia (gamma0): ' num2str(gamma)];\n fprintf('%s\\n',hyperparam11);\n fprintf(fid,'%s\\n',hyperparam11);\nend\n\nif stvol==2\n hyperparam12=['Prior variance on inertia (zeta0): ' num2str(gamma)];\n fprintf('%s\\n',hyperparam12);\n fprintf(fid,'%s\\n',hyperparam12);\nend\n\n\n\n\n\n\n\n% display coefficient estimates\n\n\nfprintf('%s\\n','');\nfprintf(fid,'%s\\n','');\nfprintf('%s\\n','');\nfprintf(fid,'%s\\n','');\nfprintf('%s\\n','');\nfprintf(fid,'%s\\n','');\n\n\ncoeffinfo=['VAR coefficients (beta): posterior estimates'];\nfprintf('%s\\n',coeffinfo);\nfprintf(fid,'%s\\n',coeffinfo);\n\n\nfor ii=1:n\n \n \n fprintf('%s\\n','');\n fprintf(fid,'%s\\n','');\n if ii~=1\n fprintf('%s\\n','');\n fprintf(fid,'%s\\n','');\n end\n \n \n endoinfo=['Endogenous: ' endo{ii,1}];\n fprintf('%s\\n',endoinfo);\n fprintf(fid,'%s\\n',endoinfo);\n \n \n coeffheader=fprintf('%25s %15s %15s %15s %15s\\n','','Median','St.dev','Low.bound','Upp.bound');\n coeffheader=fprintf(fid,'%25s %15s %15s %15s %15s\\n','','Median','St.dev','Low.bound','Upp.bound');\n \n \n % handle the endogenous\n for jj=1:n\n for kk=1:p\n values=[beta_median((ii-1)*k+n*(kk-1)+jj,1) beta_std((ii-1)*k+n*(kk-1)+jj,1) beta_lbound((ii-1)*k+n*(kk-1)+jj,1) beta_ubound((ii-1)*k+n*(kk-1)+jj,1)];\n fprintf('%25s %15.3f %15.3f %15.3f %15.3f\\n',strcat(endo{jj,1},'(-',int2str(kk),')'),values);\n fprintf(fid,'%25s %15.3f %15.3f %15.3f %15.3f\\n',strcat(endo{jj,1},'(-',int2str(kk),')'),values);\n end\n end\n \n \n % handle the exogenous\n % if there is no constant:\n if const==0\n % if there is no exogenous at all, obvioulsy, don't display anything\n if m==0\n % if there is no constant but some other exogenous, display them\n else\n for jj=1:m\n values=[beta_median(ii*k-m+jj,1) beta_std(ii*k-m+jj,1) beta_lbound(ii*k-m+jj,1) beta_ubound(ii*k-m+jj,1)];\n fprintf('%25s %15.3f %15.3f %15.3f %15.3f\\n',exo{jj,1},values);\n fprintf(fid,'%25s %15.3f %15.3f %15.3f %15.3f\\n',exo{jj,1},values);\n end\n end\n % if there is a constant\n else\n % display the results related to the constant\n values=[beta_median(ii*k-m+1,1) beta_std(ii*k-m+1,1) beta_lbound(ii*k-m+1,1) beta_ubound(ii*k-m+1,1)];\n fprintf('%25s %15.3f %15.3f %15.3f %15.3f\\n','Constant',values);\n fprintf(fid,'%25s %15.3f %15.3f %15.3f %15.3f\\n','Constant',values);\n % if there is no other exogenous, stop here\n if m==1\n % if there are other exogenous, display their results\n else\n for jj=1:m-1\n values=[beta_median(ii*k-m+jj+1,1) beta_std(ii*k-m+jj+1,1) beta_lbound(ii*k-m+jj+1,1) beta_ubound(ii*k-m+jj+1,1)];\n fprintf('%25s %15.3f %15.3f %15.3f %15.3f\\n',exo{jj,1},values);\n fprintf(fid,'%25s %15.3f %15.3f %15.3f %15.3f\\n',exo{jj,1},values);\n end\n end\n end\n \n \n fprintf('%s\\n','');\n fprintf(fid,'%s\\n','');\n \n \n % display evaluation measures\n rssinfo=['Sum of squared residuals: ' num2str(rss(ii,1),'%.2f')];\n fprintf('%s\\n',rssinfo);\n fprintf(fid,'%s\\n',rssinfo);\n \n \n r2info=['R-squared: ' num2str(r2(ii,1),'%.3f')];\n fprintf('%s\\n',r2info);\n fprintf(fid,'%s\\n',r2info);\n \n \n adjr2info=['adj. R-squared: ' num2str(r2bar(ii,1),'%.3f')];\n fprintf('%s\\n',adjr2info);\n fprintf(fid,'%s\\n',adjr2info);\n \n \nend\n\n\nfprintf('%s\\n','');\nfprintf(fid,'%s\\n','');\nfprintf('%s\\n','');\nfprintf(fid,'%s\\n','');\n\n\n\n% display VAR stability results\neigmodulus=reshape(eigmodulus,p,n);\nstabilityinfo1=['Roots of the characteristic polynomial (modulus):'];\nfprintf('%s\\n',stabilityinfo1);\nfprintf(fid,'%s\\n',stabilityinfo1);\nfor ii=1:p\n temp=num2str(eigmodulus(ii,1),'%.3f');\n for jj=2:n\n temp=[temp,' ',num2str(eigmodulus(ii,jj),'%.3f')];\n end\n fprintf('%s\\n',temp);\n fprintf(fid,'%s\\n',temp);\nend\nif stationary==1;\n stabilityinfo2=['No root lies outside the unit circle.'];\n stabilityinfo3=['The estimated VAR model satisfies the stability condition'];\n fprintf('%s\\n',stabilityinfo2);\n fprintf(fid,'%s\\n',stabilityinfo2);\n fprintf('%s\\n',stabilityinfo3);\n fprintf(fid,'%s\\n',stabilityinfo3);\nelse\n stabilityinfo2=['Warning: at leat one root lies on or outside the unit circle.'];\n stabilityinfo3=['The estimated VAR model will not be stable'];\n fprintf('%s\\n',stabilityinfo2);\n fprintf(fid,'%s\\n',stabilityinfo2);\n fprintf('%s\\n',stabilityinfo3);\n fprintf(fid,'%s\\n',stabilityinfo3);\nend\n\n\nfprintf('%s\\n','');\nfprintf(fid,'%s\\n','');\nfprintf('%s\\n','');\nfprintf(fid,'%s\\n','');\n\n\n% display posterior for sigma\nsigmainfo1=['sigma (residual covariance matrix): posterior estimates'];\nfprintf('%s\\n',sigmainfo1);\nfprintf(fid,'%s\\n',sigmainfo1);\n% calculate the (integer) length of the largest number in sigma, for formatting purpose\nwidth=length(sprintf('%d',floor(max(abs(bear.vec(sigma_median))))));\n% add a separator, a potential minus sign, and three digits (total=5) to obtain the total space for each entry in the matrix\nwidth=width+5;\nfor ii=1:n\n temp=[];\n for jj=1:n\n % convert matrix entry into string\n number=num2str(sigma_median(ii,jj),'% .3f');\n % pad potential missing blanks\n while numel(number).\n%\n% $Id$\n\n% these are used by the ft_preamble/ft_postamble function and scripts\nft_revision = '$Id$';\nft_nargin = nargin;\nft_nargout = nargout;\n\n% do the general setup of the function\nft_defaults\nft_preamble init\nft_preamble debug\nft_preamble provenance\nft_preamble randomseed\n\n% the ft_abort variable is set to true or false in ft_preamble_init\nif ft_abort\n return\nend\n\n% return immediately after distributed execution\nif ~isempty(ft_getopt(cfg, 'distribute'))\n return\nend\n\n% set defaults\nif ~isfield(cfg, 'method'), cfg.method = 'phalow_amphigh'; end\nif ~isfield(cfg, 'output'), cfg.output = 'all'; end\nif ~isfield(cfg, 'time'), cfg.time = []; end\n\nif isempty(cfg.time)\n cfg.fsample = ft_getopt(cfg, 'fsample', 1200);\n cfg.trllen = ft_getopt(cfg, 'trllen', 1);\n cfg.numtrl = ft_getopt(cfg, 'numtrl', 1);\n cfg.baseline = ft_getopt(cfg, 'baseline', 0);\nelse\n cfg.trllen = []; % can be variable\n cfg.fsample = 1/mean(diff(cfg.time{1})); % determine from time-axis\n cfg.numtrl = length(cfg.time);\nend\n\nif strcmp(cfg.method, 'superimposed')\n if ~isfield(cfg, 's1'), cfg.s1 = []; end\n if ~isfield(cfg.s1, 'freq'), cfg.s1.freq = 10; end\n if ~isfield(cfg.s1, 'phase'), cfg.s1.phase = 0; end\n if ~isfield(cfg.s1, 'ampl'), cfg.s1.ampl = 1; end\n if ~isfield(cfg, 's2'), cfg.s2 = []; end\n if ~isfield(cfg.s2, 'freq'), cfg.s2.freq = 20; end\n if ~isfield(cfg.s2, 'phase'), cfg.s2.phase = 0; end\n if ~isfield(cfg.s2, 'ampl'), cfg.s2.ampl = 0; end\n if ~isfield(cfg, 's3'), cfg.s3 = []; end\n if ~isfield(cfg.s3, 'freq'), cfg.s3.freq = 30; end\n if ~isfield(cfg.s3, 'phase'), cfg.s3.phase = 0; end\n if ~isfield(cfg.s3, 'ampl'), cfg.s3.ampl = 0; end\nend\n\nif strcmp(cfg.method, 'broadband')\n if ~isfield(cfg, 'n1'), cfg.n1 = []; end\n if ~isfield(cfg.n1, 'ampl'), cfg.n1.ampl = 1; end\n if ~isfield(cfg.n1, 'bpfreq'), cfg.n1.bpfreq = [30 50]; end\n if ~isfield(cfg, 'n2'), cfg.n2 = []; end\n if ~isfield(cfg.n2, 'ampl'), cfg.n2.ampl = 1; end\n if ~isfield(cfg.n2, 'bpfreq'), cfg.n2.bpfreq = [80 120]; end\nend\n\nif strcmp(cfg.method, 'phalow_amphigh')\n if ~isfield(cfg, 's1'), cfg.s1 = []; end\n if ~isfield(cfg.s1, 'freq'), cfg.s1.freq = 3; end\n if ~isfield(cfg.s1, 'phase'), cfg.s1.phase = -1*pi; end\n if ~isfield(cfg.s1, 'ampl'), cfg.s1.ampl = 1; end\n if ~isfield(cfg, 's2'), cfg.s2 = []; end\n if ~isfield(cfg.s2, 'freq'), cfg.s2.freq = 20; end\n if ~isfield(cfg.s2, 'phase'), cfg.s2.phase = 0; end\n if ~isfield(cfg.s2, 'ampl'), cfg.s2.ampl = 1; end\n if ~isfield(cfg, 's3'), cfg.s3 = []; end\n if ~isfield(cfg.s3, 'freq'), cfg.s3.freq = 0; end\n if ~isfield(cfg.s3, 'phase'), cfg.s3.phase = 0; end\n if ~isfield(cfg.s3, 'ampl'), cfg.s3.ampl = cfg.s1.ampl; end\nend\n\nif strcmp(cfg.method, 'amplow_amphigh')\n if ~isfield(cfg, 's1'), cfg.s1 = []; end\n if ~isfield(cfg.s1, 'freq'), cfg.s1.freq = 6; end\n if ~isfield(cfg.s1, 'phase'), cfg.s1.phase = 0; end\n if ~isfield(cfg.s1, 'ampl'), cfg.s1.ampl = 1; end\n if ~isfield(cfg, 's2'), cfg.s2 = []; end\n if ~isfield(cfg.s2, 'freq'), cfg.s2.freq = 20; end\n if ~isfield(cfg.s2, 'phase'), cfg.s2.phase = 0; end\n if ~isfield(cfg.s2, 'ampl'), cfg.s2.ampl = 1; end\n if ~isfield(cfg, 's4'), cfg.s4 = []; end\n if ~isfield(cfg.s4, 'freq'), cfg.s4.freq = 1; end\n if ~isfield(cfg.s4, 'phase'), cfg.s4.phase = -1*pi; end\n if ~isfield(cfg.s4, 'ampl'), cfg.s4.ampl = 1; end\n if ~isfield(cfg, 's3'), cfg.s3 = []; end\n if ~isfield(cfg.s3, 'freq'), cfg.s3.freq = 0; end\n if ~isfield(cfg.s3, 'phase'), cfg.s3.phase = 0; end\n if ~isfield(cfg.s3, 'ampl'), cfg.s3.ampl = cfg.s4.ampl; end\nend\n\nif strcmp(cfg.method, 'phalow_freqhigh')\n if ~isfield(cfg, 's1'), cfg.s1 = []; end\n if ~isfield(cfg.s1, 'freq'), cfg.s1.freq = 20; end\n if ~isfield(cfg.s1, 'phase'), cfg.s1.phase = 0; end\n if ~isfield(cfg.s1, 'ampl'), cfg.s1.ampl = 1; end\n if ~isfield(cfg, 's2'), cfg.s2 = []; end\n if ~isfield(cfg.s2, 'freq'), cfg.s2.freq = 2; end\n if ~isfield(cfg.s2, 'phase'), cfg.s2.phase = -0.5 * pi; end %then base freq at t=0\n if ~isfield(cfg.s2, 'ampl'), cfg.s2.ampl = pi; end\nend\n\nif strcmp(cfg.method, 'asymmetric')\n if ~isfield(cfg, 's1'), cfg.s1 = []; end\n if ~isfield(cfg.s1, 'freq'), cfg.s1.freq = 6; end\n if ~isfield(cfg.s1, 'phase'), cfg.s1.phase = 0; end\n if ~isfield(cfg.s1, 'ampl'), cfg.s1.ampl = 1; end\n if ~isfield(cfg, 'noise'), cfg.noise = []; end\n if ~isfield(cfg.noise, 'ampl'), cfg.noise.ampl = 0.1; end % default should not be too high\nend\n\nif ~isfield(cfg, 'noise'), cfg.noise = []; end\nif ~isfield(cfg.noise, 'ampl'), cfg.noise.ampl = 1; end\n\nif ~isempty(cfg.time)\n % use the user-supplied time vectors\n timevec = cfg.time;\nelse\n % give the user some feedback\n ft_debug('using %f as samping frequency', cfg.fsample);\n ft_debug('using %d trials of %f seconds long', cfg.numtrl, cfg.trllen);\n nsample = round(cfg.trllen*cfg.fsample);\n timevec = cell(1, cfg.numtrl);\n for iTr = 1:cfg.numtrl\n timevec{iTr} = (((1:nsample)-1)/cfg.fsample) - cfg.baseline;\n end\nend\n\n% give the user some feedback\nft_info('simulating data using %s method', cfg.method);\n\n%%%%%%% SUPERIMPOSED, SIMPLY ADD THE SIGNALS %%%%%%%%%\nif strcmp(cfg.method, 'superimposed')\n \n % make data\n for iTr = 1:length(timevec)\n if ischar(cfg.s1.phase); phase_s1 = rand * 2 * pi; else phase_s1 = cfg.s1.phase; end\n if ischar(cfg.s2.phase); phase_s2 = rand * 2 * pi; else phase_s2 = cfg.s2.phase; end\n if ischar(cfg.s3.phase); phase_s3 = rand * 2 * pi; else phase_s3 = cfg.s3.phase; end\n \n s1 = cfg.s1.ampl*cos(2*pi*cfg.s1.freq*timevec{iTr} + phase_s1);\n s2 = cfg.s2.ampl*cos(2*pi*cfg.s2.freq*timevec{iTr} + phase_s2);\n s3 = cfg.s3.ampl*cos(2*pi*cfg.s3.freq*timevec{iTr} + phase_s3);\n noise = cfg.noise.ampl*randn(size(timevec{iTr}));\n mix = s1 + s2 + s3 + noise;\n \n data.trial{iTr}(1,:) = mix;\n if strcmp(cfg.output, 'all')\n data.trial{iTr}(2,:) = s1;\n data.trial{iTr}(3,:) = s2;\n data.trial{iTr}(4,:) = s3;\n data.trial{iTr}(5,:) = noise;\n end\n data.time{iTr} = timevec{iTr};\n end % for iTr\n \n data.label{1} = 'mix';\n if strcmp(cfg.output, 'all')\n data.label{2} = 's1';\n data.label{3} = 's2';\n data.label{4} = 's3';\n data.label{5} = 'noise';\n end\n data.fsample = cfg.fsample;\n \n %%%%%%% SUPERIMPOSED BROADBAND SIGNAL %%%%%%%%%\nelseif strcmp(cfg.method, 'broadband')\n \n % make data\n for iTr = 1:length(timevec)\n n1 = ft_preproc_bandpassfilter(cfg.n1.ampl*randn(size(timevec{iTr})), cfg.fsample, cfg.n1.bpfreq);\n n2 = ft_preproc_bandpassfilter(cfg.n2.ampl*randn(size(timevec{iTr})), cfg.fsample, cfg.n2.bpfreq);\n noise = cfg.noise.ampl*randn(size(timevec{iTr}));\n mix = n1 + n2 + noise;\n \n data.trial{iTr}(1,:) = mix;\n if strcmp(cfg.output, 'all')\n data.trial{iTr}(2,:) = n1;\n data.trial{iTr}(3,:) = n2;\n data.trial{iTr}(4,:) = noise;\n end\n data.time{iTr} = timevec{iTr};\n end % for iTr\n \n data.label{1} = 'mix';\n if strcmp(cfg.output, 'all')\n data.label{2} = 'n1';\n data.label{3} = 'n2';\n data.label{4} = 'noise';\n end\n data.fsample = cfg.fsample;\n \n %%%%%%% PHASE TO AMPLITUDE CORRELATION %%%%%%%%%\nelseif strcmp(cfg.method, 'phalow_amphigh')\n \n % sanity checks\n if cfg.s2.freq < cfg.s1.freq\n ft_error('with method is phalow_amphigh freq s2 should be higher than freq s1')\n end\n if cfg.s2.freq > cfg.fsample/2\n ft_error('you cannot have a frequency higher than the sample frequency/2')\n end\n if cfg.s3.freq ~= 0 || cfg.s3.phase ~= 0\n ft_warning('for method phalow_amphigh s3 is DC and therefore expect freq and phase to be zero but they are not')\n end\n if cfg.s3.ampl < cfg.s1.ampl\n ft_warning('expect amplitude s3 (=DC) not to be smaller than amplitude s1 (=low frequency)')\n end\n \n % make data\n for iTr = 1:length(timevec)\n \n if ischar(cfg.s1.phase); phase_AM = rand * 2 * pi; else phase_AM = cfg.s1.phase; end\n if ischar(cfg.s2.phase); phase_high = rand * 2 * pi; else phase_high = cfg.s2.phase; end\n if ischar(cfg.s3.phase); phase_DC = rand * 2 * pi; else phase_DC = cfg.s3.phase; end\n high = cfg.s2.ampl*cos(2*pi*cfg.s2.freq*timevec{iTr} + phase_high);\n AM = cfg.s1.ampl*cos(2*pi*cfg.s1.freq*timevec{iTr} + phase_AM);\n DC = cfg.s3.ampl*cos(2*pi*0*timevec{iTr} + phase_DC);\n noise = cfg.noise.ampl*randn(size(timevec{iTr}));\n mix = ((AM + DC) .* high) + noise;\n \n data.trial{iTr}(1,:) = mix;\n if strcmp(cfg.output, 'all')\n data.trial{iTr}(2,:) = AM;\n data.trial{iTr}(3,:) = high;\n data.trial{iTr}(4,:) = DC;\n data.trial{iTr}(5,:) = noise;\n end\n data.time{iTr} = timevec{iTr};\n end % for iTr\n \n data.label{1} = 'mix';\n if strcmp(cfg.output, 'all')\n data.label{2} = 's1 (AM)';\n data.label{3} = 's2 (high)';\n data.label{4} = 's3 (DC)';\n data.label{5} = 'noise';\n end\n data.fsample = cfg.fsample;\n \n %%%%%%% POWER TO POWER CORRELATION %%%%%%%%%\nelseif strcmp(cfg.method, 'amplow_amphigh')\n \n % sanity checks\n if cfg.s2.freq < cfg.s1.freq || cfg.s1.freq < cfg.s4.freq\n ft_error('with method is powlow_powhigh freq s4 < s1 < s2')\n end\n if cfg.s2.freq > cfg.fsample/2\n ft_error('you cannot have a frequency higher than the sample frequency/2')\n end\n if cfg.s3.freq ~= 0 || cfg.s3.phase ~= 0\n ft_warning('for method powlow_powhigh s3 is DC and therefore expect freq and phase to be zero but they are not')\n end\n if cfg.s3.ampl < cfg.s4.ampl\n ft_warning('expect amplitude s3 (=DC) not to be smaller than amplitude s4 (= AM frequency)')\n end\n \n % make data\n for iTr = 1:length(timevec)\n \n if ischar(cfg.s1.phase); phase_low = rand * 2 * pi; else phase_low = cfg.s1.phase; end\n if ischar(cfg.s2.phase); phase_high = rand * 2 * pi; else phase_high = cfg.s2.phase; end\n if ischar(cfg.s3.phase); phase_DC = rand * 2 * pi; else phase_DC = cfg.s3.phase; end\n if ischar(cfg.s4.phase); phase_AM = rand * 2 * pi; else phase_AM = cfg.s4.phase; end\n high = cfg.s2.ampl*cos(2*pi*cfg.s2.freq*timevec{iTr} + phase_high);\n low = cfg.s1.ampl*cos(2*pi*cfg.s1.freq*timevec{iTr} + phase_low);\n AM = cfg.s4.ampl*cos(2*pi*cfg.s4.freq*timevec{iTr} + phase_AM);\n DC = cfg.s3.ampl*cos(2*pi*0*timevec{iTr} + phase_DC);\n noise = cfg.noise.ampl*randn(size(timevec{iTr}));\n lowmix = ((AM + DC) .* low);\n highmix = ((AM + DC) .* high);\n mix = lowmix + highmix + noise;\n \n data.trial{iTr}(1,:) = mix;\n if strcmp(cfg.output, 'all')\n data.trial{iTr}(2,:) = low;\n data.trial{iTr}(3,:) = high;\n data.trial{iTr}(4,:) = DC;\n data.trial{iTr}(5,:) = noise;\n data.trial{iTr}(6,:) = AM;\n data.trial{iTr}(7,:) = lowmix;\n data.trial{iTr}(8,:) = highmix;\n end\n data.time{iTr} = timevec{iTr};\n end % for iTr\n \n data.label{1} = 'mix';\n if strcmp(cfg.output, 'all')\n data.label{2} = 's1 (low)';\n data.label{3} = 's2 (high)';\n data.label{4} = 's3 (DC)';\n data.label{5} = 'noise';\n data.label{6} = 's4 (AM)';\n data.label{7} = 'mixlow';\n data.label{8} = 'mixhigh';\n end\n data.fsample = cfg.fsample;\n \n %%%%%%% PHASE TO FREQUENCY CORRELATION %%%%%%%%%\nelseif strcmp(cfg.method, 'phalow_freqhigh')\n \n % sanity checks\n if cfg.s1.freq > cfg.fsample/2 || cfg.s2.freq > cfg.fsample/2\n ft_error('you cannot have a frequency higher than the sample frequency/2')\n end\n \n % make data\n for iTr = 1:length(timevec)\n \n if ischar(cfg.s1.phase); phase_s1 = rand * 2 * pi; else phase_s1 = cfg.s1.phase; end\n if ischar(cfg.s2.phase); phase_s2 = rand * 2 * pi; else phase_s2= cfg.s2.phase; end\n s1 = cfg.s1.ampl .* cos(2*pi*cfg.s1.freq * timevec{iTr} + phase_s1); % to be modulated signal\n s2 = cfg.s2.ampl .* cos(2*pi*cfg.s2.freq * timevec{iTr} + phase_s2); % modulation of instantaneous phase\n inst_pha_base = 2*pi*cfg.s1.freq * timevec{iTr} + phase_s1; % unmodulated instantaneous phase s1 (linear)\n inst_pha_mod = s2; % modulation of instantaneous phase\n inst_pha = inst_pha_base + inst_pha_mod;\n noise = cfg.noise.ampl*randn(size(timevec{iTr}));\n mix = cfg.s1.ampl .* cos(inst_pha) + noise;\n \n data.trial{iTr}(1,:) = mix;\n if strcmp(cfg.output, 'all')\n data.trial{iTr}(2,:) = s1;\n data.trial{iTr}(3,:) = s2;\n data.trial{iTr}(4,:) = noise;\n data.trial{iTr}(5,:) = inst_pha_base;\n data.trial{iTr}(6,:) = inst_pha_mod;\n data.trial{iTr}(7,:) = inst_pha;\n end\n data.time{iTr} = timevec{iTr};\n end % for iTr\n \n data.label{1} = 'mix';\n if strcmp(cfg.output, 'all')\n data.label{2} = 's1';\n data.label{3} = 's2';\n data.label{4} = 'noise';\n data.label{5} = 'inst phase base';\n data.label{6} = 'inst phase modulation (=s2)';\n data.label{7} = 'inst phase';\n end\n data.fsample = cfg.fsample;\n \n %%%%%%% ASYMETRIC POSITIVE AND NEGATIVE PEAKS %%%%%%%%%\nelseif strcmp(cfg.method, 'asymmetric')\n \n % make data\n for iTr = 1:length(timevec)\n if ischar(cfg.s1.phase); phase_s1 = rand * 2 *pi; else phase_s1 = cfg.s1.phase; end\n \n s1 = cfg.s1.ampl*cos(2*pi*cfg.s1.freq*timevec{iTr} + phase_s1);\n tmp = cos(2*pi*cfg.s1.freq*timevec{iTr} + phase_s1); % same signal but with unit amplitude\n tmp = (tmp+1)/2; % scaled and shifted between 0 and 1\n tmp = tmp.^(cfg.asymmetry+1); % made asymmetric\n tmp = (tmp - mean(tmp))*2*cfg.s1.ampl; % rescale\n s2 = tmp;\n noise = cfg.noise.ampl*randn(size(timevec{iTr}));\n mix = s2 + noise;\n \n data.trial{iTr}(1,:) = mix;\n if strcmp(cfg.output, 'all')\n data.trial{iTr}(2,:) = s1;\n data.trial{iTr}(3,:) = s2;\n data.trial{iTr}(4,:) = noise;\n end\n data.time{iTr} = timevec{iTr};\n end % for iTr\n \n data.label{1} = 'mix';\n if strcmp(cfg.output, 'all')\n data.label{2} = 's1';\n data.label{3} = 's2';\n data.label{4} = 'noise';\n end\n data.fsample = cfg.fsample;\n \nelse\n ft_error('unknown method specified')\nend\n\n% do the general cleanup and bookkeeping at the end of the function\nft_postamble debug\nft_postamble randomseed\nft_postamble provenance data\nft_postamble history data\nft_postamble savevar data\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/ft_freqsimulation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5486056768357062}} {"text": "function [xu,yu,xl,yl,xc,yc]=GenerateNACASeries4Airfoil(afid,dotcount,xmod)\n\n%--------------------------------------------------------------------------\n%GenerateNACASeries4Airfoil\n%Version 1.20\n%Created by Stepen (zerocross_raptor@yahoo.com)\n%Created 20 November 2010\n%Last modified 30 November 2011\n%--------------------------------------------------------------------------\n%GenerateNACASeries4Airfoil generates the airfoil vertexes' coordinate of\n%the given NACA Series 4 Airfoil. The math equation used to generates the\n%airfoil coordinates is based on Theory of Wing Section Chapter 6 by Abbott\n%and Doenhoff.\n%--------------------------------------------------------------------------\n%Syntax:\n%[xu,yu,xl,yl,xc,yc]=GenerateNACASeries4Airfoil(afid,dotcount,xmod)\n%Input argument:\n%- afid (1 x 4 str) specifies NACA Series 4 Airfoil identifier.\n%- dotcount (1 x 1 int) specifies the number of vertexes to be generated on\n% the airfoil's camber/mean line.\n%- xmod (str) specifies the mode of airfoil vertex distribution. Enter\n% 'Uniform' to create uniform vertex distribution or 'Cosine' to create\n% vertex distribution based on cosine function (More vertex on the leading\n% edge region).\n%Output argument:\n%- xu (i x 1 num) specifies the x axis location of airfoil's upper surface\n% vertexes in fraction of chord. The airfoil's upper surface vertex are\n% arranged from leading edge (the first element of xu) to the trailing\n% edge (the last element of xu).\n%- yu (i x 1 num) specifies the y axis location of airfoil's upper surface\n% vertexes in fraction of chord. The airfoil's upper surface vertex are\n% arranged from leading edge (the first element of yu) to the trailing\n% edge (the last element of yu).\n%- xl (i x 1 num) specifies the x axis location of airfoil's lower surface\n% vertexes in fraction of chord. The airfoil's lower surface vertex are\n% arranged from leading edge (the first element of xl) to the trailing\n% edge (the last element of xl).\n%- yl (i x 1 num) specifies the y axis location of airfoil's lower surface\n% vertexes in fraction of chord. The airfoil's lower surface vertex are\n% arranged from leading edge (the first element of yl) to the trailing\n% edge (the last element of yl).\n%- xc (i x 1 num) specifies the x axis location of airfoil's camber line\n% vertexes in fraction of chord. The airfoil's camber line vertex are\n% arranged from leading edge (the first element of xc) to the trailing\n% edge (the last element of xc).\n%- yc (i x 1 num) specifies the y axis location of airfoil's camber line\n% vertexes in fraction of chord. The airfoil's camber line vertex are\n% arranged from leading edge (the first element of yc) to the trailing\n% edge (the last element of yc).\n%--------------------------------------------------------------------------\n\n%CodeStart-----------------------------------------------------------------\n%Checking input afid\n if ~ischar(afid)\n error('Airfoil identifier must be a string!')\n end\n if numel(afid)~=4\n error('Airfoil identifier must be a 4 digit number!')\n end\n if isempty(str2double(afid))\n error('Airfoil identifier must be a 4 digit number!')\n end\n%Checking input dotcount\n if numel(dotcount)~=1\n error('Number of vertex must be scalar!')\n end\n if (mod(dotcount,1~=0))||(dotcount<0)\n error('Number of vertex must be positive integer!')\n end\n%Checking input xmod\n if nargin<3\n xmod='Cosine';\n end\n if (~strcmpi(xmod,'Uniform'))&&(~strcmpi(xmod,'Cosine'))\n error('Vertex distribution input must be Uniform or Cosine!')\n end\n%Assigning identifier to equation coefficient\n id1=str2double(afid(1));\n id2=str2double(afid(2));\n id3=str2double(afid([3,4]));\n m=id1*(1/100); %Maximum camber\n p=id2*(10/100); %Maximum camber location\n t=id3*(1/100); %Maximum thickness\n if t==0\n warning(['Zero thickness airfoil!',...\n ' Airfoil will be just a camber line!'])\n end\n%Calculating x-axis location of camber line vertexes\n panelcount=dotcount-1;\n if strcmpi(xmod,'Uniform')\n panellength=1/panelcount;\n xc=(0:panellength:1)';\n elseif strcmpi(xmod,'Cosine')\n deltadeg=90/panelcount;\n xc=1-cosd(0:deltadeg:90)';\n end\n%Preallocating array for speed\n yc=zeros(dotcount,1);\n gc=zeros(dotcount,1);\n yt=zeros(dotcount,1);\n xu=zeros(dotcount,1);\n xl=zeros(dotcount,1);\n yu=zeros(dotcount,1);\n yl=zeros(dotcount,1);\n%Calculating y-axis location of camber line vertexes and camber gradient\n if m~=0\n for i=1:1:dotcount\n if xc(i)<=p\n yc(i)=(m/(p^2))*((2*p*xc(i))-(xc(i)^2));\n elseif xc(i)>p\n yc(i)=(m/((1-p)^2))*(1-(2*p)+(2*p*xc(i))-(xc(i)^2));\n end\n gc(i)=(m/p^2)*(2*p+2*xc(i));\n end\n end\n%Converting camber gradient to camber slope and normal\n sc=atand(gc);\n%Calculating thickness distribution\n for i=1:1:dotcount\n yt(i)=5*t*((0.29690*(xc(i)^0.5))-...\n (0.12600*xc(i))-...\n (0.35160*(xc(i)^2))+...\n (0.28430*(xc(i)^3))-...\n (0.10150*(xc(i)^4)));\n end\n%Generating airfoil vertexes\n for i=1:1:dotcount\n xu(i)=xc(i)-yt(i)*sind(sc(i));\n yu(i)=yc(i)+yt(i)*cosd(sc(i));\n xl(i)=xc(i)+yt(i)*sind(sc(i));\n yl(i)=yc(i)-yt(i)*cosd(sc(i));\n end\n%CodeEnd-------------------------------------------------------------------\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/34035-drawdatcomaircraft/GenerateNACASeries4Airfoil.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619134371953, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.5486056679561562}} {"text": "function [a,b,m,r,bbx,bby,f,g] = stokes_q2p1(xy,xyp,mv)\n%stokes_q2p1 vectorized Q2-P1 matrix generator\n% [A,B,Q,G,Bx,By,f,g] = stokes_q2p1(xy,xyp,mv);\n% input\n% xy Q2 nodal coordinate vector \n% xyp Q1 nodal coordinate vector \n% mv Q2 element mapping matrix\n% output\n% A Q2 vector diffusion matrix\n% B Q2-Q1 divergence matrix \n% Q Q1 mass matrix \n% G Q2 vector mass matrix \n% Bx Q2 x-derivative matrix \n% By Q2 y-derivative matrix \n% f velocity rhs vector\n% g pressure rhs vector\n%\n% Natural boundary conditions apply. Dirichlet conditions\n% must be explicitly enforced by calling function flowbc.\n% IFISS function: DJS; 7 March 2005.\n% Copyright (c) 2005 D.J. Silvester, H.C. Elman, A. Ramage \nnngpt=9; \nx=xy(:,1); y=xy(:,2);\nxp=xyp(:,1); yp=xyp(:,2);\nnvtx=length(x); nu=2*nvtx; np=3*length(xp); \nnel=length(mv(:,1)); mp=[[1:3:3*nel]',[2:3:3*nel]',[3:3:3*nel]'];\nlx=max(x)-min(x); ly=max(y)-min(y);\nhx=max(diff(x)); hy=max(diff(y));\nfprintf('setting up Q2-P1 matrices... ')\n%\n% initialise global matrices\n a = sparse(nu,nu);\n r = sparse(nu,nu);\n bbx = sparse(nvtx,nvtx);\n bby = sparse(nvtx,nvtx);\n bx = sparse(np,nvtx);\n by = sparse(np,nvtx);\n\t b = sparse(np,nu);\n m = sparse(np,np);\n f = zeros(nu,1);\n g = zeros(np,1);\n%\n%\n% Gauss point integration rules\n if (nngpt==4) % 2x2 Gauss points\n gpt=1.0e0/sqrt(3.0e0);\n s(1) = -gpt; t(1) = -gpt; wt(1)=1;\n s(2) = gpt; t(2) = -gpt; wt(2)=1;\n s(3) = gpt; t(3) = gpt; wt(3)=1; \n s(4) = -gpt; t(4) = gpt; wt(4)=1;\n elseif (nngpt==9) % 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 else\n\t error('Check Gauss point integration specification')\n end\n%\n% inner loop over elements \n for ivtx = 1:4\n xl_v(:,ivtx) = x(mv(:,ivtx));\n yl_v(:,ivtx) = y(mv(:,ivtx)); \n\t end\n ae = zeros(nel,9,9);\n re = zeros(nel,9,9);\n bbxe = zeros(nel,9,9);\n bbye = zeros(nel,9,9);\n bxe = zeros(nel,3,9);\n bye = zeros(nel,3,9);\n mpe = zeros(nel,3,3);\n ge = zeros(nel,3);\n% \n% loop over Gauss points\n for igpt = 1:nngpt\n sigpt=s(igpt);\n tigpt=t(igpt);\n wght=wt(igpt);\n% evaluate derivatives etc\n [jac,invjac,phi,dphidx,dphidy] = deriv(sigpt,tigpt,xl_v,yl_v);\n [psi,dpsidx,dpsidy] = qderiv(sigpt,tigpt,xl_v,yl_v); \n [chi,dchidx,dchidy] = lderiv(sigpt,tigpt,xl_v,yl_v);\n for j = 1:9\n for i = 1:9\n ae(:,i,j) = ae(:,i,j) + wght*dpsidx(:,i).*dpsidx(:,j).*invjac(:);\n ae(:,i,j) = ae(:,i,j) + wght*dpsidy(:,i).*dpsidy(:,j).*invjac(:);\n re(:,i,j) = re(:,i,j) + wght*psi(:,i).*psi(:,j).*jac(:);\n bbxe(:,i,j) = bbxe(:,i,j) - wght*psi(:,i) .*dpsidx(:,j); \n bbye(:,i,j) = bbye(:,i,j) - wght*psi(:,i) .*dpsidy(:,j); \n end\n\t for i=1:3\n bxe(:,i,j) = bxe(:,i,j) - wght*chi(:,i) .* dpsidx(:,j);\n bye(:,i,j) = bye(:,i,j) - wght*chi(:,i) .* dpsidy(:,j);\n end\n\t end\n\t for j=1:3\n\t for i=1:3\n mpe(:,i,j) = mpe(:,i,j) + wght*chi(:,i) .*chi(:,j) .*jac(:);\n\t end\n\t end\n%\n% end of Gauss point loop\n end \n%\n%% element assembly into global matrices\n% component velocity matrices ... \n for krow=1:9\n\t nrow=mv(:,krow);\t \n for kcol=1:9\n\t\t ncol=mv(:,kcol);\t \n a = a + sparse(nrow,ncol,ae(:,krow,kcol),nu,nu);\n\t\t a = a + sparse(nrow+nvtx,ncol+nvtx,ae(:,krow,kcol),nu,nu);\n r = r + sparse(nrow,ncol,re(:,krow,kcol),nu,nu);\n\t\t r = r + sparse(nrow+nvtx,ncol+nvtx,re(:,krow,kcol),nu,nu);\n bbx = bbx + sparse(nrow,ncol,bbxe(:,krow,kcol),nvtx,nvtx);\n bby = bby + sparse(nrow,ncol,bbye(:,krow,kcol),nvtx,nvtx);\n end\n for kcol=1:3\n\t\t ncol=mp(:,kcol);\t \n bx = bx + sparse(ncol,nrow,bxe(:,kcol,krow),np,nvtx);\n by = by + sparse(ncol,nrow,bye(:,kcol,krow),np,nvtx);\n\t\t end\n end\n%\n% vector velocity matrices ...\n\t b = [bx,by];\n% \n% pressure matrices ... \n\t for krow=1:3\n\t nrow=mp(:,krow);\t \n for kcol=1:3\n\t\t ncol=mp(:,kcol);\t \n m = m + sparse(nrow,ncol,mpe(:,krow,kcol),np,np);\n\t\t end\n\t end\n%\nfprintf('done\\n')\nreturn\n\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/toms866/stokes_flow/stokes_q2p1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.6654105454764747, "lm_q1q2_score": 0.5486056658948165}} {"text": "function RHOTPH2O = h2o_rhotp(P,X)\n% H2O_RHOTP Two-phase density of H2O in kg/m^3\n% H2O_RHOTP(P,X) Returns the two-phase density \n% of H2O at a given pressure and quality.\n% Called function: h2o_rhof(P), h2o_rhog(P)\n% Required Inputs are: P - pressure (kPa), X - quality (fraction)\n% ---------------------------------------------------------------\n% The MATLAB function was created by Tibor Balint, December 1998\n% TBoreal Research Corporation, Toronto, Ont. Canada \n% (tibor@netcom.ca) and also, University of Warwick, UK\n% ---------------------------------------------------------------\n\nformat long g; % set the format of the calculations\n\nRF=h2o_rhof(P);\nRG=h2o_rhog(P);\n\nINVRHOTP=(X/RG)+((1-X)/RF);\nRHOTPH2O=1/INVRHOTP;\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/237-pressuredrop/pressure_drop/h2o_rhotp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619979547273, "lm_q2_score": 0.6548947223065755, "lm_q1q2_score": 0.5485529039040508}} {"text": "function [model, varargout] = gmlvq_core(trainSet, trainLab, varargin)\n%GMLVQ_core.m - trains the Generalized Matrix LVQ algorithm\n%NOTE: minimal requirement version 7.4.0.336 (R2007a) \n%\n% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %% Use the wrapper GMLVQ.M to access the functionality in style of %%\n% %% the SOM Toolbox (i.e. with data structs). %%\n% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% example for usage:\n% trainSet = [1,2,3;4,5,6;7,8,9];\n% trainLab = [1;1;2];\n% GMLVQ_model=GMLVQ_train(trainSet,trainLab); % minimal parameters required\n% estimatedTrainLabels = GMLVQ_classify(trainSet, GMLVQ_model);\n% trainError = mean( trainLab ~= estimatedTrainLabels );\n%\n% input: \n% trainSet : matrix with training samples in its rows\n% trainLab : vector with the labels of the training set\n% optional parameters:\n% PrototypesPerClass: (default=1) the number of prototypes per class used. This could\n% be a number or a vector with the number for each class\n% initialPrototypes : (default=[]) a set of prototypes to start with. If not given initialization near the class means\n% initialMatrix : the matrix omega to start with. If not given random\n% initialization for rectangular matrices and Unity for squared omega\n% dim : (default=nb of features for training) the maximum rank or projection dimension\n% regularization : (default=0) values usually between 0 and 1 treat with care. \n% Regularizes the eigenvalue spectrum of omega'*omega to be more homogeneous\n% testSet : (default=[]) an optional test set used to compute\n% the test error. The last column is expected to be a label vector\n% comparable : (default=0) a flag which resets the random generator\n% to produce comparable results if set to 1\n% optimization : (default=fminlbfgs) indicates which optimization is used: sgd or fminlbfgs\n% parameter for the stochastic gradient descent sgd\n% nb_epochs : (default=100) the number of epochs for sgd\n% learningRatePrototypes: (default=[]) the learning rate for the prototypes. \n% Could be the start and end value used for a sigmoidal spectrum or a vector of length nb_epochs\n% learningRateMatrix : (default=[]) the learning rate for the matrix.\n% Could be the start and end value used for a sigmoidal spectrum or a vector of length nb_epochs\n% MatrixStart : (default=1) the epoch to start the matrix training\n% parameter for the build-in function fminlbfgs\n% threshstop : (default=0) the training error for early stopping\n% nb_reiterations : (default=100) the number of optimization reiterations performed\n% useEarlyStopping : (default=1) use early stopping based on threshstop\n% Display : (default=iter) the optimization output 'iter' or 'off'\n% GradObj : (default=on) use the gradient information or not\n% HessUpdate : (default=lbfgs) the update can be 'lbfgs', 'bfgs' or 'steepdesc'\n% TolFun : (default=1e-6) the tolerance\n% MaxIter : (default=2500) the maximal number of iterations\n% MaxFunEvals : (default=1000000) the maximal number of function evaluations\n% TolX : (default=1e-10) tolerance\n% DiffMinChange : (default=1e-10) minimal change\n%\n% output: the GMLVQ model with prototypes w their labels c_w and the matrix omega \n% optional output:\n% initialization : a struct containing the settings\n% trainError : error in the training set\n% testError : error in the training set (only computed if 'testSet' is given)\n% costs : the output of the cost function\n% \n% Citation information:\n% Petra Schneider, Michael Biehl, Barbara Hammer: \n% Adaptive Relevance Matrices in Learning Vector Quantization. Neural Computation 21(12): 3532-3561 (2009)\n% \n% K. Bunte, P. Schneider, B. Hammer, F.-M. Schleif, T. Villmann and M. Biehl, \n% Limited Rank Matrix Learning - Discriminative Dimension Reduction and Visualization, \n% Neural Networks, vol. 26, nb. 4, pp. 159-173, 2012.\n% \n% P. Schneider, K. Bunte, B. Hammer and M. Biehl, Regularization in Matrix Relevance Learning, \n% IEEE Transactions on Neural Networks, vol. 21, nb. 5, pp. 831-840, 2010.\n% \n% Kerstin Bunte (modified based on the code of Marc Strickert http://www.mloss.org/software/view/323/ and Petra Schneider)\n% uses the Fast Limited Memory Optimizer fminlbfgs.m written by Dirk-Jan Kroon available at the MATLAB central\n% kerstin.bunte@googlemail.com\n% Fri Nov 09 14:13:52 CEST 2012\n%\n% Conditions of GNU General Public License, version 2 and BSD License apply.\n% See file 'license-gpl2.txt' and 'BSD_license.txt' enclosed in this package.\n% Programs are not for use in critical applications!\n%\n\n% Contributed to SOM Toolbox vs2, December 3rd, 2012 by Alexander Schulz\n% Copyright (c) Kerstin Bunte\n% http://www.cis.hut.fi/projects/somtoolbox/\n\nnout = max(nargout,1)-1;\np = inputParser; % Create an instance of the class.\np.addRequired('trainSet', @isfloat);\np.addRequired('trainLab', @(x) length(x)==size(trainSet,1) & isnumeric(x));\n\np.addParamValue('PrototypesPerClass', ones(1,length(unique(trainLab))), @(x)(sum(~(x-floor(x)))/length(x)==1 && (length(x)==length(unique(trainLab)) || length(x)==1)));\np.addParamValue('initialPrototypes',[], @(x)(size(x,2)-1==size(trainSet,2) && isfloat(x)));\np.addParamValue('initialMatrix',[], @(x)(size(x,2)==size(trainSet,2) && isfloat(x)));\np.addParamValue('dim',size(trainSet,2), @(x)(~(x-floor(x)) && x<=size(trainSet,2) && x>0));\np.addParamValue('regularization',0, @(x)(isfloat(x) && x>=0));\np.addOptional('testSet', [], @(x)(size(x,2)-1)==size(trainSet,2) & isfloat(x));\np.addOptional('comparable', 0, @(x)(~(x-floor(x))));\np.addOptional('optimization', 'fminlbfgs', @(x)any(strcmpi(x,{'sgd','fminlbfgs'})));\n% parameter for the stochastic gradient descent\np.addOptional('nb_epochs', 100, @(x)(~(x-floor(x))));\np.addParamValue('learningRatePrototypes', [], @(x)(isfloat(x) || isa(x,'function_handle'))); % && (length(x)==2 || length(x)==p.Results.epochs)\np.addParamValue('learningRateMatrix', [], @(x)(isfloat(x) || isa(x,'function_handle')));\np.addOptional('MatrixStart', 1, @(x)(~(x-floor(x))));\n% parameter for the build-in function\np.addOptional('threshstop',0,@(x) isfloat(x));\np.addOptional('nb_reiterations',100,@(x)(~(x-floor(x))));\np.addOptional('useEarlyStopping',1,@(x)(~(x-floor(x))));\np.addOptional('Display', 'off', @(x)any(strcmpi(x,{'iter','off'})));\np.addOptional('GradObj', 'on', @(x)any(strcmpi(x,{'on','off'})));\np.addOptional('HessUpdate', 'lbfgs', @(x)any(strcmpi(x,{'lbfgs', 'bfgs', 'steepdesc'})));\np.addOptional('TolFun',1e-6,@(x) isfloat(x));\np.addOptional('MaxIter', 2500, @(x)(~(x-floor(x))));\np.addOptional('MaxFunEvals', 1000000, @(x)(~(x-floor(x))));\np.addOptional('TolX',1e-10,@(x) isfloat(x));\np.addOptional('DiffMinChange',1e-10,@(x)isfloat(x));\np.CaseSensitive = true;\np.FunctionName = 'GMLVQ';\n% Parse and validate all input arguments.\np.parse(trainSet, trainLab, varargin{:});\n\n%%% check if results should be comparable\nif p.Results.comparable,\n rng('default');\nend\n%%% set useful variables\nnb_samples = size(trainSet,1);\nnb_features = size(trainSet,2);\n% labels should be a row vector\nif size(trainLab,1)~=nb_samples, trainLab = trainLab';end\n\nclasses = unique(trainLab);\nnb_classes = length(classes);\ndim = p.Results.dim;\nMatrixStart = p.Results.MatrixStart;\ntestSet = p.Results.testSet;\n% global regularization;\nregularization = p.Results.regularization;\nif regularization, disp(['Regularize the eigenvalue spectrum of omega''*omega with ',num2str(regularization)]);end\n\ninitialization = rmfield(p.Results, 'trainSet');\ninitialization.trainSet = [num2str(nb_samples),'x',num2str(nb_features),' matrix'];\ninitialization = rmfield(initialization, 'trainLab');\ninitialization.trainLab = ['vector of length ',num2str(length(trainLab))];\nif ~isempty(testSet)\n initialization = rmfield(initialization, 'testSet');\n initialization.testSet = [num2str(size(testSet,1)),'x',num2str(size(testSet,2)),' matrix'];\nend\nswitch(p.Results.optimization)\ncase{'sgd'}\n initialization = rmfield(initialization, 'useEarlyStopping');\n initialization = rmfield(initialization, 'Display');\n initialization = rmfield(initialization, 'GradObj');\n initialization = rmfield(initialization, 'HessUpdate');\n initialization = rmfield(initialization, 'TolFun');\n initialization = rmfield(initialization, 'MaxIter');\n initialization = rmfield(initialization, 'MaxFunEvals');\n initialization = rmfield(initialization, 'TolX');\n initialization = rmfield(initialization, 'DiffMinChange');\n initialization = rmfield(initialization, 'nb_reiterations');\ncase{'fminlbfgs'}\n disp('The fminlbfgs optimization uses some global variables:');\n disp('threshstop earlystopped useEarlyStopping');\n initialization = rmfield(initialization, 'nb_epochs');\n initialization = rmfield(initialization, 'learningRatePrototypes');\n initialization = rmfield(initialization, 'learningRateMatrix');\n initialization = rmfield(initialization, 'MatrixStart');\n nb_reiterations = p.Results.nb_reiterations;\nend\n% Display all arguments.\n%disp 'Settings for GMLVQ:'\n%disp(initialization);\n\n%%% check the number of prototypes per class if one integer is given and turn\n%%% it into a vector\nnb_ppc = p.Results.PrototypesPerClass;\nif length(nb_ppc)~=nb_classes,\n nb_ppc = ones(1,nb_classes)*nb_ppc;\nend\n\n%%% initialize the prototypes\nif isempty(p.Results.initialPrototypes)\n % initialize near the class centers\n w = zeros(sum(nb_ppc),nb_features);\n c_w = zeros(sum(nb_ppc),1);\n actPos = 1;\n for actClass=1:nb_classes\n nb_prot_c = nb_ppc(actClass);\n classMean = mean(trainSet(trainLab==classes(actClass),:));\n % set the prototypes to the class mean and add a random variation between -0.1 and 0.1\n w(actPos:actPos+nb_prot_c-1,:) = classMean(ones(nb_prot_c,1),:)+(rand(nb_prot_c,nb_features)*2-ones(nb_prot_c,nb_features))/10;\n c_w(actPos:actPos+nb_prot_c-1) = classes(actClass);\n actPos = actPos+nb_prot_c;\n end\nelse\n % initialize with given w\n w = p.Results.initialPrototypes(:,1:end-1);\n c_w = p.Results.initialPrototypes(:,end);\nend\n%%% initialize the matrix\nif isempty(p.Results.initialMatrix)\n if(p.Results.dim==nb_features)\n omega = eye(nb_features);\n else % initialize with random numbers between -1 and 1\n omega = rand(dim,nb_features)*2-ones(dim,nb_features);\n end\nelse\n omega = p.Results.initialMatrix;\nend\n% normalize the matrix\nomega = omega / sqrt(sum(diag(omega'*omega)));\nmodel = struct('w',w,'c_w',c_w,'omega',omega);\nclear w c_w omega;\n\n% GMLVQ_algorithm = struct('update',@GMLVQ_update,'classify',@GMLVQ_classify,'costfun',@GLVQ_costfun);\nswitch(p.Results.optimization)\ncase{'sgd'}\n %%% gradient descent variables\n nb_epochs = p.Results.nb_epochs;\n % compute the vector of nb_epochs learning rates alpha for the prototype learning\n if isa(p.Results.learningRatePrototypes,'function_handle')\n % with a given function specified from the user\n alphas = arrayfun(p.Results.learningRatePrototypes, 1:nb_epochs);\n elseif length(p.Results.learningRatePrototypes)>2\n if length(p.Results.learningRatePrototypes)==nb_epochs\n alphas = p.Results.learningRatePrototypes;\n else\n disp('The learning rate vector for the prototypes does not fit the nb of epochs');\n return;\n end\n else\n % or use an decay with a start and a decay value\n if isempty(p.Results.learningRatePrototypes)\n initialization.learningRatePrototypes = [nb_features/100, nb_features/10000];\n end\n alpha_start = initialization.learningRatePrototypes(1);\n alpha_end = initialization.learningRatePrototypes(2);\n alphas = arrayfun(@(x) alpha_start * (alpha_end/alpha_start)^(x/nb_epochs), 1:nb_epochs);\n % alphas = arrayfun(@(x) alpha_start / (1+(x-1)*alpha_end), 1:nb_epochs);\n end\n % compute the vector of nb_epochs learning rates epsilon for the Matrix learning\n epsilons = zeros(1,nb_epochs);\n if isa(p.Results.learningRateMatrix,'function_handle')\n % with a given function specified from the user\n % \tepsilons = arrayfun(p.Results.learningRateMatrix, 1:nb_epochs);\n epsilons(MatrixStart:nb_epochs) = arrayfun(p.Results.learningRateMatrix, MatrixStart:nb_epochs);\n elseif length(p.Results.learningRateMatrix)>2\n if length(p.Results.learningRateMatrix)==nb_epochs\n epsilons = p.Results.learningRateMatrix;\n else\n disp('The learning rate vector for the Matrix does not fit the nb of epochs');\n return;\n end\n else\n % or use an decay with a start and a decay value\n if isempty(p.Results.learningRateMatrix)\n initialization.learningRateMatrix = [nb_features/1000, nb_features/100000];\n end\n eps_start = initialization.learningRateMatrix(1);\n eps_end = initialization.learningRateMatrix(2);\n % epsilons = arrayfun(@(x) eps_start * (eps_end/eps_start)^(x/nb_epochs), 1:nb_epochs);\n epsilons(MatrixStart:nb_epochs) = arrayfun(@(x) eps_start * (eps_end/eps_start)^((x-MatrixStart)/(nb_epochs-MatrixStart)), MatrixStart:nb_epochs);\n end\n \n %%% initialize requested outputs\n trainError = [];\n costs = [];\n testError = [];\n if nout>=2,\n % train error requested\n trainError = ones(1,nb_epochs+1);\n estimatedLabels = GMLVQ_classify(trainSet, model); % error after initialization\n trainError(1) = sum( trainLab ~= estimatedLabels )/nb_samples;\n if nout>=3,\n % test error requested\n if isempty(testSet)\n testError = [];\n disp('The test error is requested, but no labeled test set given. Omitting the computation.');\n else\n testError = ones(1,nb_epochs+1);\n estimatedLabels = GMLVQ_classify(testSet(:,1:end-1), model); % error after initialization\n testError(1) = sum( testSet(:,end) ~= estimatedLabels )/length(estimatedLabels);\n end \n if nout>=4,\n % costs requested\n% LabelEqPrototype = trainLab*ones(1,numel(model.c_w)) == (model.c_w*ones(1,nb_samples))';\n disp('The computation of the costs is an expensive operation, do it only if you really need it!');\n costs = ones(1,nb_epochs+1);\n costs(1) = GMLVQ_costfun(trainSet, trainLab, model, regularization);\n% costs(1) = sum(arrayfun(@(idx) GLVQ_costfun(min(dist(idx,model.c_w == trainLab(idx))),...\n% min(dist(idx,model.c_w ~= trainLab(idx))))-regTerm, 1:size(dist,1)));\n end\n end\n end\n \n %%% optimize with stochastic gradient descent\n for epoch=1:nb_epochs\n if mod(epoch,100)==0, disp(epoch); end\n % generate order to sweep through the trainingset\n order = randperm(nb_samples);\t\n % perform one sweep through trainingset\n for i=1:nb_samples\n % select one training sample randomly\n xi = trainSet(order(i),:);\n c_xi = trainLab(order(i));\n\n% dist = ((xi(ones(size(model.w,1),1),:))-model.w)*model.omega'*(model.omega*((xi(ones(size(model.w,1),1),:))-model.w)');\n% dist = diag(dist);\n dist = sum((bsxfun(@minus, xi, model.w)*model.omega').^2, 2);\n % determine the two winning prototypes\n % nearest prototype with the same class\n [sortDist,sortIdx] = sort(dist);\n count = 1;\n J = sortIdx(count);\n while model.c_w(sortIdx(count)) ~= c_xi, \n count = count+1;\n J = sortIdx(count);\n end\n dJ = sortDist(count);\n count = 1;\n K = sortIdx(count);\n while model.c_w(sortIdx(count)) == c_xi, \n count = count+1;\n K = sortIdx(count);\n end\n dK = sortDist(count);\n % disp([J,K,dJ,dK]);\n wJ = model.w(J,:);\n wK = model.w(K,:);\n % prototype update\n norm_factor = (dJ + dK)^2;\n DJ = (xi-wJ);\n DK = (xi-wK);\n\n oo = model.omega'*model.omega;\n\n dwJ = (2*dK/norm_factor)*2*oo*DJ';\n dwK = (2*dJ/norm_factor)*2*oo*DK';\n % dwJ = (2*dK/norm_factor)*2*model.omega'*model.omega*DJ';\n % dwK = (2*dJ/norm_factor)*2*model.omega'*model.omega*DK';\n model.w(J,:) = wJ + alphas(epoch) * dwJ';\n model.w(K,:) = wK - alphas(epoch) * dwK';\n % update matrices\n if epsilons(epoch)>0, % epoch >= MatrixStart\n f1 = (2*dK/norm_factor)*2*(model.omega*DJ')*DJ;\n f2 = (2*dJ/norm_factor)*2*(model.omega*DK')*DK;\n % update omega\n if regularization,\n f3 = (pinv(model.omega))'; \n else\n f3 = 0;\n end\n model.omega = model.omega-epsilons(epoch) * (f1-f2 - regularization * f3);\n % normalization\n model.omega = model.omega / sqrt(sum(diag(oo)));\n end\n end\n if nout>=2,\n % train error requested\n estimatedLabels = GMLVQ_classify(trainSet, model); % error after epoch\n trainError(epoch+1) = sum( trainLab ~= estimatedLabels )/nb_samples;\n if nout>=3,\n % test error requested\n if ~isempty(testSet)\n estimatedLabels = GMLVQ_classify(testSet(:,1:end-1), model); % error after initialization\n testError(epoch+1) = sum( testSet(:,end) ~= estimatedLabels )/length(estimatedLabels);\n end \n if nout>=4,\n % costs requested\n costs(epoch+1) = GMLVQ_costfun(trainSet, trainLab, model, regularization);\n% costs(epoch+1) = sum(arrayfun(@(idx) GLVQ_costfun(min(dist(idx,model.c_w == trainLab(idx))),...\n% min(dist(idx,model.c_w ~= trainLab(idx))))-regTerm, 1:size(dist,1)));\n end\n end\n end\n end\ncase{'fminlbfgs'}\n %%% optimization options\n options = struct( ...\n 'Display',p.Results.Display, ...\n 'GradObj',p.Results.GradObj, ...\n 'GradConstr',false, ...\n 'GoalsExactAchieve',0, ...\n 'TolFun',p.Results.TolFun, ...\n 'MaxIter',p.Results.MaxIter, ...\n 'MaxFunEvals', p.Results.MaxFunEvals, ...\n 'TolX',p.Results.TolX, ...\n 'DiffMinChange',p.Results.DiffMinChange, ...\n 'OutputFcn','LVQ_progresser', ...\n 'HessUpdate',p.Results.HessUpdate ...\n );\n clear('progresser'); % memory therein might need reset \n global threshstop earlystopped useEarlyStopping % for LVQ_progresser.m datval labval n_vec\n useEarlyStopping = p.Results.useEarlyStopping; % use early stopping\n earlystopped = false;\n threshstop = p.Results.threshstop; % stop if classification below this threshold for early stopping\n% prototypeLabel = model.c_w;\n nb_prototypes = numel(model.c_w);\n% LabelEqualsPrototype = trainLab*ones(1,nb_prototypes) == (model.c_w*ones(1,nb_samples))'; \n LabelEqualsPrototype = bsxfun(@eq,trainLab,model.c_w');\n earlystopped = false; % don't change, assigned in progresser.m\n clear('progresser'); % memory therein might need reset\n newfval = realmax('single');\n % fminlbfgs optimizer courtesy of Dirk-Jan Kroon: \n % http://www.mathworks.de/matlabcentral/fileexchange/23245\n % early stopping to be implemented in progresser function \n variables = zeros(dim+nb_prototypes,size(trainSet,2));\n variables(1:nb_prototypes,:) = model.w;\n variables(nb_prototypes+1:end,:) = model.omega; \n LRprototypes = 1; % learn prototype locations\n LRrelevances = 0; % don't learn metric\n% [variables,fval] = fminlbfgs(@GMLVQ_optfun,variables,options);\n [variables,fval] = fminlbfgs(@(variables) GMLVQ_optfun(variables,trainSet,LabelEqualsPrototype,LRrelevances,LRprototypes,model.c_w,regularization),variables,options);\n if not(isempty(fval))\n newfval = fval;\n end\n LRprototypes = 0; % don't learn prototype locations\n LRrelevances = 1; % learn metric\n% [variables,fval] = fminlbfgs(@GMLVQ_optfun,variables,options); \n [variables,fval] = fminlbfgs(@(variables) GMLVQ_optfun(variables,trainSet,LabelEqualsPrototype,LRrelevances,LRprototypes,model.c_w,regularization),variables,options);\n \n if not(isempty(fval))\n newfval = fval;\n end\n if not(isempty(fval))\n clear('progresser'); % memory therein might need reset\n LRprototypes = 1; \n for i = 1:nb_reiterations % depending on data, re-iterations might further improve\n% [variables,fval] = fminlbfgs(@GMLVQ_optfun,variables,options);\n [variables,fval] = fminlbfgs(@(variables) GMLVQ_optfun(variables,trainSet,LabelEqualsPrototype,LRrelevances,LRprototypes,model.c_w,regularization),variables,options);\n if not(isempty(fval))\n if abs(fval - newfval) < 1e-3 \n newfval = fval;\n break\n end\n newfval = fval;\n end\n if isempty(fval) || earlystopped\n break\n end\n end\n end\n model.w = variables(1:nb_prototypes,:);\n model.omega = variables(nb_prototypes+1:end,:);\n model.omega = model.omega / sqrt(sum(diag(model.omega'*model.omega)));\n if nout>=2,\n % train error requested\n estimatedLabels = GMLVQ_classify(trainSet, model); % error after initialization\n trainError = mean( trainLab ~= estimatedLabels );\n if nout>=3,\n % test error requested\n if isempty(testSet)\n testError = [];\n disp('The test error is requested, but no labeled test set given. Omitting the computation.');\n else\n estimatedLabels = GMLVQ_classify(testSet(:,1:end-1), model); % error after initialization\n testError = mean( testSet(:,end) ~= estimatedLabels );\n end \n if nout>=4,\n % costs requested\n costs = GMLVQ_costfun(trainSet, trainLab, model, regularization);\n% dist = computeDistance(trainSet, model.w, model);\n% if regularization,\n% regTerm = regularization * log(det(model.omega*model.omega'));\n% else\n% regTerm = 0;\n% end\n% costs = sum(arrayfun(@(idx) GLVQ_costfun(min(dist(idx,model.c_w == trainLab(idx))),...\n% min(dist(idx,model.c_w ~= trainLab(idx)))), 1:size(dist,1)))-regTerm;\n end\n end\n end\nend\n%%% output of the training\nvarargout = cell(nout);\nfor k=1:nout\n\tswitch(k)\n\t\tcase(1)\n\t\t\tvarargout(k) = {initialization};\n\t\tcase(2)\n\t\t\tvarargout(k) = {trainError};\n\t\tcase(3)\n\t\t\tvarargout(k) = {testError};\n\t\tcase(4)\n varargout(k) = {costs};\n\tend\nend\n\n\n\n\n\nfunction cost = GMLVQ_costfun(trainSet, trainLab, model, regularization)\n%GMLVQ_costfun.m - computes the costs for a given training set and GMLVQ\n%model with or without regularization\n% example for usage:\n% trainSet = [1,2,3;4,5,6;7,8,9];\n% trainLab = [1;1;2];\n% GMLVQ_model=GMLVQ_train(trainSet,trainLab); % minimal parameters required\n% costs = GMLVQ_costfun(trainSet, trainLab, GMLVQ_model, 0);\n%\n% input: \n% trainSet : matrix with training samples in its rows\n% trainLab : a vector of training labels\n% model : GMLVQ model with prototypes w their labels c_w and the matrix omega\n% regularization: the factor>=0 for the regularization\n% \n% output : cost function value\n% \n% Kerstin Bunte (based on the code from Marc Strickert)\n% kerstin.bunte@googlemail.com\n% Mon Nov 05 09:05:52 CEST 2012\n%\n% Conditions of GNU General Public License, version 2 apply.\n% See file 'license-gpl2.txt' enclosed in this package.\n% Programs are not for use in critical applications!\n%\nnb_samples = length(trainLab);\n% labels should be a row vector\nif size(trainLab,1)~=nb_samples, trainLab = trainLab';end\n\n% LabelEqPrototype = trainLab*ones(1,numel(model.c_w)) == (model.c_w*ones(1,nb_samples))';\nLabelEqPrototype = bsxfun(@eq,trainLab,model.c_w');\ndists = computeDistance(trainSet, model.w, model);\nif regularization,\n regTerm = regularization * log(det(model.omega*model.omega'));\n% if strcmp(p.Results.optimization,'sgd') \nelse\n regTerm = 0;\nend\nDwrong = dists;\nDwrong(LabelEqPrototype) = realmax(class(Dwrong)); % set correct labels impossible\ndistwrong = min(Dwrong.'); % closest wrong\nclear Dwrong;\n\nDcorrect = dists;\nDcorrect(~LabelEqPrototype) = realmax(class(Dcorrect)); % set wrong labels impossible\ndistcorrect = min(Dcorrect.'); % closest correct\nclear Dcorrect;\nclear dists;\ndistcorrectpluswrong = distcorrect + distwrong;\ndistcorrectminuswrong = distcorrect - distwrong;\nmu = distcorrectminuswrong ./ distcorrectpluswrong;\nif regularization,\n regTerm = regularization * log(det(model.omega*model.omega'));\nelse\n regTerm = 0;\nend\ncost = sum(mu)-regTerm;\n\n\n\n\n\n\n\nfunction [f G] = GMLVQ_optfun(variables,training_data,LabelEqualsPrototype,LRrelevances,LRprototypes,prototypeLabel,regularization)\n% [f G] = GMLVQ_optfun(variables) \n% function to be optimzed by matrix relevance learning vector quantization\n% variables = [prototype matrix;omega matrix]\n% global variables are\n% training_data : data vectors as row vectors, i.e. attributes in columns\n% LabelEqualsPrototype : binary matrix indicating coocurrences of\n% training labels and prototype labels\n% prototypeLabel : label vector for the prototypes\n% regularization : the regularization parameter\n% LRrelevances : learning rate for the relevance matrix\n% LRprototypes : learning rate for the prototypes\n%\n% Kerstin Bunte (modified based on the code of Marc Strickert http://www.mloss.org/software/view/323/)\n% kerstin.bunte@googlemail.com\n% Fri Nov 09 14:13:52 CEST 2012\n%\n% Conditions of GNU General Public License, version 2 apply.\n% See file 'license-gpl2.txt' enclosed in this package.\n% Programs are not for use in critical applications!\n% \nif isempty(LRprototypes) % values between 1e-2,1e-3,... 1e-8 seem pragmatic\n LRprototypes = 1; % no relevance learning by default\nend\nif isempty(LRrelevances) % values between 1e-2,1e-3,... 1e-8 seem pragmatic\n LRrelevances = 0; % no relevance learning by default\nend\n[n_data, n_dim] = size(training_data);\nnb_prototypes = numel(prototypeLabel);\nomegaT = variables(nb_prototypes+1:end,:)';\nn_vec = size(variables,1) - nb_prototypes;\n\ndists = squaredEuclidean(training_data*omegaT, variables(1:nb_prototypes,:)*omegaT);\n\nDwrong = dists;\nDwrong(LabelEqualsPrototype) = realmax(class(Dwrong)); % set correct labels impossible\n[distwrong pidxwrong] = min(Dwrong.'); % closest wrong\nclear Dwrong;\n\nDcorrect = dists;\nDcorrect(~LabelEqualsPrototype) = realmax(class(Dcorrect)); % set wrong labels impossible\n[distcorrect pidxcorrect] = min(Dcorrect.'); % closest correct\nclear Dcorrect;\n\ndistcorrectpluswrong = distcorrect + distwrong;\ndistcorrectminuswrong = distcorrect - distwrong;\nmu = distcorrectminuswrong ./ distcorrectpluswrong;\n% callitq = 1./(1 + exp(-squashsigmoid * mu)); % apply sigmoidal\n\nif regularization,\n regTerm = regularization * log(det(omegaT'*omegaT));\nelse\n regTerm = 0;\nend\nf = sum(mu)-regTerm;\n% f = mean(callitq);\n\nif nargout > 1 % gradient needed not just function eval\n G = zeros(size(variables)); % initially no gradient\n % callitq = squashsigmoid * callitq .* (1-callitq); % derivative of sigmoid\n % distcorrectpluswrong = 2 * callitq ./ distcorrectpluswrong.^2; % degeneration?\n distcorrectpluswrong = 4 ./ distcorrectpluswrong.^2; % norm_factor for derivative for every data sample\n if LRrelevances > 0\n Gw = zeros(n_vec,n_dim);\n end\n for k=1:nb_prototypes%(n_vec+1):size(lambda,1) % update all prototypes \n idxc = (k == pidxcorrect); % Js: idxs where actual prototype is nearest correct\n idxw = (k == pidxwrong); % Ks: idxs where actual prototype is nearest wrong\n\n dcd = distcorrect(idxw) .* distcorrectpluswrong(idxw);\n dwd = distwrong(idxc) .* distcorrectpluswrong(idxc);\n if LRrelevances > 0\n % part of derivative of distance\n difc = bsxfun(@minus,training_data(idxc,:),variables(k,:)); % DJs\n difw = bsxfun(@minus,training_data(idxw,:),variables(k,:)); % DKs\n % update omega \n Gw = Gw - (bsxfun(@times,difw,dcd.') * omegaT).' * difw + ...\n (bsxfun(@times,difc,dwd.') * omegaT).' * difc;\n if LRprototypes > 0\n G(k,:) = dcd * difw - dwd * difc;\n end\n else\n if LRprototypes > 0\n G(k,:) = dcd * training_data(idxw,:) - dwd * training_data(idxc,:) + (sum(dwd)-sum(dcd)) * variables(k,:);\n end\n end\n end\nif regularization,\n f3 = (pinv(omegaT'))'; \nelse\n f3 = 0;\nend \n % some rescalings needed\n if LRrelevances > 0\n G(nb_prototypes+1:nb_prototypes+n_vec,:) = 2/n_data * LRrelevances * Gw - regularization*f3;\n end\n if LRprototypes > 0\n G(1:nb_prototypes,:) = 1./n_data * LRprototypes * G(1:nb_prototypes,:) * omegaT * omegaT.';\n end\n G = G .* (1 + .0001 * (rand(size(G))-.5)); % help break symmetries\nend\n% if 0,\n% w = variables(1:nb_prototypes,:);\n% dJs = zeros(1,nb_samples);\n% dKs = zeros(1,nb_samples);\n% Js = zeros(1,nb_samples);\n% Ks = zeros(1,nb_samples);\n% norm_factors = zeros(1,nb_samples);\n% DJs = zeros(nb_samples,size(training_data,2));\n% DKs = zeros(nb_samples,size(training_data,2));\n% for i=1:nb_samples\n% % select one training sample randomly\n% xi = training_data(i,:);\n% c_xi = trainLab(i);\n% \n% dist = ((xi(ones(size(w,1),1),:))-w)*omegaT*(omegaT'*((xi(ones(size(w,1),1),:))-w)');\n% dist = diag(dist);\n% % determine the two winning prototypes\n% % nearest prototype with the same class\n% [sortDist,sortIdx] = sort(dist);\n% count = 1;\n% J = sortIdx(count);\n% while prototypeLabel(sortIdx(count)) ~= c_xi, \n% count = count+1;\n% J = sortIdx(count);\n% end\n% dJ = sortDist(count);\n% dJs(i) = dJ;\n% Js(i) = J;\n% count = 1;\n% K = sortIdx(count);\n% while prototypeLabel(sortIdx(count)) == c_xi, \n% count = count+1;\n% K = sortIdx(count);\n% end\n% dK = sortDist(count);\n% dKs(i) = dK;\n% Ks(i) = K;\n% \n% wJ = w(J,:);\n% wK = w(K,:);\n% % prototype update\n% norm_factors(i) = 4/((dJ + dK)^2);\n% DJ = (xi-wJ);\n% DK = (xi-wK);\n% DJs(i,:) = DJ;\n% DKs(i,:) = DK;\n% end\n% end\n\n\n\n\n\nfunction D = squaredEuclidean(A, B)\n% computes the sqared Euclidean distance\n%\n% D = squaredEuclidean(X) returns the squared Euclidean distance matrix of data in rows of X \n% D = squaredEuclidean(X, Y) returns the distance matrix with all distances between the points in X and Y.\n%\nif nargin == 1 % means that one matrix\n D = bsxfun(@plus, sumsquared(A,2), bsxfun(@minus, sumsquared(A,2).', 2*A*A.')); % 2*(Y*Y.')\nelse \n D = bsxfun(@plus, sumsquared(A,2), bsxfun(@minus, sumsquared(B,2).', 2*A*B.'));\nend\nD = max(D,0);\n\n\n\n\nfunction sq = sumsquared(x,dim) \n% sq = sumsquared(x,dim) \n% sum of all squared element of matrix x along dimension dim\n\npersistent isoctave\n\nif isempty(isoctave)\n isoctave = exist('OCTAVE_VERSION','builtin');\nend\n\nif nargin == 1\n dim = 1;\nend\n\nif isoctave\n sq = sumsq(x,dim);\nelse\n sq = sum(x.^2, dim);\nend\n", "meta": {"author": "ilarinieminen", "repo": "SOM-Toolbox", "sha": "f2597abc1ae33c2060e0443d49e854011ff21831", "save_path": "github-repos/MATLAB/ilarinieminen-SOM-Toolbox", "path": "github-repos/MATLAB/ilarinieminen-SOM-Toolbox/SOM-Toolbox-f2597abc1ae33c2060e0443d49e854011ff21831/contrib/gmlvq/gmlvq_core.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619959279793, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.548552896272818}} {"text": "function in = iresponse_proxy(in)\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% 'iresponse_proxy' computes the impulse response functions to shock\n% identified via instrumental variables \n% Codes are written based on the Mertens Ravn (2013, AER) source codes,\n% modified to \n%1) handle different length of VAR and factors\n%2) Multiple instruments to explain the same shock\n\n% Filippo Ferroni, 6/1/2015\n% Revised, 2/15/2017\n% Revised, 3/21/2018\n% Revised, 9/11/2019\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nY = in.vars(in.p+1:end,:);\n[T,n] = size(Y);\n[T_m,n_m] = size(in.proxies);\n\n% number of proxies\nk = 1;\n%Assuming proxies start at least p periods later\ninstrument = in.proxies(1:end,:);\n \n% Identification\n%%%%%%%%%%%%%%%%%\n\n% covariance of the reduced form shocks\nin.Sigma_m = in.Sigma;\n\n% Instrument on VAR residuals\nPhib = [ones(T_m,1) instrument]\\in.res(T-T_m-in.T_m_end+1:T-in.T_m_end,:);\n\n% Fitted values of the identified shocks\n% here is where thes prior on beta should enter , instead of Phib(:,1)\n% m = beta e1 + v\nuhat1 = [ones(T_m,1) instrument]*Phib(:,1); \n\n% regress the fitted values on the other reduced form shocks\nb21ib11_TSLS = [ones(T_m,1) uhat1]\\in.res(T-T_m-in.T_m_end+1:T-in.T_m_end,2:end); \nb21ib11_TSLS = b21ib11_TSLS(2:end,:)';\nb21ib11 = b21ib11_TSLS;\n\n% Identification of b11 and b12 from the covariance matrix of the VAR\nSig11 = in.Sigma_m(1:k,1:k);\nSig21 = in.Sigma_m(k+1:n,1:k);\nSig22 = in.Sigma_m(k+1:n,k+1:n);\nZZp = b21ib11*Sig11*b21ib11'-(Sig21*b21ib11'+b21ib11*Sig21')+Sig22;\nb12b12p = (Sig21- b21ib11*Sig11)'*(ZZp\\(Sig21- b21ib11*Sig11));\nb11b11p = Sig11-b12b12p;\nb11 = sqrt(b11b11p);\nin.b1 = [b11; b21ib11*b11];\nin.Phib = Phib;\n\n% Impulse Responses\n%%%%%%%%%%%%%%%%%%%%\n% initial shock: eps(1,1)=1\nirs(in.p+1,:) = in.b1(:,1);\n\nfor jj = 2:in.irhor%+max(max(VAR.term_spreads_matur),max(VAR.real_rates_init+VAR.real_rates_matur-1))\n lvars = (irs(in.p+jj-1:-1:jj,:))';\n irs(in.p+jj,:) = lvars(:)'*in.Phi(1:in.p * n,:); \nend\n\nin.irs = irs(in.p+1:in.p+in.irhor,:);\nin.uhat1 = uhat1;\n\n\nif in.compute_F_stat == 1\n % F-test\n %%%%%%%%%%%%%%%%%%%%%%%%%\n XX_m = [ones(T_m,1) instrument];\n Res_m = in.res( T-T_m-in.T_m_end+1 : T-in.T_m_end , :)- XX_m * Phib;\n Res_const = in.res( T-T_m-in.T_m_end+1 : T-in.T_m_end,1) - ...\n ones(T_m,1)*(ones(T_m,1)\\in.res(T-T_m-in.T_m_end+1 : T-in.T_m_end,1));\n \n SST_m = Res_const'*Res_const;\n SSE_m = Res_m(:,1)'*Res_m(:,1);\n in.F_m = ((SST_m-SSE_m)/n_m)/ ...\n (SSE_m/(length(in.res(T-T_m-in.T_m_end+1 : T-in.T_m_end,1))-(n_m+1)));\n in.R2_m = (1-SSE_m/(SST_m));\n in.R2adj_m = in.R2_m-...\n (n_m / ((length(in.res(T-T_m-in.T_m_end+1 : T-in.T_m_end,1)) -(n_m+1))))*(1-in.R2_m);\n \n % Calculate robust standard errors\n SS_m = zeros(n_m+1,n_m+1);\n for ii = 1 : T_m\n SS_m = SS_m+1/T_m * XX_m(ii,:)'*XX_m(ii,:)*Res_m(ii,1)^2;\n end\n Avarb_m = inv(1/T_m * XX_m'*XX_m)*SS_m *inv(1/T_m * XX_m'*XX_m);\n RR_m = [zeros(n_m,1) eye(n_m)];\n WW_m = T_m*(RR_m*Phib(:,1))' * inv(RR_m*Avarb_m*RR_m') * (RR_m*Phib(:,1));\n in.F_m_rob = WW_m/n_m;\nend", "meta": {"author": "naffe15", "repo": "BVAR_", "sha": "4c935f440a2e98475ead4f873ebdfd03378a0eee", "save_path": "github-repos/MATLAB/naffe15-BVAR_", "path": "github-repos/MATLAB/naffe15-BVAR_/BVAR_-4c935f440a2e98475ead4f873ebdfd03378a0eee/bvartools/iresponse_proxy.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869819218865, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.5483514034831002}} {"text": "function [resCe, rhsCe] = electrolyteDiffusion(ce,dCe,jflux,T,param)\n% electrolyteDiffusion evaluates the residual for the electrolyte\n% concentration of Li-ions in the electrolyte solution.\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\n% Comment this for benchmark purposes\nDeff_p = param.ElectrolyteDiffusionFunction(ce(1:param.Np),T(param.Nal+1:param.Nal+param.Np),param,'p');\nDeff_s = param.ElectrolyteDiffusionFunction(ce(param.Np+1:param.Np+param.Ns),T(param.Nal+param.Np+1:param.Nal+param.Np+param.Ns),param,'s');\nDeff_n = param.ElectrolyteDiffusionFunction(ce(param.Np+param.Ns+1:end),T(param.Nal+param.Np+param.Ns+1:end-param.Ncu),param,'n');\n\n% Uncomment this for benchmark purposes\n% Deff_p = repmat(param.Dp*param.eps_p^param.brugg_p,param.Np,1);\n% Deff_s = repmat(param.Ds*param.eps_s^param.brugg_s,param.Ns,1);\n% Deff_n = repmat(param.Dn*param.eps_n^param.brugg_n,param.Nn,1);\n\n% Interpolation of the diffusion coefficients\n[Deff_p, Deff_s, Deff_n] = interpolateDiffusionCoefficients(Deff_p,Deff_s,Deff_n,param);\n\n%% Positive A Matrix\nA_p = - diag(Deff_p);\n\nA_p(2:end,2:end) = A_p(2:end,2:end) - diag(Deff_p(1:end-1));\nA_p(1:end-1,2:end) = A_p(1:end-1,2:end) + diag(Deff_p(1:end-1));\nA_p(2:end,1:end-1) = A_p(2:end,1:end-1) + diag(Deff_p(1:end-1));\n%% Separator A Matrix\nA_s = - diag(Deff_s);\n\nA_s(2:end,2:end) = A_s(2:end,2:end) - diag(Deff_s(1:end-1));\nA_s(1:end-1,2:end) = A_s(1:end-1,2:end) + diag(Deff_s(1:end-1));\nA_s(2:end,1:end-1) = A_s(2:end,1:end-1) + diag(Deff_s(1:end-1));\n%% Negative A Matrix\nA_n = - diag(Deff_n);\n\nA_n(2:end,2:end) = A_n(2:end,2:end) - diag(Deff_n(1:end-1));\nA_n(1:end-1,2:end) = A_n(1:end-1,2:end) + diag(Deff_n(1:end-1));\nA_n(2:end,1:end-1) = A_n(2:end,1:end-1) + diag(Deff_n(1:end-1));\n% Fix the last elements of the A_n\nA_n(end,end-1:end) = [Deff_n(end-1) -Deff_n(end-1)];\n%% A_tot matrix\nA_tot = blockDiagonalMatrix(param,A_p,A_s,A_n);\n\n% Divide by the deltax and the length of the positive electrode\nA_tot(1:param.Np,1:param.Np) = A_tot(1:param.Np,1:param.Np)/(param.deltax_p^2*param.len_p^2);\n% Reset values on the lines for the interfaces conditions\nA_tot(param.Np,:) = 0;\nA_tot(param.Np+1,:) = 0;\n\n% Divide by the deltax and the length of the separator\nA_tot(param.Np+1:param.Np+param.Ns,param.Np+1:param.Np+param.Ns) = A_tot(param.Np+1:param.Np+param.Ns,param.Np+1:param.Np+param.Ns)/(param.deltax_s^2 * param.len_s^2);\n% Reset values on the lines for the interfaces conditions\nA_tot(param.Np+param.Ns,:) = 0;\nA_tot(param.Np+param.Ns+1,:) = 0;\n\n% Divide by the deltax and the length of the negative electrode\nA_tot(param.Np+param.Ns+1:end,param.Np+param.Ns+1:end) = A_tot(param.Np+param.Ns+1:end,param.Np+param.Ns+1:end)/(param.deltax_n^2 * param.len_n^2);\n\n%% Interface between separator and positive electrode (last volume in the positive electrode)\n\n% Compute the common denominator at the interface\nden_s = (param.deltax_p*param.len_p/2 + param.deltax_s*param.len_s/2);\n% Last diffusion coefficient of the positive electrode\nlast_p = Deff_p(end-1)/(param.deltax_p*param.len_p);\n% Diffusion coefficient on the interface\nfirst_s = Deff_p(end)/den_s;\n% Fix the values at the boundaries\nA_tot(param.Np,param.Np-1:param.Np+1) = [last_p -(last_p+ first_s) first_s]/(param.deltax_p*param.len_p*param.eps_p);\n\n%% Interface between separator and positive electrode (first volume in the separator)\n\n% Compute the common denominator at the interface\nden_s = (param.deltax_p*param.len_p/2 + param.deltax_s*param.len_s/2);\n% First diffusion coefficient in the separator\nsecond_s = Deff_s(1)/(param.deltax_s*param.len_s);\n% Diffusion coefficient on the interface\nfirst_s = Deff_p(end)/den_s;\n\nA_tot(param.Np+1,param.Np:param.Np+2) = [first_s -(first_s+second_s) second_s]/(param.deltax_s*param.len_s*param.eps_s);\n\n%% Interface between separator and negative electrode (last volume in the separator)\n\n% Compute the common denominator at the interface\nden_s = (param.deltax_s*param.len_s/2 + param.deltax_n*param.len_n/2);\n% Last diffusion coefficient in the separator\nlast_s = Deff_s(end-1)/(param.deltax_s*param.len_s);\n% Diffusion coefficient on the interface\nfirst_n = Deff_s(end)/den_s;\n\nA_tot(param.Np+param.Ns,param.Np+param.Ns-1:param.Np+param.Ns+1) = [last_s -(last_s+first_n) first_n]/(param.deltax_s*param.len_s*param.eps_s);\n\n%% Interface between separator and negative electrode (first volume in the negative electrode)\n\n% Compute the common denominator at the interface\nden_n = (param.deltax_s*param.len_s/2 + param.deltax_n*param.len_n/2);\n% First diffusion coefficient in the negative electrode\nsecond_n = Deff_n(1)/(param.deltax_n*param.len_n);\n% Diffusion coefficient on the interface\nfirst_n = Deff_s(end)/den_n;\n\nA_tot(param.Np+param.Ns+1,param.Np+param.Ns:param.Np+param.Ns+2) = [first_n -(first_n+second_n) second_n]/(param.deltax_n*param.len_n*param.eps_n);\n\n%% Useful stuff\na_tot = [\n repmat(param.a_i(1),param.Np,1);...\n zeros(param.Ns,1);...\n repmat(param.a_i(3),param.Nn,1)...\n ];\n\njflux_tot = [\n jflux(1:param.Np);...\n zeros(param.Ns,1);...\n jflux(param.Np+1:end)...\n ];\n\neps_tot = [\n repmat(param.eps_p,param.Np,1);...\n repmat(param.eps_s,param.Ns,1);...\n repmat(param.eps_n,param.Nn,1)\n ];\n\nK = 1./eps_tot;\nA_eps = diag(K);\n\n% Build porosities matrix\nif(~isa(eps_tot,'casadi.MX') && ~isa(eps_tot,'casadi.SX'))\n A_eps = A_eps + diag(K(1:end-1),1);\n A_eps = A_eps + diag(K(1:end-1),-1);\n A_eps = sparse(A_eps);\nelse\n A_u_l = diag(K(1:end-1));\n A_eps(1:end-1,2:end) = A_eps(1:end-1,2:end)+A_u_l;\n A_eps(2:end,1:end-1) = A_eps(2:end,1:end-1)+A_u_l;\nend\n\nA_eps(param.Np,param.Np-1:param.Np+1) = 1;\nA_eps(param.Np+1,param.Np:param.Np+2) = 1;\n\nA_eps(param.Np+param.Ns,param.Np+param.Ns-1:param.Np+param.Ns+1) = 1;\nA_eps(param.Np+param.Ns+1,param.Np+param.Ns:param.Np+param.Ns+2) = 1;\n\nG = A_eps.*A_tot;\n\n% Write the RHS of the equation\nrhsCe = (G*ce + K.*(1-param.tplus).*a_tot.*jflux_tot);\n\n% Write the residual of the equation\nresCe = dCe - rhsCe;\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/electrolyteDiffusion.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256551882382, "lm_q2_score": 0.6513548714339145, "lm_q1q2_score": 0.5483272414049056}} {"text": "function [A,B] = hmxQRSVD(A,B,tol)\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 : hmxQRSVD.m |\n%| # | VERSION : 0.52 |\n%| _#_ | AUTHOR(S) : Matthieu Aussal |\n%| ( # ) | CREATION : 14.03.2017 |\n%| / 0 \\ | LAST MODIF : 01.01.2019 |\n%| ( === ) | SYNOPSIS : QR factorization and SVD recompression for |\n%| `---' | low-rank matrices |\n%+========================================================================+\n\nif ~isempty(A)\n % QR Factorisation A = QA * RA;\n [QA,RA] = qr(A,0);\n \n % QR Factorisation Bt = QB * RB\n [QB,RB] = qr(B.',0);\n \n % Singular value decomposition U*S*V = RA * RB.'\n try\n [U,S,V] = svd(RA * RB.','econ');\n catch\n return\n end\n\n % Compression rank\n s = diag(S);\n n = sum( s./s(1) >= tol );\n\n % Recompression A = QA * U * S\n A = QA * (U(:,1:n) * S(1:n,1:n));\n \n % Recompression B = V' * QB^t\n B = V(:,1:n)' * QB.';\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/hmxQRSVD.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972818382005, "lm_q2_score": 0.6297745935070806, "lm_q1q2_score": 0.5482800492780221}} {"text": "%============================================================================\n% Copyright (C) 2014, Heikki Hyyti\n%\n% Permission is hereby granted, free of charge, to any person obtaining a\n% copy of this software and associated documentation files (the \"Software\"),\n% to deal in the Software without restriction, including without limitation\n% the rights to use, copy, modify, merge, publish, distribute, sublicense,\n% and/or sell copies of the Software, and to permit persons to whom the\n% Software is furnished to do so, subject to the following conditions:\n%\n% The above copyright notice and this permission notice shall be included in\n% all copies or substantial portions of the Software.\n%\n% THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n% THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n% FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n% DEALINGS IN THE SOFTWARE.\n%============================================================================\n\n%source: http://ieeexplore.ieee.org/stamp/stamp.jsp?arnumber=05291740\n% A Triaxial Accelerometer Calibration Method Using a Mathematical Model\n% by S.P. Won, F. Golnaraghi\n\nfunction [B, G] = IMUcalibIteration(S_x, S_y, S_z, B, G)\n % gravitation at Helsinki\n g0 = 9.8189; \n\n % current estimate of accelerations \n A_x = (S_x - B(1)) / G(1);\n A_y = (S_y - B(2)) / G(2);\n A_z = (S_z - B(3)) / G(3);\n \n % squares\n A_x2 = (A_x.*A_x);\n A_y2 = (A_y.*A_y);\n A_z2 = (A_z.*A_z);\n \n % error estimate\n E = A_x2 + A_y2 + A_z2 - (g0*g0);\n \n ACCEL = [A_x2 A_y2 A_z2 A_x A_y A_z];\n \n CAL = ACCEL \\ E;\n \n % gain change\n G_change2 = 1 ./ (1 - CAL(1:3));\n G_change = sqrt(abs(G_change2));\n\n % bias change\n B_change = CAL(4:6) .* G .* G_change2 .* 0.5;\n \n % update estimates\n G = G .* G_change;\n B = B + B_change;\nend", "meta": {"author": "hhyyti", "repo": "dcm-imu", "sha": "762992befcc87be972f9d07c01d039889b545f23", "save_path": "github-repos/MATLAB/hhyyti-dcm-imu", "path": "github-repos/MATLAB/hhyyti-dcm-imu/dcm-imu-762992befcc87be972f9d07c01d039889b545f23/IMUcalibIteration.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797071719777, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5482603561872443}} {"text": "function UNew = fluidNeumann3D(varargin);\n% fluidNeumann3D: solve fluid registraion in 3D 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[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 sine transform of new force field\nFS = discreteCosineTransform(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 DST\nV = discreteCosineTransform(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 = discreteCosineTransform(F,M,N,P);\n% compute discrete cosine transform of 3-D vector field\n\n% initialize resulting array\nFS = F;\n\n% first perform cosine transform down columns\nlen = 2*M-2; ind = 1:M;\nfor p=1:P\n for n=1:N\n s = fft(FS(:,n,p,:),len,1);\n FS(:,n,p,:) = real(s(ind,:,:,:));\n end\nend\nFS = sqrt(2/(M-1))*FS;\n\n% next perform cosine transform across rows\nlen = 2*N-2; ind = 1:N;\nfor p=1:P\n for m=1:M\n s = fft(FS(m,:,p,:),len,2);\n FS(m,:,p,:) = real(s(:,ind,:,:));\n end\nend\nFS = sqrt(2/(N-1))*FS;\n\n% finally perform cosine transform across pages\nlen = 2*P-2; ind = 1:P;\nfor n=1:N\n for m=1:M\n s = fft(FS(m,n,:,:),len,3);\n FS(m,n,:,:) = real(s(:,:,ind,:));\n end\nend\nFS = sqrt(2/(P-1))*FS;\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/fluidNeumann3D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970748488297, "lm_q2_score": 0.6224593241981982, "lm_q1q2_score": 0.5482603519661523}} {"text": "function p = cs_nd (A)\n%CS_ND generalized nested dissection ordering.\n% p = cs_nd(A) computes the nested dissection ordering of a matrix. Small\n% submatrices (order 500 or less) are ordered via cs_amd. A must be sparse\n% and symmetric (use p = cs_nd(A|A') if it is not symmetric).\n%\n% Example:\n% A = delsq (numgrid ('L', 300)) ; % matrix used in 'bench'\n% p = cs_nd (A) ;\n% cspy (A (p,p)) ;\n%\n% See also CS_AMD, CS_SEP, CS_ESEP, CS_NSEP, AMD.\n\n% Copyright 2006-2007, Timothy A. Davis.\n% http://www.cise.ufl.edu/research/sparse\n\nn = size (A,1) ;\nif (n == 1)\n p = 1 ;\nelseif (n < 500)\n p = cs_amd (A) ; % use cs_amd on small graphs\nelse\n [s a b] = cs_nsep (A) ; % find a node separator\n a = a (cs_nd (A (a,a))) ; % order A(a,a) recursively\n b = b (cs_nd (A (b,b))) ; % order A(b,b) recursively\n p = [a b s] ; % concatenate to obtain the final ordering\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/SuiteSparse/CXSparse/MATLAB/CSparse/cs_nd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8031737869342623, "lm_q2_score": 0.6825737214979745, "lm_q1q2_score": 0.5482253207573407}} {"text": "function [y,dzdx2] = vl_nnscosinesim(x1, x2, varargin)\n% VL_NNCOSINESIM Compute the cosine similariy between features\n% Y = VL_NNCOSINESIM(X1, X2) computes the cosine similarity between X1\n% and X2 where X1 has shape H x W x C x N, X2 has shape\n% H x W x C x N and Y is has shape 1 x 1 x 1 x N (producing a scalar\n% per batch element).\n%\n% [DZDX1, DZDX2] = VL_NNCOSINESIM(X1, X2, DZDY) computes the\n% derivatives of the block projected onto DZDY. DZDX1 and DZDX2\n% have the same dimensions as X1, X2 and B respectively.\n%\n% NOTES: The cosine similarity is defined between vectors A and B of\n% dimension N x 1 to be the scalar given by:\n% cos_sim = a'b / (norm(a,2) * norm(b,2))\n% To operate with tensors, the first three channels (H, W and C) are\n% treated as the vector elements, while the fourth dimension denotes\n% batch indicies.\n%\n% VL_NNCOSINELOSS(.., 'option', value, ...) accepts the following options:\n%\n% `eps`:: 1e-6\n% A small value to avoid possible division by zero.\n%\n% Copyright (C) 2018 Samuel Albanie.\n% Licensed under The MIT License [see LICENSE.md for details]\n\n opts.eps = 1e-6 ;\n [~, dzdy] = vl_argparsepos(struct(), varargin) ;\n\n sz1 = size(x1) ; sz2 = size(x2) ;\n assert(all(sz1 == sz2), 'tensor sizes do not match') ;\n x1 = reshape(x1, [], sz1(4)) ;\n x2 = reshape(x2, [], sz1(4)) ;\n dots = dot(x1, x2, 1) ;\n x1_norms = sqrt(sum(x1 .* x1, 1)) ;\n x2_norms = sqrt(sum(x2 .* x2, 1)) ;\n\n if isempty(dzdy)\n y = dots ./ max(x1_norms .* x2_norms, opts.eps) ;\n y = reshape(y, 1, 1, 1, sz1(4)) ;\n else\n dzdy = dzdy{1} ; dsize = size(dzdy) ;\n assert(numel(dsize) == 4 & all(dsize(1:3) == ones(1,3)) ...\n & dsize(4) == sz1(4), 'DZDY has an unexpected size') ;\n t1 = bsxfun(@rdivide, x2, max(x1_norms .* x2_norms, opts.eps)) ;\n t2 = bsxfun(@rdivide, bsxfun(@times, x1, dots), ...\n max(x1_norms .^3 .* x2_norms, opts.eps)) ;\n dzdx1 = t1 - t2 ;\n\n t1 = bsxfun(@rdivide, x1, max(x2_norms .* x1_norms, opts.eps)) ;\n t2 = bsxfun(@rdivide, bsxfun(@times, x2, dots), ...\n max(x2_norms .^3 .* x1_norms, opts.eps)) ;\n dzdx2 = t1 - t2 ;\n\n % reshape to match input and compute projected derivatives\n dzdx1 = reshape(dzdx1, sz1) ;\n dzdx2 = reshape(dzdx2, sz2) ;\n dzdx1 = bsxfun(@times, dzdx1, dzdy) ;\n dzdx2 = bsxfun(@times, dzdx2, dzdy) ;\n y = dzdx1 ;\n end\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_nncosinesim.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324983301568, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.5481066508284888}} {"text": "function k = lfmvKernDiagCompute(lfmKern, t)\n\n% LFMVKERNDIAGCOMPUTE Compute diagonal of LFMV kernel.\n% FORMAT\n% DESC computes the diagonal of the kernel matrix for velocity- velocity in\n% the switching dynamical latent force kernel.\n% ARG kern : the kernel structure for which the matrix is computed.\n% ARG t : input data matrix in the form of a design matrix.\n% RETURN k : a vector containing the diagonal of the kernel matrix\n% computed at the given points.\n%\n% COPYRIGHT : Mauricio A. Alvarez, 2010\n\n% KERN\n\n% Get length scale out.\nsigma2 = 2/lfmKern.inverseWidth;\nsigma = sqrt(sigma2);\n\n% Parameters of the kernel\nalpha(1) = lfmKern.damper./(2*lfmKern.mass);\nomega(1) = sqrt(lfmKern.spring./lfmKern.mass - alpha(1)*alpha(1));\n\n% Precomputations to increase the speed\npreExp1 = zeros(length(t),2);\ngamma1_p = alpha(1) + j*omega(1);\ngamma1_m = alpha(1) - j*omega(1);\npreGamma(1) = gamma1_p + gamma1_p;\npreGamma(2) = gamma1_p + gamma1_m;\npreGamma(3) = gamma1_m + gamma1_p;\npreGamma(4) = gamma1_m + gamma1_m;\npreConst = 1./preGamma;\npreFactors(1) = preConst(2) - preConst(1);\npreFactors(2) = preConst(3) - preConst(4);\npreFactors(3) = preConst(3) - preConst(1);\npreFactors(4) = preConst(2) - preConst(4);\npreExp1(:,1) = gamma1_p.*exp(-gamma1_p*t);\npreExp1(:,2) = gamma1_m.*exp(-gamma1_m*t);\n% Actual computation of the kernel\nsk =lfmDiagComputeH3VV(gamma1_p, gamma1_m, sigma2, t, preFactors([1 2]), 1) + ...\n lfmDiagComputeH3VV(gamma1_p, gamma1_m, sigma2, t, preFactors([3 4]), 0) + ...\n lfmDiagComputeH4VV(gamma1_p, gamma1_m, sigma2, t, preGamma([1 2 4 3]), preExp1 ) + ...\n lfmDiagComputeH4VV(gamma1_p, gamma1_m, sigma2, t, preGamma([1 3 4 2]), preExp1 );\n\nif lfmKern.isNormalised\n k0 = lfmKern.sensitivity^2/(8*sqrt(2)*lfmKern.mass^2*omega^2);\nelse\n k0 = sqrt(pi)*sigma*lfmKern.sensitivity^2/(8*lfmKern.mass^2*omega^2);\nend\nk = k0*sk;\n\n\nfunction h = lfmDiagComputeH3VV(gamma1_p, gamma1_m, sigma2, t, preFactor, mode)\n\nh = preFactor(1)*lfmvvComputeUpsilonDiagVector(gamma1_p, sigma2, t, mode) ...\n + preFactor(2)*lfmvvComputeUpsilonDiagVector(gamma1_m,sigma2, t, mode);\n\nfunction h = lfmDiagComputeH4VV(gamma1_p, gamma1_m, sigma2, t, ...\n preFactor, preExp)\n\nh = lfmvpComputeUpsilonVector(gamma1_p,sigma2, t, 0).*( preExp(:,2)/preFactor(2) - preExp(:,1)/preFactor(1)) ...\n + lfmvpComputeUpsilonVector(gamma1_m,sigma2, t, 0).*( preExp(:,1)/preFactor(4) - preExp(:,2)/preFactor(3));\n\n\n\n\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/kern/lfmvKernDiagCompute.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324803738429, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.5481066441083025}} {"text": "function [transformationMatrix] = ...\n phase_difference_linear_registration3d(moving, movingCertainty, ...\n fixed, fixedCertainty, varargin)\n% PHASE_DIFFERENCE_LINEAR_REGISTRATION3D Estimates a transformation matrix using phase-difference\n%\n% [transformationMatrix] = ...\n% phase_difference_linear_registration3d(moving, movingCertainty, ...\n% fixed, fixedCertainty)\n%\n% INPUT ARGUMENTS\n% moving - Moving image\n% movingCertainty - Certainty mask of moving image\n% fixed - Fixed image\n% fixedCertainty - Certainty mask of fixed image\n%\n% OPTIONAL INPUT ARGUMENTS\n% 'transformationModel' - Transformation model for estimating the\n% displacement field\n% 'translation', 'affine' (default)\n%\n% OUTPUT ARGUMENTS\n% transformationMatrix - Estimated transformation matrix\n\n% Copyright (c) 2012 Daniel Forsberg\n% danne.forsberg@outlook.com\n%\n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n\n%% Setup default parameters\n% translation, affine, non-rigid\ntransformationModel = 'affine';\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(4);\n\n% Load quadrature filters\nload quadratureFiltersLinearRegistration3D\n\n% Perform quadrature filtering\nq21 = imfilter(moving,f1,'same','conv');\nq22 = imfilter(moving,f2,'same','conv');\nq23 = imfilter(moving,f3,'same','conv');\n\nq11 = imfilter(fixed,f1,'same','conv');\nq12 = imfilter(fixed,f2,'same','conv');\nq13 = imfilter(fixed,f3,'same','conv');\n\nfilterSize = (size(real(f1),1)-1)/2;\nq11 = q11(filterSize+1:end-filterSize,filterSize+1:end-filterSize,filterSize+1:end-filterSize);\nq12 = q12(filterSize+1:end-filterSize,filterSize+1:end-filterSize,filterSize+1:end-filterSize);\nq13 = q13(filterSize+1:end-filterSize,filterSize+1:end-filterSize,filterSize+1:end-filterSize);\nq21 = q21(filterSize+1:end-filterSize,filterSize+1:end-filterSize,filterSize+1:end-filterSize);\nq22 = q22(filterSize+1:end-filterSize,filterSize+1:end-filterSize,filterSize+1:end-filterSize);\nq23 = q23(filterSize+1:end-filterSize,filterSize+1:end-filterSize,filterSize+1:end-filterSize);\n\n% Compute phase-difference, certainties and phase-gradients\ndphi(:,:,:,1) = angle(q11.*conj(q21));\ndphi(:,:,:,2) = angle(q12.*conj(q22));\ndphi(:,:,:,3) = angle(q13.*conj(q23));\n\n% Estimate certainties\ncertainty(:,:,:,1) = abs(q11.*q21).*((cos(dphi(:,:,:,1)/2)).^2);\ncertainty(:,:,:,2) = abs(q12.*q22).*((cos(dphi(:,:,:,2)/2)).^2);\ncertainty(:,:,:,3) = abs(q13.*q23).*((cos(dphi(:,:,:,3)/2)).^2);\n\n% Add certainty masks\nif ~isempty(fixedCertainty)\n fixedCertainty = fixedCertainty(...\n filterSize+1:end-filterSize,filterSize+1:end-filterSize,filterSize+1:end-filterSize);\n certainty = bsxfun(@times,certainty,fixedCertainty);\nend\nif ~isempty(movingCertainty)\n movingCertainty = movingCertainty(...\n filterSize+1:end-filterSize,filterSize+1:end-filterSize,filterSize+1:end-filterSize);\n certainty = bsxfun(@times,certainty,movingCertainty);\nend\n\n% Estimate gradients of phi\ngrad_x_dphi_n1 = zeros(size(q11));\ngrad_x_dphi_n1(:,2:end-1,:) = ...\n angle(q11(:,3:end,:).*conj(q11(:,2:end-1,:)) + ...\n q11(:,2:end-1,:).*conj(q11(:,1:end-2,:)) + ...\n q21(:,3:end,:).*conj(q21(:,2:end-1,:)) + ...\n q21(:,2:end-1,:).*conj(q21(:,1:end-2,:)));\n\ngrad_y_dphi_n2 = zeros(size(q11));\ngrad_y_dphi_n2(2:end-1,:,:) = ...\n angle(q12(3:end,:,:).*conj(q12(2:end-1,:,:)) + ...\n q12(2:end-1,:,:).*conj(q12(1:end-2,:,:)) + ...\n q22(3:end,:,:).*conj(q22(2:end-1,:,:)) + ...\n q22(2:end-1,:,:).*conj(q22(1:end-2,:,:)));\n\ngrad_z_dphi_n3 = zeros(size(q11));\ngrad_z_dphi_n3(:,:,2:end-1) = ...\n angle(q13(:,:,3:end).*conj(q13(:,:,2:end-1)) + ...\n q13(:,:,2:end-1).*conj(q13(:,:,1:end-2)) + ...\n q23(:,:,3:end).*conj(q23(:,:,2:end-1)) + ...\n q23(:,:,2:end-1).*conj(q23(:,:,1:end-2)));\n\n% Save all the phase gradients nicely...\nphaseGradient(:,:,:,1) = grad_x_dphi_n1;\nphaseGradient(:,:,:,2) = grad_y_dphi_n2;\nphaseGradient(:,:,:,3) = grad_z_dphi_n3;\n\n% Build A and h for A p = h\n[A, h] = build_A_h_3d(dphi, certainty, phaseGradient, transformationModel);\n\n% Solve the equation system\nswitch transformationModel\n case 'translation'\n d = A \\ h;\n transformationMatrix(1:3,4) = d;\n case {'rigid','affine'}\n p = A \\ h;\n transformationMatrix(1:3,1:4) = [1+p(1) p(2) p(3) p(10);...\n p(4) 1+p(5) p(6) p(11);...\n p(7) p(8) 1+p(9) p(12)];\nend", "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/phase_difference_linear_registration3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324803738429, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.5481066387558897}} {"text": "function [w,u] = biharmonicP2(node,elem,pde,bdFlag,option)\n% [w,u] = biharmonicP1(node,elem,pde,bdFlag) produces the mixed cubic finite element\n% approximation of the biharmonic equation, where w = laplace u\n% See also biharmonicP1, biharmonicP2, biharmonicP3.\n% Created by Jie Zhou.\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details.\n\nif nargin<5, option = []; end\ntic;\n%% Construct Data Structure\n[elem2dof,edge,bdDof] = dofP2(elem);\nN = size(node,1); NT = size(elem,1); Ndof = N+size(edge,1);\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 quadratic, numerical quadrature rule is used here\nif ~isfield(option,'quadorder')\n option.quadorder = 4; % default order\nend\n[lambda, weight] = quadpts(option.quadorder);\nnQuad = size(lambda,1);\nii = zeros(21*NT,1); jj = zeros(21*NT,1); sA = zeros(21*NT,1);sB = zeros(21*NT,1);\nindex = 0;\nfor i = 1:6\n for j = i:6\n Bij = 0;\n Aij = 0; \n for p = 1:nQuad\n Bij = Bij + weight(p)*dot(Dphi(p,i),Dphi(p,j),2);\n Aij = Aij + weight(p)*dot(phi(p,i),phi(p,j),2);\n end\n Bij = Bij.*area;\n Aij = Aij.*area;\n\n ii(index+1:index+NT) = double(elem2dof(:,i)); \n jj(index+1:index+NT) = double(elem2dof(:,j));\n sB(index+1:index+NT) = Bij;\n sA(index+1:index+NT) = Aij; \n index = index + NT;\n end\nend\nclear Aij Bij\ndiagIdx = (ii == jj); upperIdx = ~diagIdx;\nB = sparse(ii(diagIdx),jj(diagIdx),sB(diagIdx),Ndof,Ndof);\nA = sparse(ii(diagIdx),jj(diagIdx),sA(diagIdx),Ndof,Ndof);\n% A = spdiags(accumarray(ii(diagIdx),sA(diagIdx),[Ndof 1]),0,Ndof,Ndof);\nBU = sparse(ii(upperIdx),jj(upperIdx),sB(upperIdx),Ndof,Ndof);\nAU = sparse(ii(upperIdx),jj(upperIdx),sA(upperIdx),Ndof,Ndof);\nB = B + BU + BU';\nA = A + AU + AU';\n\n%% boundary condition\n%%\n fixedDof = [];\n isFixedDof = false(Ndof,1); \n if ~isempty(bdFlag) \n elem2edge = elem2dof(:,4:6)-N;\n isDirichlet(elem2edge(bdFlag(:)==1)) = true;\n isFixedDof(edge(isDirichlet,:)) = true;\n isFixedDof(N + find(isDirichlet')) = true;\n fixedDof = find(isFixedDof);\n freeDof = find(~isFixedDof); \n end\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% subfunction Dphi\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n function s = Dphi(p,i) % gradient of basis phi\n switch i\n case 1\n s = (4*lambda(p,1)-1).*Dlambda(:,:,1); \n case 2\n s = (4*lambda(p,2)-1).*Dlambda(:,:,2); \n case 3\n s = (4*lambda(p,3)-1).*Dlambda(:,:,3); \n case 4\n s = 4*(lambda(p,2)*Dlambda(:,:,3)+lambda(p,3)*Dlambda(:,:,2));\n case 5\n s = 4*(lambda(p,3)*Dlambda(:,:,1)+lambda(p,1)*Dlambda(:,:,3));\n case 6\n s = 4*(lambda(p,1)*Dlambda(:,:,2)+lambda(p,2)*Dlambda(:,:,1));\n end\n end\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% subfunction Dphi\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n function s = phi(p,i) % gradient of basis phi\n switch i\n case 1\n s = (2*lambda(p,1)-1).*lambda(p,1); \n case 2\n s = (2*lambda(p,2)-1).*lambda(p,2); \n case 3\n s = (2*lambda(p,3)-1).*lambda(p,3); \n case 4\n s = 4*lambda(p,3).*lambda(p,2); \n case 5\n s = 4*lambda(p,1).*lambda(p,3); \n case 6\n s = 4*lambda(p,1).*lambda(p,2); \n end\n end\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%% Assemble right hand side by high order quadrature rule\n% To reduce the effect of the error introduced by the numerical quadrature,\n% the load term is computed using the 3rd order qudrature rule.\nb = zeros(Ndof,1);\nu=zeros(Ndof,1);\nw=zeros(Ndof,1);\n\nif ~isfield(option,'fquadorder')\n option.fquadorder = 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,w] = quadpts(option.fquadorder);\n nQuad = size(lambda,1);\n% phi(:,1) = lambda(:,1).*(2*lambda(:,1)-1);\n% phi(:,2) = lambda(:,2).*(2*lambda(:,2)-1);\n% phi(:,3) = lambda(:,3).*(2*lambda(:,3)-1);\n% phi(:,4) = 4*lambda(:,2).*lambda(:,3);\n% phi(:,5) = 4*lambda(:,3).*lambda(:,1);\n% phi(:,6) = 4*lambda(:,1).*lambda(:,2);\n bt = zeros(NT,6);\n for p = 1:nQuad\n % quadrature points in the x-y coordinate\n pxy = lambda(p,1)*node(elem(:,1),:) ...\n + lambda(p,2)*node(elem(:,2),:) ...\n + lambda(p,3)*node(elem(:,3),:);\n 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:6\n bt(:,j) = bt(:,j) + w(p)*phi(p,j)*fp;\n end\n end\n bt = bt.*repmat(area,1,6);\n b = accumarray(elem2dof(:),bt(:),[Ndof 1]); \nend\n\n\n\n\n function [b1,u] = getbdP2(b)\n %% Boundary conditions for Poisson equation: P2 quadratic FEM.\n %\n % The set up of boundary condition consists of two parts: \n %\n\n %\n % Modify the right hand side b. The Neumann boundary integral is added\n % to b. For Dirichlet boundary ndoes, b(fixedDof) is the evaluation of\n % pde.g_D.\n %\n\n\n u = zeros(Ndof,1);\n \n\n \n %% Part 1: Find boundary edges and modify the load b \n % Neumann boundary condition\n if ~isfield(option,'gNquadorder')\n option.gNquadorder = 6; \n end \n idxN = (bdFlag(:) == 1); % all Neumann edges in bdFlag \n Neumannidx = elem2edge(idxN ); % index of Neumann and Robin edges\n % since boundary integral is also needed for Robin edges\n Neumann = edge(Neumannidx,:);\n b1 = zeros(Ndof,1);\n [lambdagN,weightgN] = quadpts1(option.gNquadorder);\n nQuadgN = size(lambdagN,1);\n % quadratic bases (1---3---2)\n bdphi = zeros(nQuadgN,3); \n bdphi(:,1) = (2*lambdagN(:,1)-1).*lambdagN(:,1);\n bdphi(:,2) = (2*lambdagN(:,2)-1).*lambdagN(:,2);\n bdphi(:,3) = 4*lambdagN(:,1).*lambdagN(:,2);\n % length of edge\n el = sqrt(sum((node(Neumann(:,1),:) - node(Neumann(:,2),:)).^2,2));\n ge = zeros(size(Neumann,1),3);\n for pp = 1:nQuadgN\n ppxy = lambdagN(pp,1)*node(Neumann(:,1),:) ...\n + lambdagN(pp,2)*node(Neumann(:,2),:);\n gNu = pde.g_N(ppxy);\n ge(:,1) = ge(:,1) + weightgN(pp)*gNu*bdphi(pp,1);\n ge(:,2) = ge(:,2) + weightgN(pp)*gNu*bdphi(pp,2);\n ge(:,3) = ge(:,3) + weightgN(pp)*gNu*bdphi(pp,3); % interior bubble\n end\n % update RHS\n ge = ge.*repmat(el,1,3); \n b1(1:N) = accumarray(Neumann(:), [ge(:,1); ge(:,2)],[N,1]);\n b1(N+Neumannidx) = b1(N+Neumannidx) + ge(:,3);\n\n %% Part 2: Find Dirichlet boundary edges and compute the boundary value\n % Dirichlet boundary conditions\n \n isDirichlet(elem2edge(bdFlag(:)==1)) = true;\n % interpolation\n idx = (fixedDof > N); % index of edge nodes\n u(fixedDof(~idx)) = pde.g_D(node(fixedDof(~idx),:)); % bd value at vertex dofs\n bdEdgeIdx = fixedDof(idx) - N;\n bdEdgeMid = (node(edge(bdEdgeIdx,1),:) + node(edge(bdEdgeIdx,2),:))/2;\n u(fixedDof(idx)) = pde.g_D(bdEdgeMid);\n b1 = b1 - B*u;\n \n\n end % end of getbdP2\n\n\n\n\n\n[b1,u] = getbdP2(b);\nB(:,fixedDof)=[];\nNu=size(freeDof,1);\n\nb(fixedDof)=[];\n bigA = [A, B; ...\n B', sparse(Nu,Nu)];\n bigF = [b1; -b];\n\n\n% Solver\ntic;\n\n\n\n%bigU=PFGMRES(bigA, bigF,sparse(Ndof+Nu,1), Ndof, 10, 1e-6, [],[]);\n\n bigU=bigA\\bigF;\n w=bigU(1:Ndof);\n u(freeDof)=bigU(Ndof+1:Ndof+Nu);\ntoc\nend % end of function PoissonP2", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/iFEM/equation/biharmonicP2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424528443251, "lm_q2_score": 0.6477982315512488, "lm_q1q2_score": 0.5480000249466795}} {"text": "function [x, xdot, x2dot] = modifiednewmarkint(M, C, K, R, x0, xdot0, ...\n t, varargin)\n%Newmark's Direct Integration Method\n%--------------------------------------------------------------------------\n% Code written by : - Siva Srinivas Kolukula |\n% Senior Research Fellow |\n% Structural Mechanics Laboratory |\n% Indira Gandhi Center for Atomic Research |\n% INDIA\n% - Hamed Nokhostin |\n% B.S. Student |\n% Mechanical Engineering Faculty |\n% K.N.Toosi Uiversity of Technoloygy |\n% I.R.Iran |\n% E-mail : allwayzitzme@gmail.com\n% h_nokhostin@yahoo.com |\n%-------------------------------------------------------------------------\n% PURPOSE\n% ???\n% SYNTAX\n% [x, xdot, x2dot] = newmarkint(M, C, K, R, x0, xdot0, t, varargin)\n% INPUT\n% [M] : System Mass [n,n]\n% [C] : System Damping [n,n]\n% [K] : System Stiffness [n,n]\n% [R] : Externally Applied Load [n,nt]\n% [x0] : Initial Position [n,1]\n% [xdot0] : Initial Velocity [n,1]\n% [t] : Time Vector [1,nt]\n% [varargin]: Options\n%\n% OUTPUT\n% [x]: Displacemente Response [n,nt]\n% [xdot]: Velocity [n,nt]\n% [x2dot]: Acceleration [n,nt]\n%\n%\n% nt = number of time steps\n% n = number of nodes\n% The options include changing the value of the \"gamma\" and \"beta\"\n% coefficient which appear in the formulation of the method. By default\n% these values are set to gamma = 1/2 and beta = 1/4.\n%\n% EXAMPLE\n% To change nemark's coefficients, say to gamma = 1/3 and beta = 1/5, \n% the syntax is:\n% [u, udot, u2dot] = newmark_int(t,p,u0,udot0,m,k,xi, 1/3, 1/5) \n%\n%-------------------------------------------------------------------------\nif nargin == 7\n disp('Using default values:');\n disp(' gamma = 1/2');\n disp(' beta = 1/4');\n gamma = 1 / 2;\n beta = 1 / 4;\nelseif nargin == 9\n gamma = varargin{1};\n beta = varargin{2};\n disp('Using user''s values:');\n disp([' gamma = ', num2str(alpha)]);\n disp([' beta = ', num2str(delta)]);\nelse\n error('Incorrect number of imput arguments');\nend\n\ndt = t(2) - t(1);\nnt = fix((t(length(t) )- t(1)) / dt);\nn = length(M);\n\n% Constants used in Newmark's integration\na1 = gamma / (beta * dt);\na2 = 1 / (beta * dt ^ 2);\na3 = 1 / (beta * dt);\na4 = gamma / beta;\na5 = 1/(2 * beta);\na6 = (gamma / (2 * beta) - 1) * dt;\n\n\nx = zeros(n,nt);\nxdot = zeros(n,nt);\nx2dot = zeros(n,nt);\n\n% Initial Conditions\nx(:, 1) = x0;\nxdot(:, 1) = xdot0;\n%R0 = zeros(n,1);\nx2dot(:,1) = M \\ (R(:, 1) - C * xdot(:, 1) - K * x(:, 1)) ;\n\nKcap = K + a1 * C + a2 * M;\n\na = a3 * M + a4 * C;\nb = a5 * M + a6 * C;\n\n% Tme step starts\nfor i = 1 : nt\n delR = R(:, i) + a * xdot(:, i) + b * x2dot(:, i);\n delx = Kcap \\ delR ;\n delxdot = a1 * delx - a4 * xdot(:, i) - a6 * x2dot(:, i);\n delx2dot = a2 * delx - a3 * xdot(:, i) - a5 * x2dot(:, i);\n x(:, i + 1) = x(:, i) + delx;\n xdot(:, i + 1) = xdot(:, i) + delxdot;\n x2dot(:, i + 1) = x2dot(:, i) + delx2dot;\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/35465-newmark-integrator-function/modifiednewmarkint.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.845942452844325, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5480000134425909}} {"text": "% The static class geometricTools encapsulates the most used functions for surface processing\n% used to solve EEG forward or inverse problems.\n%\n% Author: Alejandro Ojeda, SCCN/INC/UCSD, 2012\n%\n% Contributors:\n% nonrigid_version23 -> D.Kroon, University of Twente, August\n% 2010 (http://www.mathworks.com/matlabcentral/fileexchange/20057)\n% getSurfaceLaplacian -> Nelson Trujillo Barreto and Pedro Antonio Valdes\n% Hernandez, Cuban Neuroscience Center\n% iso2mesh dependencies -> Qianqian Fang, http://iso2mesh.sourceforge.net/cgi-bin/index.cgi\n\nclassdef geometricTools\n methods\n function obj = geometricTools()\n end\n %%\n function disp(obj)\n disp(['Static class: ' class(obj)])\n disp('Static classes work like a namespace, they are used to create data and functions that can be accessed without creating an instance of the class.')\n methods(obj);\n end\n end\n methods(Static)\n %%\n function Xcentered = correctOrigin(X)\n [m,n] = size(X);\n K = ones(m,n);\n B = pinv(K'*K)*K'*X;\n X0 = K*B;\n Aff = eye(4);\n Aff([1 2],4) = X0(1,[1 2])';\n Xcentered = Aff\\[X ones(m,1)]';\n Xcentered = Xcentered(1:3,:)';\n end\n %%\n function [Aff,Sn, scale] = affineMapping(S,T)\n % S: source space\n % T: target space\n % S = [sx1 sy1 sz1; sx2 sy2 sz2; ... sxk syn szk]\n % T = [tx1 ty1 tz1; tx2 ty2 tz2; ... txk tyn tzk]\n %\n % d(Aff) = min frobenius(T -S* Aff')\n % Sn = S*Aff';\n \n [~,~,transform] = procrustes(T,S);\n scale = transform.b;\n Aff = [[transform.b*transform.T;transform.c(1,:)] [0;0;0;1]]';\n Sn = geometricTools.applyAffineMapping(S,Aff);\n end\n %%\n function T = applyAffineMapping(S,M)\n % [T 1] = [S 1]*M';\n T = [S ones(size(S,1),1)]*M';\n T(:,4) = [];\n end\n %%\n function [def,spacing,offset,SgridWarped] = bSplineMapping(S,T,Sgrid,options)\n if nargin < 4,\n options.Verbose = false;\n options.MaxRef = 5;\n end\n mn = min(Sgrid);\n Smn = bsxfun(@minus,S,mn);\n dim = max(Sgrid) - mn;\n Tmn = bsxfun(@minus,T,mn);\n [def,spacing,SgridWarped] = point_registration(dim,Smn,Tmn,options);\n offset = mn;\n SgridWarped = bsxfun(@plus,SgridWarped,offset);\n end\n %%\n function SgridWarped = applyBSplineMapping(def,spacing,offset,Sgrid)\n Smn = bsxfun(@minus,Sgrid,offset);\n SmnWarped = bspline_trans_points_double(def,spacing,Smn);\n SgridWarped = bsxfun(@plus,SmnWarped,offset);\n end\n %%\n function [neighbors,D,loc] = nearestNeighbor(vertices,T)\n if exist('DelaunayTri','file')\n dt = DelaunayTri(vertices(:,1),vertices(:,2),vertices(:,3)); %#ok\n else dt = delaunayTriangulation(vertices(:,1),vertices(:,2),vertices(:,3));\n end\n try [loc,D] = nearestNeighbor(dt, T);\n catch\n loc = nearestNeighbor(dt, T);\n D = sqrt(sum((vertices(loc,:)-T).^2,2));\n end\n neighbors = vertices(loc,:);\n end\n %%\n function Yi = ridgeInterpolation(vertices,faces,elec,Y)\n L = geometricTools.getSurfaceLaplacian(vertices,faces);\n K = geometricTools.localGaussianInterpolator(vertices,elec,1);\n K = full(K);\n Yi = ridgeGCV(Y,K,L,100,0);\n end\n %%\n function J = simulateGaussianSource(X,X0,h)\n if nargin < 3, h = 0.1;end\n J = geometricTools.localGaussianInterpolator(X,X0,h)';\n end\n function W = localGaussianInterpolator(X,Xi,h,normalize)\n if nargin < 3, h = 0.1;end\n if nargin < 4, normalize = false;end\n N = size(Xi,1);\n M = size(X,1);\n W = zeros(N,M);\n for it=1:N\n d = sum(bsxfun(@minus,X,Xi(it,:)).^2,2);\n W(it,:) = exp(-d/(2*h^2));\n end\n if normalize, W = bsxfun(@rdivide,W,sum(W,2)+eps);end\n end\n %%\n function D = isInConvexHull(X,Xi)\n \n X = geometricTools.correctOrigin(X);\n X = bsxfun(@rdivide,X,sqrt(sum(X.^2,2)));\n \n [x,y,z] = sphere(64);\n \n figure;\n surf(x,y,z,'FaceColor','g','FaceAlpha',0.7,'EdgeColor','none');\n set(gca,'Projection','perspective','DataAspectRatio',[1 1 1]); hold on;axis tight;camlight\n \n plot3(X(:,1),X(:,2),X(:,3),'.')\n \n X = geometricTools.correctOrigin(X);\n X = bsxfun(@rdivide,X,sqrt(sum(X.^2,2)));\n \n \n N = size(Xi,1);\n M = size(X,1);\n D = zeros(M,N);\n for it=1:N\n d = bsxfun(@minus,X,Xi(it,:));\n D(:,it) = sqrt(sum(( d ).^2,2));\n end\n end\n %%\n function Yi = localGaussianScatterInterpolator(X,Y,Xi)\n n = size(Y,2);\n if n==1\n F = TriScatteredInterp(X(:,1),X(:,2),X(:,3),Y,'nearest');\n Yi = F(Xi(:,1),Xi(:,2),Xi(:,3));\n else\n Yi = zeros(size(Xi,1),n);\n for it=1:n\n F = TriScatteredInterp(X(:,1),X(:,2),X(:,3),Y(:,it),'nearest');\n Yi(:,it) = F(Xi(:,1),Xi(:,2),Xi(:,3));\n end\n end\n W = geometricTools.localGaussianInterpolator(Xi,Xi,16);\n Yi = W*Yi;\n end\n %%\n function [rVertices,rFaces] = resampleSurface(vertices,faces,decimationPercent)\n if nargin < 2, error('Not enough input arguments.');end\n if nargin < 3, decimationPercent = 0.1;end\n if isempty(which('meshresample')), error('This function uses Iso2Mesh toolbox, you can download it for free fom: http://iso2mesh.sourceforge.net');end\n [rVertices,rFaces]=meshresample(vertices,faces,decimationPercent);\n end\n %%\n function sVertices = smoothSurface(vertices,faces,lambda,method)\n if nargin < 2, error('Not enough input arguments.');end\n if nargin < 3, lambda = 0.2;end\n if nargin < 4, method = 'lowpass';end\n \n maxIter = 20;\n N = size(vertices,1);\n \n if isempty(which('meshresample'))\n warning('MoBILAB:noIso2Mesh','This function uses Iso2Mesh toolbox if is installed, you can download it for free fom: http://iso2mesh.sourceforge.net');\n sVertices = vertices;\n for it=1:N\n ind = any(faces==it,2);\n indices = faces(ind,:);\n indices = indices(:);\n indices(indices==it) = [];\n W = geometricTools.localGaussianInterpolator(vertices(indices,:),vertices(it,:),10);\n sVertices(it,:) = sum((1./W)*vertices(indices,:),1)./sum(1./W);\n end\n return;\n end\n conn = neighborelem(faces,size(vertices,1));\n for it=1:N\n tmp = faces(conn{it},:);\n conn{it} = unique(tmp(:)');\n end\n sVertices = smoothsurf(vertices,[],conn,maxIter,lambda,method);\n end\n %%\n function [rVertices,rFaces] = refineSurface(vertices,faces,decimationRate,maxIter)\n if nargin < 3, decimationRate = 0.5;end\n if nargin < 4, maxIter = 3;end\n if isempty(which('meshresample')), error('This function uses Iso2Mesh toolbox, you can download it for free fom: http://iso2mesh.sourceforge.net');end\n \n tmpVertices = vertices;\n tmpFaces = faces;\n for it=1:maxIter\n [tmpVertices,tmpFaces] = geometricTools.resampleSurface(tmpVertices,tmpFaces,decimationRate);\n tmpVertices = geometricTools.smoothSurface(tmpVertices,tmpFaces);\n disp(it)\n end\n rVertices = tmpVertices;\n rFaces = tmpFaces;\n end\n %%\n function verticesExt = repareIntersectedSurface(surfInt,surfOut,dmax)\n if nargin < 3, dmax = 8;end\n verticesInt = surfInt.vertices;\n verticesExt = surfOut.vertices;\n [nVerticesInt,d] = geometricTools.nearestNeighbor(verticesExt,verticesInt);\n I = d < dmax;\n while any(I)\n I2 = ismember(verticesExt,nVerticesInt(I,:),'rows');\n verticesExt(I2,:) = 1.005*verticesExt(I2,:);\n [nVerticesInt,d] = geometricTools.nearestNeighbor(verticesExt,verticesInt);\n I = d < dmax;\n end\n if any(verticesExt(:) ~= surfOut.vertices(:))\n verticesExt = geometricTools.smoothSurface(verticesExt,surfOut.faces);\n end\n end\n %%\n function [normals,faces] = getSurfaceNormals(vertices,faces,normalsIn)\n if nargin < 3, normalsIn = true;end\n h = figure('visible','off');\n h2 = patch('vertices',vertices,'faces',fliplr(faces));\n normals = get(h2,'vertexnormals');close(h);\n if isempty(normals)\n normals = vertices;\n end\n normals = normals./(sqrt(sum(normals.^2,2))*[1 1 1]);\n area1 = geometricTools.getSurfaceArea(vertices,faces);\n area2 = geometricTools.getSurfaceArea(vertices+normals,faces);\n if area2 < area1% && normalsIn\n faces = fliplr(faces);\n h = figure('visible','off');h2 = patch('vertices',vertices,'faces',fliplr(faces));\n normals = get(h2,'vertexnormals');close(h);\n normals = normals./(sqrt(sum(normals.^2,2))*[1 1 1]);\n end\n if normalsIn\n faces = fliplr(faces);\n h = figure('visible','off');h2 = patch('vertices',vertices,'faces',fliplr(faces));\n normals = get(h2,'vertexnormals');close(h);\n normals = normals./(sqrt(sum(normals.^2,2))*[1 1 1]);\n end\n end\n %%\n function [area,areas] = getSurfaceArea(vertices,faces)\n x1= vertices(faces(:,1),1);\n y1= vertices(faces(:,1),2);\n z1= vertices(faces(:,1),3);\n x2= vertices(faces(:,2),1);\n y2= vertices(faces(:,2),2);\n z2= vertices(faces(:,2),3);\n x3= vertices(faces(:,3),1);\n y3= vertices(faces(:,3),2);\n z3= vertices(faces(:,3),3);\n area = sqrt(((y2-y1).*(z3-z1)-(y3-y1).*(z2-z1)).^2+((z2-z1).*(x3-x1)-(z3-z1).*(x2-x1)).^2+...\n ((x2-x1).*(y3-y1)-(x3-x1).*(y2-y1)).^2)/2;\n areas = area;\n area = sum(area);\n end\n function L = getSurfaceLaplacian1(vertices,faces)\n % LAPLACES Calculates a Discrete Surface Laplacian Matrix\n % for a triangulated surface\n \n Nv = size(vertices,1);\n Nf = size(faces,1);\n L = spalloc(Nv,Nv,3*Nf);\n %L = speye(Nvtx);\n for fi=1:Nf\n for k=1:3\n kk = mod(k,3)+1;\n L(faces(fi,k),faces(fi,kk)) = sqrt( sum((vertices(faces(fi,k),:)-vertices(faces(fi,kk),:)).^2,2));\n end\n end\n L(L>0) = 1./L(L>0);\n L = (L+L')/2;\n L = L - spdiags(sum(L,2),0,Nv,Nv);\n end\n function L = getSurfaceLaplacian(vertices,faces)\n % LAPLACES Calculates a Discrete Surface Laplacian Matrix\n % for a triangulated surface\n %\n % Reference:\n % [1] Huiskamp, G., 1991, Difference formulas for the surface laplacian\n % on a triangulated surface, Journal of Computational Physics 95,\n % 477-496.\n %\n % Nelson Trujillo Barreto\n % Pedro antonio Valdes Hernandez\n % Cuban Neuroscience Center\n \n Cortex.vertices = vertices;\n Cortex.faces = faces;\n vtx = Cortex.vertices;\n tri = Cortex.faces;\n [nei,nei_tri] = geometricTools.get_neis(Cortex);\n Nvtx = size(vtx,1);\n L = speye(Nvtx);\n for j=1:Nvtx,\n nei_tri_j = tri(nei_tri{j},:);\n nei_j = nei{j};\n PHI_jk = [];\n rj = vtx(j,:);\n Nj = length(nei_j);\n for k=1:Nj,\n \n [indi,indj]=find(nei_tri_j==nei_j(k)); %#ok\n nei_tri_jk = nei_tri_j(indi,:);\n if size(nei_tri_jk,1) < 2,\n break;\n end\n nei_k_lr = setxor(nei_tri_jk(1,:),nei_tri_jk(2,:));\n \n rk2 = sum((rj-vtx(nei_j(k),:)).^2);\n rl2 = sum((rj-vtx(nei_k_lr(1),:)).^2);\n rr2 = sum((rj-vtx(nei_k_lr(2),:)).^2);\n rkl2 = sum((vtx(nei_k_lr(1),:)-vtx(nei_j(k),:)).^2);\n rkr2 = sum((vtx(nei_k_lr(2),:)-vtx(nei_j(k),:)).^2);\n \n cos_phi_kl = (rk2+rl2-rkl2)./sqrt(rk2.*rl2)./2;\n cos_phi_kr = (rk2+rr2-rkr2)./sqrt(rk2.*rr2)./2;\n sin_phi_kl = sqrt(1-cos_phi_kl.^2);\n sin_phi_kr = sqrt(1-cos_phi_kr.^2);\n \n PHI_jk = [PHI_jk (1-cos_phi_kl)./(sin_phi_kl+eps)+(1-cos_phi_kr)./(sin_phi_kr+eps)]; %#ok\n end\n if ~isempty(PHI_jk)\n rjk = sqrt(sum((vtx(nei_j,:)-repmat(rj,Nj,1)).^2,2));\n rj_bar = mean(rjk);\n \n theta_jk = 4*PHI_jk'./(rj_bar*sum(PHI_jk)*rjk);\n L(j,nei_j) = theta_jk'; %#ok\n else\n L(j,nei_j) = 0; %#ok\n L(j,j) = 1; %#ok\n end\n end;\n \n L = L - speye(Nvtx,Nvtx);\n L = L - spdiags(sum(L,2),0,Nvtx,Nvtx);\n d = diag(L);\n ind = find(d==0);\n if ~isempty(ind), for it=1:length(ind), L(ind(it),ind(it)) = 1;end;end\n %th = prctile(nonzeros(L),[0.1 99.9]);\n %L(L>th(2)) = 0;\n %L(LmaxColorValue) = 0;\n indNonZero = A(:)~=0;\n colorTable = A(indNonZero);\n [x,y,z] = ndgrid(1:v.dim(1),1:v.dim(2),1:v.dim(3));\n M = v.mat;\n X = [x(:) y(:) z(:) ones(numel(x),1)]*M';\n X = X(indNonZero,1:3); \n clear x y z\n F = TriScatteredInterp(X,colorTable,'nearest');\n n = size(Surf.vertices,1);\n labelsValue = F(Surf.vertices);\n colorTable = labelsValue;\n hwait = waitbar(0,'Atlas correction...');\n for it=1:n\n neigInd = any(Surf.faces == it,2);\n vertexInedex = Surf.faces(neigInd,:);\n vertexInedex = vertexInedex(:);\n [y,x] = hist(labelsValue(vertexInedex));\n [~,loc] = max(y);\n [~,loc] = min(abs(labelsValue(vertexInedex) - x(loc)));\n labelsValue(it) = colorTable(vertexInedex(loc));\n waitbar(it/n,hwait);\n end\n waitbar(1,hwait);\n close(hwait);\n atlas.colorTable = labelsValue;\n atlas.label = textfile2cell(txtAtlasLabel);\n atlas.label = atlas.label(1:max(atlas.colorTable));\n for it=1:length(atlas.label)\n ind = find(atlas.label{it} == ' ');\n atlas.label{it} = atlas.label{it}(ind(1)+1:ind(end)-1);\n end\n end\n %%\n function X = projectOntoUnitarySphere(X)\n [~,X(:,1),X(:,2),X(:,3)] = geometricTools.projectOnSphere(X(:,1),X(:,2),X(:,3));\n [azimuth,elevation,r] = cart2sph(X(:,1),X(:,2),X(:,3));\n [X(:,1),X(:,2),X(:,3)] = sph2cart(azimuth,elevation,elevation*0+1);\n end\n %%\n function [Yi,W] = spSplineInterpolator(X,Y,Xi,plotFlag)\n % Computes the spherical spline interpolator based on Perrin, F., \n % Pernier, J., Bertrand, O., Echallier, J.F. (1990). Corrigenda \n % EEG 02274. Electroencephalography and Clinical Neurophysiology, 76, 565.\n \n if nargin < 4, plotFlag = false;end\n %X0 = mean(X);\n %X = bsxfun(@minus,X,X0);\n %Xi = bsxfun(@minus,Xi,X0);\n X = geometricTools.projectOntoUnitarySphere(X);\n Xi = geometricTools.projectOntoUnitarySphere(Xi);\n %X = bsxfun(@rdivide,X,sqrt(sum(X.^2,2)));\n %Xi = bsxfun(@rdivide,Xi,sqrt(sum(Xi.^2,2)));\n \n %-- \n M = size(X,1);\n One = ones(size(Xi,1),1);\n %--\n \n % Solving eq. 4 of Perrin et al. (1989)\n COS_X = geometricTools.cosines(X,X);\n COS_Xi = geometricTools.cosines(Xi,X);\n \n % Solving eq. 3 of Perrin et al. (1989)\n Gx = geometricTools.sphericalSpline(COS_X);\n Gxi = geometricTools.sphericalSpline(COS_Xi);\n \n % Solving eq. 2 Perrin et al. (1989)\n [C,~,~,T] = ridgeGCV([Y;0],[Gx ones(M,1);ones(1,M) 0],eye(M+1));\n \n % Interpolating with the spherical harmonics\n Yi = [Gxi One]* C;\n \n W = [Gxi One]* T(:,1:end-1);\n \n % Plot the input & projected electrode positions on a sphere\n if plotFlag\n geometricTools.plot_on_sphere(X,Y,Xi,Yi);\n end\n end\n %%\n function Gx = sphericalSpline(x)\n % sphericalSpline solves eq. 3 of Perrin et al. (1989)\n % g(COS) = 1/4pi * sum[n=1:inf] (( (2*n+1)/( n^m * (n+1)^m ) ) * Pn(COS));\n \n m = 4;\n N = 16; % gives accuracy of 10^-6\n \n P = cat(3, ones(size(x)), x);\n Gx = 3 / 2 ^ m * P(:, :, 2);\n for n = 2:N\n P(:, :, 3) = ((2 * n - 1) * x .* P(:, :, 2) - (n - 1) * P(:, :, 1)) / n;\n P = P(:,:,[2 3 1]);\n Gx = Gx + (2 * n + 1) / (n ^ m * (n + 1) ^ m) * P(:, :, 2);\n end\n Gx = Gx / (4 * pi);\n end\n %%\n function [r,x,y,z] = projectOnSphere(X,Y,Z,xo,yo,zo)\n % projectOnSphere - calculates projections of xyz positions\n % onto the unitary sphere\n %\n % Usage: [r,x,y,z] = projectOnSphere(X,Y,Z,xo,yo,zo,plotFlag)\n %\n % Notes: The general formula for a sphere, with radius r is given by:\n %\n % (x - xo)^2 + (y - yo)^2 + (z - zo)^2 = r^2\n %\n % This function takes arguments for cartesian co-ordinates\n % of X,Y,Z (assume Z > 0) and the center of the sphere (xo,yo,zo).\n % If (xo,yo,zo) is not provided a cnter at (0,0,0) is assumed.\n %\n % Returned values are the fitted radius 'r' (constant)\n % and the (x,y,z) Cartesian coordinates of the projected points\n %\n %\n % $Revision: 1.3 $ $Date: 2005/07/12 22:16:48 $\n % Licence: GNU GPL, no express or implied warranties\n % History: 02/2002, Darren.Weber_at_radiology.ucsf.edu\n % adapted from elec_fit_sph\n %\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n \n % initialise centroid, unless input parameters defined\n if nargin < 4, xo = 0;end\n if nargin < 5, yo = 0;end\n if nargin < 6, zo = 0;end\n \n % Initialise r0 as a rough guess at the sphere radius\n rX = (max(X) - min(X)) / 2;\n rY = (max(Y) - min(Y)) / 2;\n rZ = max(Z) - zo;\n r0 = mean([ rX rY rZ ]);\n \n % perform least squares estimate of spherical radius (r)\n options = optimset('fminsearch');\n r = fminsearch(@geometricTools.fit2sphere,r0, options, X, Y, Z, xo, yo, zo);\n \n \n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % Find the projection point of X,Y,Z to the fitted sphere radius r\n \n % Convert Cartesian X,Y,Z to spherical (radians)\n theta = atan2( (Y-yo), (X-xo) );\n phi = atan2( sqrt( (X-xo).^2 + (Y-yo).^2 ), (Z-zo) );\n % do not recalc: r = sqrt( (X-xo).^2 + (Y-yo).^2 + (Z-zo).^2);\n \n % Recalculate X,Y,Z for constant r, given theta & phi.\n R = ones(size(phi)) * r;\n x = R .* sin(phi) .* cos(theta);\n y = R .* sin(phi) .* sin(theta);\n z = R .* cos(phi);\n end \n end\n methods(Static,Hidden=true)\n %%\n function f = fit2sphere(r, X, Y, Z, xo, yo, zo)\n S = (X-xo).^2 + (Y-yo).^2 + (Z-zo).^2 - r^2;\n f = sum( S.^2 );\n end\n %%\n function Cos = cosines(A,B)\n Na = size(A,1);\n Nb = size(B,1);\n One1 = ones(1,Nb);\n One2 = ones(Na,1);\n Xe = A(:,1)*One1;\n Ye = A(:,2)*One1;\n Ze = A(:,3)*One1;\n Xf = One2*B(:,1)';\n Yf = One2*B(:,2)';\n Zf = One2*B(:,3)';\n Cos = (Xe-Xf).^2 + (Ye-Yf).^2 + (Ze-Zf).^2;\n Cos = 1-Cos/2;\n Cos(Cos > 1) = 1-eps;\n Cos(Cos < -1) = -1+eps;\n end\n function plot_on_sphere(X,Y,Xi,Yi)\n [~,X(:,1), X(:,2), X(:,3)] = geometricTools.projectOnSphere(X(:,1), X(:,2), X(:,3));\n [~,Xi(:,1),Xi(:,2),Xi(:,3)] = geometricTools.projectOnSphere(Xi(:,1),Xi(:,2),Xi(:,3));\n X = bsxfun(@rdivide,X,sqrt(sum(X.^2,2)));\n Xi = bsxfun(@rdivide,Xi,sqrt(sum(Xi.^2,2)));\n \n Xt = [X;Xi];\n Yt = [Y;Yi];\n Xt = bsxfun(@rdivide,Xt,sqrt(sum(Xt.^2,2)));\n Xi = bsxfun(@rdivide,Xi,sqrt(sum(Xi.^2,2)));\n Ne = size(X,1);\n Nf = 72;\n [Xs,Ys,Zs]=sphere(Nf);\n Xsp = [Xs(:) Ys(:) Zs(:)];\n Fsp = geometricTools.localGaussianInterpolator(Xt,Xsp,0.2);\n \n \n %[J,lambdaOpt,~,iFsp] = ridgeGCV(Yt,Fsp',eye(size(Xsp,1)),100,1);\n %J = iFsp*Yt;\n Ysp = Fsp*Yt;\n figure('NumberTitle','off','Name','Electrode Placements');\n set(gca,'Projection','perspective','DataAspectRatio',[1 1 1]); hold on\n %plot3(x,y,z,'b.');\n plot3(X(:,1),X(:,2),X(:,3),'ro');\n plot3(Xi(:,1),Xi(:,2),Xi(:,3),'k.')\n legend('input xyz','projected head','Location','BestOutside');\n surf(Xs,Ys,Zs,reshape(Ysp,[Nf Nf]+1),'specularstrength',0.1,'facealpha',0.9,'linestyle','none');\n camlight\n camlight headlight\n view(2); rotate3d;\n axis vis3d\n end\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/MoBILAB/geometricTools.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424256566558, "lm_q2_score": 0.6477982247516796, "lm_q1q2_score": 0.5480000015825113}} {"text": "function f=comp_idgt_fac(coef,gf,L,a,M)\n%COMP_IDGT_FAC Full-window factorization of a Gabor matrix.\n% Usage: f=comp_idgt_fac(c,g,a,M)\n%\n% Input parameters:\n% c : M x N array of coefficients.\n% gf : Factorization of window (from facgabm).\n% a : Length of time shift.\n% M : Number of frequency shifts.\n% Output parameters:\n% f : Reconstructed signal.\n%\n% Do not call this function directly, use IDGT.\n% This function does not check input parameters!\n%\n% If input is a matrix, the transformation is applied to\n% each column.\n%\n% This function does not handle multidimensional data, take care before\n% you call it.\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.\nN=L/a;\nb=L/M;\n\nR=prod(size(gf))/L;\n\nW=prod(size(coef))/(M*N*R);\n\nN=L/a;\nb=L/M;\n\n[c,h_a,h_m]=gcd(a,M);\nh_a=-h_a;\np=a/c;\nq=M/c;\nd=N/q;\n\nff=zeros(p,q*W,c,d,assert_classname(coef,gf));\nC=zeros(q*R,q*W,c,d,assert_classname(coef,gf));\nf=zeros(L,W,assert_classname(coef,gf));\n\n% Apply ifft to the coefficients.\n%coef=ifft(reshape(coef,M,N*W))*sqrt(M);\ncoef=ifft(coef)*sqrt(M);\n \n% Set up the small matrices\n\ncoef=reshape(coef,M,N,R,W);\n\nif p==1\n\n for rw=0:R-1\n for w=0:W-1\n for s=0:d-1\n\tfor l=0:q-1\n\t for u=0:q-1\n\t C(u+1+rw*q,l+1+w*q,:,s+1)=coef((1:c)+l*c,mod(u+s*q+l,N)+1,rw+1,w+1);\n\t end;\n\tend;\n end;\n end;\n end;\nelse\n % Rational oversampling\n for rw=0:R-1\n for w=0:W-1\n for s=0:d-1\n\tfor l=0:q-1\n\t for u=0:q-1\n\t C(u+1+rw*q,l+1+w*q,:,s+1)=coef((1:c)+l*c,mod(u+s*q-l*h_a,N)+1,rw+1,w+1);\n\t end;\n\tend;\n end;\n end;\n end;\nend;\n\n% FFT them\nif d>1\n C=fft(C,[],4);\nend;\n\n% Multiply them\nfor r=0:c-1 \n for s=0:d-1\n CM=reshape(C(:,:,r+1,s+1),q*R,q*W);\n GM=reshape(gf(:,r+s*c+1),p,q*R);\n\n ff(:,:,r+1,s+1)=GM*CM;\n end;\nend;\n\n% Inverse FFT\nif d>1\n ff=ifft(ff,[],4);\nend;\n\n% Place the result \nif p==1\n\n for s=0:d-1\n for w=0:W-1\n for l=0:q-1\n\tf((1:c)+mod(s*M+l*a,L),w+1)=reshape(ff(1,l+1+w*q,:,s+1),c,1);\n end;\n end;\n end;\n\nelse\n % Rational oversampling\n for w=0:W-1\n for s=0:d-1\n for l=0:q-1\n\tfor k=0:p-1\n\t f((1:c)+mod(k*M+s*p*M-l*h_a*a,L),w+1)=reshape(ff(k+1,l+1+w*q,:,s+1),c,1);\n\tend;\n end;\n end;\n end;\n\nend;\n\n\n\n\n\n\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/comp/comp_idgt_fac.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424217727027, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5479999933144494}} {"text": "%typ==0 -> nav=geodetic_frame, typ==1 -> nav=wander_frame\n%although this implementation can be used as wander frame mechanization,\n%this is still singular as it explicitly computes the wander angle for\n%transport rate computation.\n%For non-singular implementation see strapdown_wander_quat (which uses\n%geowander to compute earth curvature)\n\n\nfunction [Cbn_new, Vn_new, Cen_new, h_new]=strapdown_Cen_dcm(Cbn, Vn, Cen, h, a, w, dt, typ)\n\n%%Geo Params\n[ll, wander]=dcm2llh_v000(Cen);\nCgn=[wander(2) wander(1) 0;-wander(1) wander(2) 0;0 0 1];\nllh=[ll;h];\n[Rn, Re, g, sL, cL, WIE_E]=geoparam_v000(llh);\n\nwie_n=Cen*[0; 0; WIE_E];\nwen_n=Cgn*[0 1/(Re+llh(3)) 0; -1/(Rn+llh(3)) 0 0;0 -sL/cL/(Re+llh(3)) 0]*Cgn'*Vn;\n\nif (typ==1) %wander transport rate\n wen_n(3)=0;\nend\n\n%%%Update attitude\n%Part I:Body frame update\nrot=w*dt;\nrot_norm=norm(rot);\nsr_a=1-(rot_norm^2/6)+(rot_norm^4/120);\nsr_b=(1/2)-(rot_norm^2/24)+(rot_norm^4/720);\nmx_a=eye(3)+sr_a*skew(rot)+sr_b*skew(rot)*skew(rot);\n\n%Part II:Nav Frame update\nrot=-(wen_n+wie_n)*dt;\nrot_norm=norm(rot);\nsr_a=1-(rot_norm^2/6)+(rot_norm^4/120);\nsr_b=(1/2)-(rot_norm^2/24)+(rot_norm^4/720);\nmx_b=eye(3)+sr_a*skew(rot)+sr_b*skew(rot)*skew(rot);\n\nCbn_new=mx_b*Cbn*mx_a;\n\n%%%Update Velocity\nvel_inc1=(Cbn*(a*dt))+[0;0;g]*dt;\nvel_inc2=(cross(Vn,2*wie_n+wen_n))*dt;\nVn_new=Vn+vel_inc1+vel_inc2;\n\n%%%Update Cen (position + wander_angle)\nrot=-wen_n*dt;\nrot_norm=norm(rot);\nsr_a=1-(rot_norm^2/6)+(rot_norm^4/120);\nsr_b=(1/2)-(rot_norm^2/24)+(rot_norm^4/720);\nmx_b=eye(3)+sr_a*skew(rot)+sr_b*skew(rot)*skew(rot);\nCen_new=mx_b*Cen;\n\n%update height\nh_new=h-Vn(3)*dt;\n", "meta": {"author": "JzHuai0108", "repo": "ekfmonoslam", "sha": "443f6be744732453cdb90679abcaf5c962a6295e", "save_path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam", "path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam/ekfmonoslam-443f6be744732453cdb90679abcaf5c962a6295e/instk/INS/strapdown_Cen_dcm_v000.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513814471134, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5479519381567451}} {"text": "function [ xa, xb, fxa, fxb ] = secant ( fatol, step_max, prob, xatol, xmin, ...\n xmax, xa, xb, fxa, fxb )\n\n%*****************************************************************************80\n%\n%% SECANT carries out the secant method to seek a root of F(X) = 0.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 16 May 2011\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real FATOL, an absolute error tolerance for the\n% function value of the root. If an approximate root X satisfies\n% ABS ( F ( X ) ) <= FATOL, then X will be accepted as the\n% root and the iteration will be terminated.\n%\n% Input, integer STEP_MAX, the maximum number of steps allowed\n% for an iteration.\n%\n% Input, integer PROB, the index of the function whose root is\n% to be sought.\n%\n% Input, real XATOL, an absolute error tolerance for the root.\n%\n% Input, real XMAX, XMIN, the interval in which the root should\n% be sought.\n%\n% Input/output, real XA, XB, two points at which the \n% function differs in sign. On output, these values have been adjusted\n% to a smaller interval.\n%\n% Input/output, real FXA, FXB, the value of the function \n% at XA and XB.\n% \n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SECANT\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Step X F(X)\\n' );\n fprintf ( 1, '\\n' );\n\n step_num = -1;\n fprintf ( 1, ' %4d %14g %14g\\n', step_num, xa, fxa );\n\n if ( abs ( fxa ) <= fatol )\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Function small enough for convergence.\\n' );\n return\n end\n\n step_num = 0;\n fprintf ( 1, ' %4d %14g %14g\\n', step_num, xb, fxb );\n\n for step_num = 1 : step_max\n\n if ( abs ( fxb ) <= fatol )\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Function small enough for convergence.\\n' );\n return\n end\n\n if ( abs ( xa - xb ) < xatol )\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Interval small enough for convergence.\\n' );\n return\n end\n\n if ( xb < xmin || xmax < xb )\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Iterate has left the region [XMIN,XMAX].\\n' );\n return\n end\n\n if ( fxa == fxb )\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' F(A) = F(B), algorithm fails.\\n' );\n return\n end\n\n xc = ( fxa * xb - fxb * xa ) / ( fxa - fxb );\n\n fxc = p00_fx ( prob, xc );\n\n xa = xb;\n fxa = fxb;\n xb = xc;\n fxb = fxc;\n fprintf ( 1, ' %4d %14g %14g\\n', step_num, xb, fxb );\n\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Took maximum number of steps.\\n' );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_zero/secant.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743735019595, "lm_q2_score": 0.7401743677704878, "lm_q1q2_score": 0.5478580989467298}} {"text": "function ROCout=roc(varargin)\n% ROC - Receiver Operating Characteristics.\n% The ROC graphs are a useful tecnique for organizing classifiers and\n% visualizing their performance. ROC graphs are commonly used in medical\n% decision making.\n%\n% Syntax: ROCout=roc(x,thresholds,alpha,verbose)\n%\n% Input: x - This is a Nx2 data matrix. The first column is the column of the data value;\n% The second column is the column of the tag: unhealthy (1) and\n% healthy (0).\n% Thresholds - If you want to use all unique values in x(:,1) \n% then set this variable to 0 or leave it empty; \n% else set how many unique values you want to use (min=3);\n% alpha - significance level (default 0.05)\n% verbose - if you want to see all reports and plots (0-no; 1-yes by\n% default);\n%\n% Output: if verbose = 1\n% the ROCplots, the sensitivity and specificity at thresholds; the Area\n% under the curve with Standard error and Confidence interval and\n% comment.\n% if ROCout is declared, you will have a struct:\n% ROCout.AUC=Area under the curve (AUC);\n% ROCout.SE=Standard error of the area;\n% ROCout.ci=Confidence interval of the AUC\n% ROCout.co=Cut off points\n% ROCdata.xr and ROCdata.yr points for ROC plot\n%\n% USING roc WITHOUT ANY DATA, IT WILL RUN A DEMO\n%\n% Created by Giuseppe Cardillo\n% giuseppe.cardillo-edta@poste.it\n%\n% To cite this file, this would be an appropriate format:\n% Cardillo G. (2008) ROC curve: compute a Receiver Operating Characteristics curve.\n% http://www.mathworks.com/matlabcentral/fileexchange/19950\n\n%Input Error handling\nargs=cell(varargin);\nnu=numel(args);\nif isempty(nu)\n error('Warning: almost the data matrix is required')\nelseif nu>4\n error('Warning: Max four input data are required')\nend\ndefault.values = {[165 1;140 1;154 1;139 1;134 1;154 1;120 1;133 1;150 1;...\n146 1;140 1;114 1;128 1;131 1;116 1;128 1;122 1;129 1;145 1;117 1;140 1;...\n149 1;116 1;147 1;125 1;149 1;129 1;157 1;144 1;123 1;107 1;129 1;152 1;...\n164 1;134 1;120 1;148 1;151 1;149 1;138 1;159 1;169 1;137 1;151 1;141 1;...\n145 1;135 1;135 1;153 1;125 1;159 1;148 1;142 1;130 1;111 1;140 1;136 1;...\n142 1;139 1;137 1;187 1;154 1;151 1;149 1;148 1;157 1;159 1;143 1;124 1;...\n141 1;114 1;136 1;110 1;129 1;145 1;132 1;125 1;149 1;146 1;138 1;151 1;...\n147 1;154 1;147 1;158 1;156 1;156 1;128 1;151 1;138 1;193 1;131 1;127 1;...\n129 1;120 1;159 1;147 1;159 1;156 1;143 1;149 1;160 1;126 1;136 1;150 1;...\n136 1;151 1;140 1;145 1;140 1;134 1;140 1;138 1;144 1;140 1;140 1;159 0;...\n136 0;149 0;156 0;191 0;169 0;194 0;182 0;163 0;152 0;145 0;176 0;122 0;...\n141 0;172 0;162 0;165 0;184 0;239 0;178 0;178 0;164 0;185 0;154 0;164 0;...\n140 0;207 0;214 0;165 0;183 0;218 0;142 0;161 0;168 0;181 0;162 0;166 0;...\n150 0;205 0;163 0;166 0;176 0;],0,0.05,1};\ndefault.values(1:nu) = args;\n[x threshold alpha verbose] = deal(default.values{:});\nif isvector(x)\n error('Warning: X must be a matrix')\nend\nif ~all(isfinite(x(:))) || ~all(isnumeric(x(:)))\n error('Warning: all X values must be numeric and finite')\nend\nx(:,2)=logical(x(:,2));\nif all(x(:,2)==0)\n error('Warning: there are only healthy subjects!')\nend\nif all(x(:,2)==1)\n error('Warning: there are only unhealthy subjects!')\nend\nif nu>=2\n if isempty(threshold)\n threshold=0;\n else\n if ~isscalar(threshold) || ~isnumeric(threshold) || ~isfinite(threshold)\n error('Warning: it is required a numeric, finite and scalar THRESHOLD value.');\n end\n if threshold ~= 0 && threshold <3\n error('Warning: Threshold must be 0 if you want to use all unique points or >=2.')\n end\n end\n if nu>=3\n if isempty(alpha)\n alpha=0.05;\n else3\n if ~isscalar(alpha) || ~isnumeric(alpha) || ~isfinite(alpha)\n error('Warning: it is required a numeric, finite and scalar ALPHA value.');\n end\n if alpha <= 0 || alpha >= 1 %check if alpha is between 0 and 1\n error('Warning: ALPHA must be comprised between 0 and 1.')\n end\n end\n end\n if nu==4\n verbose=logical(verbose);\n end\nend\nclear args default nu\n\ntr=repmat('-',1,100);\nlu=length(x(x(:,2)==1)); %number of unhealthy subjects\nlh=length(x(x(:,2)==0)); %number of healthy subjects\nz=sortrows(x,1);\nif threshold==0\n labels=unique(z(:,1));%find unique values in z\nelse\n K=linspace(0,1,threshold+1); K(1)=[];\n labels=quantile(unique(z(:,1)),K)';\nend\nlabels(end+1)=labels(end)+1;\nll=length(labels); %count unique value\na=zeros(ll,2); b=a; c=zeros(ll,1);%array preallocation\nubar=mean(x(x(:,2)==1),1); %unhealthy mean value\nhbar=mean(x(x(:,2)==0),1); %healthy mean value\nfor K=1:ll\n if hbarlabels(K)));\n FP=length(x(x(:,2)==0 & x(:,1)>labels(K)));\n FN=length(x(x(:,2)==1 & x(:,1)<=labels(K)));\n TN=length(x(x(:,2)==0 & x(:,1)<=labels(K)));\n else\n TP=length(x(x(:,2)==1 & x(:,1)=labels(K)));\n TN=length(x(x(:,2)==0 & x(:,1)>=labels(K)));\n end\n M=[TP FP;FN TN];\n a(K,:)=diag(M)'./sum(M); %Sensitivity and Specificity\n b(K,:)=[a(K,1)/(1-a(K,2)) (1-a(K,1))/a(K,2)]; %Positive and Negative likelihood ratio\n c(K)=trace(M)/sum(M(:)); %Efficiency\nend\nb(isnan(b))=Inf;\n\nif hbar1; ci(2)=1; end\nm=zeros(1,4); \n%z-test\nSAUC=(Area-0.5)/Serror; %standardized area\np=1-0.5*erfc(-SAUC/realsqrt(2)); %p-value\n\nif verbose\n %Performance of the classifier\n if Area==1\n str='Perfect test';\n elseif Area>=0.90 && Area<1\n str='Excellent test';\n elseif Area>=0.80 && Area<0.90\n str='Good test';\n elseif Area>=0.70 && Area<0.80\n str='Fair test';\n elseif Area>=0.60 && Area<0.70\n str='Poor test';\n elseif Area>=0.50 && Area<0.60\n str='Fail test';\n else\n str='Failed test - less than chance';\n end\n %display results\n disp('ROC CURVE ANALYSIS')\n disp(' ')\n disp(tr)\n str2=['AUC\\t\\t\\tS.E.\\t\\t\\t\\t' num2str((1-alpha)*100) '%% C.I.\\t\\t\\tComment\\n'];\n fprintf(str2)\n disp(tr)\n fprintf('%0.5f\\t\\t\\t%0.5f\\t\\t\\t%0.5f\\t\\t%0.5f\\t\\t\\t%s\\n',Area,Serror,ci,str)\n disp(tr)\n fprintf('Standardized AUC\\t\\t1-tail p-value\\n')\n if p<1e-4\n fprintf('%0.4f\\t\\t\\t\\t%0.4e',SAUC,p)\n else\n fprintf('%0.4f\\t\\t\\t\\t%0.4f',SAUC,p)\n end\n if p<=alpha\n fprintf('\\t\\tThe area is statistically greater than 0.5\\n')\n else\n fprintf('\\t\\tThe area is not statistically greater than 0.5\\n')\n end\n disp(' ')\n %display graph\n H=figure;\n set(H,'Position',[4 402 560 420])\n hold on\n plot([0 1],[0 1],'k');\n plot(xfit,yfit,'marker','none','linestyle','-','color','r','linewidth',2);\n H1=plot(xroc,yroc,'bo');\n set(H1,'markersize',6,'markeredgecolor','b','markerfacecolor','b')\n hold off\n xlabel('False positive rate (1-Specificity)')\n ylabel('True positive rate (Sensitivity)')\n title(sprintf('ROC curve (AUC=%0.4f)',Area))\n axis square\nend\n\nif p<=alpha\n ButtonName = questdlg('Do you want to input the true prevalence?', 'Prevalence Question', 'Yes', 'No', 'Yes');\n if strcmp(ButtonName,'Yes')\n ButtonName = questdlg('Do you want to input the true prevalence as:', 'Prevalence Question', 'Ratio', 'Probability', 'Ratio');\n switch ButtonName\n case 'Ratio'\n prompt={'Enter the Numerator or the prevalence ratio:','Enter the denominator or the prevalence ratio:'};\n name='Input for Ratio prevalence';\n Ratio=str2double(inputdlg(prompt,name));\n POD=Ratio(1)/diff(Ratio); %prior odds\n case 'Probability'\n prompt={'Enter the prevalence probability comprised between 0 and 1:'};\n name='Input for prevalence';\n pr=str2double(inputdlg(prompt,name));\n POD=pr/(1-pr); %prior odds\n end\n d=[1./(1+1./(b(:,1).*POD)) 1./(1+(b(:,2).*POD))];\n d((a(:,1)==0 & a(:,2)==1),1)=NaN;\n d((a(:,1)==1 & a(:,2)==0),2)=NaN;\n table=[labels'; a(:,1)'; a(:,2)';c';d(:,1)'.*100; d(:,2)'.*100;]';\n if verbose\n disp('ROC CURVE DATA')\n disp(tr)\n fprintf('Cut-off \\tSensitivity\\tSpecificity\\tEfficiency\\tPos.Pred.\\tNeg.Pred.\\n')\n fprintf('%0.2f\\t\\t%0.4f\\t\\t%0.4f\\t\\t%0.4f\\t\\t%0.2f\\t\\t%0.2f\\n',table')\n disp(tr)\n disp(' ')\n end\n else\n table=[labels'; a(:,1)'; a(:,2)';c']';\n if verbose\n disp('ROC CURVE DATA')\n disp(tr)\n fprintf('Cut-off \\tSensitivity\\tSpecificity\\tEfficiency\\n')\n fprintf('%0.2f\\t\\t%0.4f\\t\\t%0.4f\\t\\t%0.4f\\n',table')\n disp(tr)\n disp(' ')\n end\n end\n CSe=find(table(:,2)==max(table(:,2)),1,'first'); %Max sensitivity cut-off\n CSp=find(table(:,3)==max(table(:,3)),1,'last'); %Max specificity cut-off\n CEff=find(table(:,4)==max(table(:,4)),1,'first'); %Max efficiency cut-off\n d=realsqrt(xroc.^2+(1-yroc).^2); %apply the Pitagora's theorem\n [~,CE]=min(d); %Cost-effective cut-off\n xg=linspace(0,max(table(:,1)),500);\n st=[1 mean(table(:,1)) 1]; U=[Inf max(table(:,1)) Inf];\n fo_ = fitoptions('method','NonlinearLeastSquares','Lower',L,'Upper',U,'Startpoint',st);\n fitSe = fit(table(:,1),table(:,2),ft_,fo_);\n st=[-1 mean(table(:,1)) 1]; L=[-Inf 0 0]; U=[0 max(table(:,1)) Inf];\n fo_ = fitoptions('method','NonlinearLeastSquares','Lower',L,'Upper',U,'Startpoint',st);\n fitSp=fit(table(:,1),table(:,3),ft_,fo_);\n st=[min(table(:,4)) 1 mean(table(:,1)) max(table(:,4)) 1]; L=[0 0 0 0 0]; U=[1 Inf max(table(:,1)) 1 Inf];\n ft_ = fittype('D+(A-D)/((1+(x/C)^B)^E)','dependent',{'y'},'independent',{'x'},'coefficients',{'A', 'B', 'C', 'D', 'E'});\n fo_ = fitoptions('method','NonlinearLeastSquares','Lower',L,'Upper',U,'Startpoint',st);\n fitEff=fit(table(:,1),table(:,4),ft_,fo_);\n if verbose\n H2=figure;\n set(H2,'Position',[570 402 868 420])\n hold on\n HSE = plot(xg,feval(fitSe,xg),'marker','none','linestyle','-','color','r','linewidth',2);\n HCSe=plot([table(CSe,1) table(CSe,1)],[0 1],'marker','none','linestyle','--','color','r','linewidth',2);\n HSP = plot(xg,feval(fitSp,xg),'marker','none','linestyle','-','color','g','linewidth',2);\n HCSp=plot([table(CSp,1) table(CSp,1)],[0 1],'marker','none','linestyle','--','color','g','linewidth',2);\n HEFF = plot(xg,feval(fitEff,xg),'marker','none','linestyle','-','color','b','linewidth',2);\n HCEff=plot([table(CEff,1) table(CEff,1)],[0 1],'marker','none','linestyle','--','color','b','linewidth',2);\n HCO=plot([table(CE,1) table(CE,1)],[0 1],'marker','none','linestyle','--','color','m','linewidth',2);\n hold off\n legend([HSE HCSe HSP HCSp HCO HEFF HCEff],...\n 'Sensitivity',sprintf('Max Sensitivity cutoff: %0.4f',table(CSe,1)),...\n 'Specificity',sprintf('Max Specificity cutoff: %0.4f',table(CSp,1)),...\n sprintf('Cost effective cutoff: %0.4f',table(CE,1)),...\n 'Efficiency',sprintf('Max Efficiency cutoff: %0.4f',table(CEff,1)),...\n 'Location','BestOutside')\n axis([xg(1) xg(end) 0 1.1])\n\n fprintf('1) Max Sensitivity Cut-off point= %0.2f\\n',table(CSe,1))\n fprintf('2) Max Specificity Cut-off point= %0.2f\\n',table(CSp,1))\n fprintf('3) Cost effective Cut-off point= %0.2f\\n',table(CE,1)), \n fprintf('4) Max Efficiency Cut-off point= %0.2f\\n',table(CEff,1))\n m=table([CSe CSp CE CEff],1);\n end\nelse\n table=NaN;\nend\n\n\nif nargout\n ROCout.AUC=Area; %Area under the curve\n ROCout.SE=Serror; %standard error of the area\n ROCout.ci=ci; % 95% Confidence interval\n ROCout.co=m; % cut off points\n ROCout.xr=xroc; %graphic x points\n ROCout.yr=yroc; %graphic y points\n ROCout.table=table;\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/19950-roc-curve/roc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.712232184238947, "lm_q1q2_score": 0.5477636971038919}} {"text": "function linpack_d_test25 ( )\n\n%*****************************************************************************80\n%\n%% TEST25 tests DSIFA and DSISL.\n%\n% Discussion:\n%\n% DSIFA and DSISL are for symmetric indefinite matrices.\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 = 100;\n lda = n;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST25\\n' );\n fprintf ( 1, ' For a symmetric indefinite matrix,\\n' );\n fprintf ( 1, ' DSIFA factors the matrix,\\n' );\n fprintf ( 1, ' DSISL solves a factored linear system,\\n' );\n fprintf ( 1, ' The matrix size is N = %d\\n', n );\n%\n% Assign values to the matrix A and the right hand side B.\n%\n b(1:n-1) = 0.0;\n b(n)= n + 1;\n%\n% Force B to be a column vector.\n%\n b = b';\n \n a(1:n,1:n) = 0.0;\n\n for i = 1 : n\n a(i,i) = 2.0;\n if ( i < n )\n a(i,i+1) = -1.0;\n end\n end\n%\n% Factor the matrix.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Factor the matrix.\\n' );\n \n [ a, ipvt, info ] = dsifa ( a, lda, n );\n \n if ( info ~= 0 )\n fprintf ( 1, ' Error! DSIFA 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 = dsisl ( a, lda, n, ipvt, 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_test25.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.7122321781307375, "lm_q1q2_score": 0.5477636924061887}} {"text": "function [rowAssignments,colAssignments,blocks] = findNonInteractingRowsAndColumns(A)\n% Factors a matrix into non-interacting blocks of rows and columns. Each\n% block consists of the smallest set of rows and the smallest set of\n% columns such that entries of the matrix outside the columns in the rows\n% are zero and vice-versa.\n%\n% Author: Jonathan Karr\n% Affiliation: Covert Lab, Depatment of Bioengineering, Stanford University\n% Last updated: 11/5/2008\n\n%Test Cases\n% A = [1 0 1;\n% 0 0 0;\n% 1 0 0];\n%\n% A = [0 0 1;\n% 0 1 0;\n% 1 0 0];\n%\n% A = [1 0 1;\n% 0 1 0;\n% 1 0 0];\n\n%assign rows, columns to blocks\nnBlocks=0;\nrowAssignments=zeros(size(A,1),1);\ncolAssignments=zeros(size(A,2),1);\n\n%assign empty rows and columns to single block\nfor i=1:size(A,1)\n if(isempty(find(A(i,:),1)))\n nBlocks=1;\n rowAssignments(i)=nBlocks;\n end\nend\nfor i=1:size(A,2)\n if(isempty(find(A(:,i),1)))\n nBlocks=1;\n colAssignments(i)=nBlocks;\n end\nend\n\n%assign remaining rows and columns\nfor i=1:size(A,1)\n if(rowAssignments(i)~=0); continue; end;\n nBlocks=nBlocks+1;\n rowAssignments(i)=nBlocks;\n [rowAssignments,colAssignments]=assignRecursively_row(A,i,nBlocks,rowAssignments,colAssignments);\nend\nfor i=1:size(A,2)\n if(colAssignments(i)~=0); continue; end;\n nBlocks=nBlocks+1;\n colAssignments(i)=nBlocks;\n [rowAssignments,colAssignments]=assignRecursively_col(A,i,nBlocks,rowAssignments,colAssignments);\nend\n\n%assemble blocks\nblocks=cell(nBlocks,1);\nfor i=1:nBlocks\n blocks{i}=A(rowAssignments==i,colAssignments==i);\nend\n\n% helper function\nfunction [rowAssignments,colAssignments]=assignRecursively_row(A,row,nBlocks,rowAssignments,colAssignments)\nfor i=1:size(A,2)\n if(colAssignments(i)==0 && A(row,i)~=0)\n colAssignments(i)=nBlocks;\n [rowAssignments,colAssignments]=assignRecursively_col(A,i,nBlocks,rowAssignments,colAssignments);\n end\nend\n\n%helper function\nfunction [rowAssignments,colAssignments]=assignRecursively_col(A,col,nBlocks,rowAssignments,colAssignments)\nfor i=1:size(A,1)\n if(rowAssignments(i)==0 && A(i,col)~=0)\n rowAssignments(i)=nBlocks;\n [rowAssignments,colAssignments]=assignRecursively_row(A,i,nBlocks,rowAssignments,colAssignments);\n end\nend", "meta": {"author": "CovertLab", "repo": "WholeCell", "sha": "6cdee6b355aa0f5ff2953b1ab356eea049108e07", "save_path": "github-repos/MATLAB/CovertLab-WholeCell", "path": "github-repos/MATLAB/CovertLab-WholeCell/WholeCell-6cdee6b355aa0f5ff2953b1ab356eea049108e07/src/+edu/+stanford/+covert/+util/findNonInteractingRowsAndColumns.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461390043208003, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.5477552085134263}} {"text": "function g = diskfun(f, varargin)\n% DISKFUN returns a diskfun representing the BALLFUN F evaluated at a\n% planar slice.\n%\n% G = DISKFUN(F) is the slice of F in the XY plane. \n%\n% G = DISKFUN(F, 'x', C) is the slice of F in the plane X = C,\n% scaled to the unit disk; G is a diskfun.\n%\n% G = DISKFUN(F, 'y', C) is the slice of F in the plane Y = C,\n% scaled to the unit disk; G is a diskfun.\n%\n% G = DISKFUN(F, 'z', C) is the slice of F in the plane Z = C,\n% scaled to the unit disk; G is a diskfun.\n%\n% G = DISKFUN(F, PHI, THETA, PSI, C) rotates F using Euler angles phi, theta, \n% and psi with the ZXZ convention and then evaluates it in the plane Z = C\n% (C = 0 by default)\n%\n% % See also BALLFUN/SPHEREFUN.\n\n\n% Copyright 2019 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\nif isempty( f )\n g = diskfun();\n return\nend\n\n% Parse user inputs to get the Euler angles\n[phi, theta, psi, c] = parseInputs(varargin{:});\n\n% Throw an error if c>1 or c<1\nif abs(c) > 1\n error('CHEBFUN:BALLFUN:diskfun:sliceNotInBall',...\n ['The specified slice does not lie in unit ball.']);\nend\n\n% Rotate f using Euler angles phi, theta and psi\nf = rotate(f, phi, theta, psi);\n\n% Get the size\n[m,n,~] = size(f);\n\n% If n is odd, make it even\nm = m + 1-mod(m,2);\nn = n + mod(n,2);\n\n% Evaluation points in [c, 1]\nrho = chebpts(m)*sqrt(1-c^2);\nrho = rho(ceil(m/2):end);\n\n% Evaluation points in [-pi,pi)\nlambda = pi*trigpts(n);\n\n% Build the grid and evaluate at the plane Z = C\nr = sqrt(rho.^2+c^2);\n\ntheta = atan2(rho,c);\nG = zeros(length(r),n);\nfor i = 1:length(r)\n G(i,:) = fevalm(f, r(i), lambda, theta(i));\nend\n\n% Return the diskfun\ng = diskfun(real(G));\nend\n\nfunction [phi, theta, psi, c] = parseInputs(varargin)\n% Parse user inputs to DISKFUN.\nc = 0;\nif nargin == 0\n phi = 0;\n theta = 0;\n psi = 0;\nelseif ischar(varargin{1})\n phi = 0;\n if strcmp(varargin{1},'x')\n theta = -pi/2;\n psi = pi/2;\n % Evaluate at Y-Z plane\n elseif strcmp(varargin{1},'y')\n % Evaluate at X-Z plane\n theta = -pi/2;\n psi = 0;\n elseif strcmp(varargin{1},'z')\n % Evaluate at X-Y plane\n theta = 0;\n psi = 0;\n end\n if nargin >= 2\n c = varargin{2}; \n end\nelse\n phi = varargin{1};\n theta = 0;\n psi = 0;\n if nargin >= 2\n theta = varargin{2};\n end\n if nargin >= 3\n psi = varargin{3};\n end\n if nargin >= 4\n c = varargin{4};\n end\nend\nend", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/@ballfun/diskfun.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872243177517, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.5476266414796311}} {"text": "function [score] = EMRtest(x,model)\n% [score] = EMRtest(x,model): Efficient Manifold Ranking for out-of-sample\n% retrieval\n% Input:\n% - x: the query point, row vector.\n% - model: the model learned by EMR\n% \n% Output:\n% - score: the ranking scores for each point in the database\n%\n% Usage:\n%\n% See: http://www.zjucadcg.cn/dengcai/Data/Examples.html#EMR\n%\n%Reference:\n%\n%\t Bin Xu, Jiajun Bu, Chun Chen, Deng Cai, Xiaofei He, Wei Liu, Jiebo\n%\t Luo, \"Efficient Manifold Ranking for Image Retrieval\",in Proceeding of\n%\t the 34th International ACM SIGIR Conference on Research and\n%\t Development in Information Retrieval (SIGIR), 2011, pp. 525-534. \n%\n% version 2.0 --Feb./2012 \n% version 1.0 --Sep./2010 \n%\n% Written by Bin Xu (binxu986 AT gmail.com)\n% Deng Cai (dengcai AT gmail.com)\n\n\n\n\nr = model.r;\na = model.a;\np = size(model.landmarks,1);\n\n\n% Z construction\nD = EuDist2(x,model.landmarks);\n[dump,idx] = sort(D);\ndump = dump(1:r)/dump(r);\ndump = 0.75 * (1 - dump.^2);\nz = sparse(idx(1:r),1,dump,p,1);\n\nZ = [model.Z z];\nZ = Z';\n\nnSmp =size(Z,1);\n\n\ny0 = zeros(nSmp,1);\ny0(end) = 1;\n\n% Efficient Ranking\nfeaSum = full(sum(Z,1));\nD = Z*feaSum';\nD = max(D, 1e-12);\nD = D.^(-.5);\nH = spdiags(D,0,nSmp,nSmp)*Z;\n\nC = speye(p);\nA = H'*H-(1/a)*C;\n\ntmp = H'*y0;\ntmp = A\\tmp;\nscore = y0 - H*tmp;\n\nscore(end) = [];\n\n\n\n", "meta": {"author": "ZJULearning", "repo": "MatlabFunc", "sha": "97504df0f597c1980ab76ddc0c9c5d669043c6c9", "save_path": "github-repos/MATLAB/ZJULearning-MatlabFunc", "path": "github-repos/MATLAB/ZJULearning-MatlabFunc/MatlabFunc-97504df0f597c1980ab76ddc0c9c5d669043c6c9/Ranking/EMRtest.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711832583696, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5475727760449688}} {"text": "function [P3, S_bar, V, Z, RO, Tr] = random_nr_motion(T, J, K, state)\n% [P3, S_bar, V, Z, RO, Tr] = random_nr_motion(T, J, K, state)\n%\n% INPUT:\n%\n% T - number of frames\n% J - number of points\n% K - number of deformation basis\n%\n% OUTPUT:\n%\n% P3 - (3*T) x J 3D-motion matrix: P3([t t+T t+2*T],:) contains the 3D coordinates of the J points at time t\n% S_bar - shape average: 3 x J matrix\n% V - deformation shapes: (3*K) x J matrix ( V((n-1)*3+[1:3],:) contains the n-th deformation basis )\n% Z - deformation weights: T x K matrix\n% RO - rotation: cell array ( RO{t} gives the rotation matrix at time t )\n% Tr - translation: T x 2 matrix\n\nrand('state', state);\nrandn('state', state);\n\nS_bar = rand(3, J);\n\n[q,r] = qr(rand(3*J));\n\nV = zeros(3*K, J);\nfor kk=1:K,\n V(1+(kk-1)*3:3*kk, :) = reshape(q(:,kk), 3, J);\nend\n\nZ = randn(T,K);\nTr = randn(T,2);\n\na = (rand(T,1)-0.5)*2*pi;\nb = (rand(T,1)-0.5)*2*pi;\nc = (rand(T,1)-0.5)*2*pi;\nP3 = zeros(3*T, J);\nfor t=1:T,\n R1 = [1 0 0; 0 cos(a(t)) -sin(a(t)); 0 sin(a(t)) cos(a(t))];\n R2 = [cos(b(t)) 0 sin(b(t)); 0 1 0; -sin(b(t)) 0 cos(b(t))];\n R3 = [cos(c(t)) -sin(c(t)) 0; sin(c(t)) cos(c(t)) 0; 0 0 1];\n \n RO{t} = R1*R2*R3;\n \n Sdef = S_bar;\n for kk = 1:K,\n Sdef = Sdef+Z(t,kk)*V((kk-1)*3+[1:3],:);\n end; \n Sdef = RO{t}*Sdef +[Tr(t,:)'; 0]*ones(1, J);\n \n P3([t t+T t+2*T], :) = Sdef;\nend\n", "meta": {"author": "TadasBaltrusaitis", "repo": "OpenFace", "sha": "3d4b5cf8d96138be42bed229447f36cbb09a5a29", "save_path": "github-repos/MATLAB/TadasBaltrusaitis-OpenFace", "path": "github-repos/MATLAB/TadasBaltrusaitis-OpenFace/OpenFace-3d4b5cf8d96138be42bed229447f36cbb09a5a29/model_training/pdm_generation/nrsfm-em/random_nr_motion.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711604559846, "lm_q2_score": 0.6442250996557036, "lm_q1q2_score": 0.5475727555492308}} {"text": "function [texture structure] = structure_texture_decomposition_rof(im, theta, nIters, alp)\n%\n% Decompose the input IMAGE into structure and texture parts using the\n% Rudin-Osher-Fatemi method. The final output is a linear combination \n% of the decomposed texture and the structure parts.\n%\n% According to Wedel etal \"An Improved Algorithm for TV-L1 optical flow\"\n% equations (8)-(10)\n%\n% Test code\n% [im1, im2, tu, tv] = read_image_flow_tune_para(4,0);\n% [t1 s1] = structure_texture_decomposition_rof(im1); \n% [t2 s2] = structure_texture_decomposition_rof(im2); \n% indx = ~isnan(tu) | ~isnan(tv);\n% uv = cat(3, tu, tv);\n% uv(isnan(uv)) = 0;\n% figure; imshow(-abs(partial_deriv(cat(3,im1, im2), uv)).*indx, []); title('original');\n% figure; imshow(-abs(partial_deriv(cat(3,s1, s2), uv)).*indx, []); title('structure');\n% figure; imshow(-abs(partial_deriv(cat(3,t1, t2), uv)).*indx, []); title('texture');\n% tmp = partial_deriv(cat(3,t1, t2, uv);\n% figure; imshow(t1, []); figure; imshow(s1, []);\n\n% Author: Deqing Sun, Department of Computer Science, Brown University\n% Contact: dqsun@cs.brown.edu\n% $Date: 2009 $\n%\n% Copyright 2009-2010, Brown University, Providence, RI. USA\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\nif nargin == 1\n theta = 1/8; \n nIters = 100;\n alp = 0.95; % alp = 0.75 results in 4:1\nend;\n\n% Rescale the input image to [-1 1]\nIM = scale_image(im, -1,1);\n\n% Backup orginal images\nim = IM; \n\n% stepsize\ndelta = 1.0/(4.0*theta);\n\nfor iIm = 1:size(im,3)\n\n % Initialize dual variable p to be 0\n p = zeros([size(im,1) size(im,2) 2]);\n \n % Gradient descend \n I = squeeze(IM(:,:,iIm));\n \n for iter = 1:nIters\n \n % Compute divergence eqn(8) \n div_p = imfilter(p(:,:,1), [-1 1 0], 'corr', 0)+ ...\n imfilter(p(:,:,2), [-1 1 0]', 'corr', 0); \n \n I_x = imfilter(I+theta*div_p, [-1 1], 'replicate');\n \n I_y = imfilter(I+theta*div_p, [-1 1]', 'replicate');\n \n % Update dual variable eqn(9)\n p(:,:,1) = p(:,:,1) + delta*(I_x);\n p(:,:,2) = p(:,:,2) + delta*(I_y);\n \n % Reproject to |p| <= 1 eqn(10) \n reprojection = max(1.0, sqrt(p(:,:,1).^2 + p(:,:,2).^2));\n p(:,:,1) = p(:,:,1)./reprojection;\n p(:,:,2) = p(:,:,2)./reprojection;\n \n end\n \n % compute divergence \n div_p = imfilter(p(:,:,1), [-1 1 0], 'corr', 0)+ ...\n imfilter(p(:,:,2), [-1 1 0]', 'corr', 0);\n \n % compute structure component\n IM(:,:,iIm) = I + theta*div_p;\n \nend;\n\n\ntexture = squeeze(scale_image(im - alp*IM, 0, 255));\n\nif nargout == 2\n structure = squeeze(scale_image(IM, 0, 255)); %(u-min(u(:)))/(max(u(:))-min(u(:))) - 1;\nend;", "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/structure_texture_decomposition_rof.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303285397349, "lm_q2_score": 0.6926419894793246, "lm_q1q2_score": 0.5475544995035061}} {"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 = sprice_2(a, b, r, n, f, k, t,cp)\n% sabr prices using an admissible region kl <= k <= ku where sabr is used\n% for 0 <= k <= kl \n% we use a put pricing function f(x) = K^mu exp(a + bx + cx^2)\n% for ku < k < +infty \n% we use a call pricing function f(x) = K^(-nu) exp(a + bx^(-1) + cx(-2)\neps = 1e-004;\n\n%find index where density is positive\ns = @(x) psabr(a, b, r, n, f, x, t);\nindex = find(s(k)<0,1,'last');\n\nif isempty(index)\n kl = .25 *f;\nelse \n kl = max(.25 * f,k(index+1));% lower strike level (free parameter) \nend\n\n%kl = .5 * f; % lower strike level\n\ns = @(x) sprice(a, b, r, n, f, x, t,-1); % sabr price (-1) for puts\n\ns1 = s(kl-eps); % for calc of derivatives\ns2 = s(kl); % for calc of derivatives\ns3 = s(kl+eps); % for calc of derivatives\n\nV1 = log(s2); % log put price\n\nU2 = (s3-s1)/(2*eps); % derivative of the price\nV2 = U2/s2; % derivative of the log price\n\nU3 = (s3-2*s2+s1)/eps^2; % second derivative of the price\nV3 = U3/s2 - V2^2; % second derivative of the log price\n\n% fix mu and solve \n% V1 = mu log kl + a + b kl + c kl^2\n% V2 = mu / kl + b + 2c kl\n% V3 = - mu / kl^2 + 2c\n\nmu = -V3*kl^2; bl = V2 - mu / kl; al = V1 - mu *log(kl) - bl * kl;\n\n\nku = 15 * f; % upper strike level\ns = @(x) sprice(a, b, r, n, f, x, t,1); % sabr price (1) for calls\ns1 = s(ku-eps); % for calc of derivatives\ns2 = s(ku); % for calc of derivatives\ns3 = s(ku+eps); % for calc of derivatives\n\nV1 = log(s2); % log call price\n\nU2 = (s3-s1)/(2*eps); % derivative of the price\nV2 = U2/s2; % derivative of the log price \n\nU3 = (s3-2*s2+s1)/eps^2; % second derivative of the price\nV3 = U3/s2 - (U2/s2)^2; % second derivative f the price\n\n% fix nu and solve\n% V1 = -nu log ku + a + b/ku + c/ku^2\n% V2 = -nu / ku - b / ku^2 - 2c/ku^3 \n% V3 = nu / ku^2 + 2 b / ku^3 - 6 c / ku^4\n\nnu = 2; cu = (-1.5*nu / ku + .5*V3 * ku - V2)*ku^3/5; \nbu = -ku^2*(V2 + nu/ku +2*cu/ku^3); \nau = V1 + nu * log(ku) - bu / ku - cu / ku^2; \n\n\n% the sabr volatility for the admissible region kl <= k <= ku\nsigma = svol(a,b,r,n,f,k((kl<=k)&(k<=ku)),t);\n\n d1= (log(f./k((kl<=k)&(k<=ku)))+(0.5*t*sigma.*sigma))./(sqrt(t)*sigma); % BS d1 with sabr vol\n d2= (log(f./k((kl<=k)&(k<=ku)))-(0.5*t*sigma.*sigma))./(sqrt(t)*sigma); % BS d2 with sabr vol\n\nif cp==1\n yu = k(k>ku).^(-nu) .* exp(au+bu./k(k>ku)+cu./k(k>ku).^2); % call price ku < k < +infty\n ym = f.*normcdf( d1,0,1)-k((kl<=k)&(k<=ku)).*normcdf( d2,0,1); % admissible region kl <= k <= ku\n yl = k(kku).^(-nu) .* exp(au+bu./k(k>ku)+cu./k(k>ku).^2) - f + k(k>ku);% put prices using call-out parity ku < k < +infty\nend\n\ny = [yl ym yu]; % output\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/sprice_2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.6926419894793246, "lm_q1q2_score": 0.547554492667088}} {"text": "function [transParameters,nu,lambda]=igarch_transform(parameters,p,q,errorType,constant)\n% IGARCH(P,Q) parameter transformation. Used to map parameters from a IGARCH\n% process to the positive unit simplex. Used in the estimation of IGARCH.\n%\n% USAGE:\n% [TRANSPARAMETERS,NU,LAMBDA]=igarch_transform(PARAMETERS,P,Q,ERRORTYPE,CONSTANT)\n%\n% INPUTS:\n% PARAMETERS - Column parameter vector\n% P - Positive, scalar integer representing the number of\n% symmetric innovations\n% Q - Non-negative, scalar integer representing the number\n% of lags of conditional variance (0 for ARCH)\n% ERRORTYPE - One of:\n% 1 - Gaussian Innovations\n% 2 - T-distributed errors\n% 3 - Generalized Error Distribution\n% 4 - Skewed T distribution\n% CONSTANT - 1 if model includes a constant, 0 otherwise\n%\n% OUTPUTS:\n% TRANSPARAMETERS - A CONSTANT+p+q-1 column vector of transformed parameters corresponding to\n% [omega,alpha(1),...,alpha(p) beta1 ... beta(q-1)]'\n% where the final beta has been excluded\n% NU - Distribution kurtosis parameter, empty if not applicable\n% LAMBDA - Distribution asymmetry parameter, empty if not applicable\n%\n% COMMENTS:\n% Input parameters must satisfy:\n% (1) omega > 0\n% (2) alpha(i) >= 0 for i = 1,2,...,p\n% (3) beta(i) >= 0 for i = 1,2,...,q\n% (4) sum(alpha(i) + beta(j)) = 1 for i = 1,2,...p and j = 1,2,...q\n% (5) nu>2 of Students T and nu>1 for GED\n% (6) -.990\n%nu>2.01 or 1.01\n%-.990\n% gamma>-alpha(i)\n% beta>0\n% sum(alpha)+0.5sum(gamma)+sum(beta)<1\n\nnu=[];\nlambda=[];\n\n%Handle nu, >2.01 in the case of a T, 1.01=UB\n error('These do not conform to the necessary set of restrictions to be transformed.')\nend\n\n%Finally, must be certain that none of the parameters are exactly zero, and\n%that the alpha2+gamma2>0\nalpha(alpha==0)=1e-8;\nbeta(beta==0)=1e-8;\n\n%Finally, up the upper bound a tiny bit\nUB=UB+1e-8*(p+q);\n\n%Set the scale\nscale=UB;\n%Initialze the transformed alpha\ntalpha=alpha;\nfor i=1:p\n %Scale the alpha\n talpha(i)=alpha(i)./scale;\n %Use an inverse logistic\n talpha(i)=log(talpha(i)./(1-talpha(i)));\n %Update the scale\n scale=scale-alpha(i);\nend\n\nif q>1\n %Initialize the beta\n tbeta=beta;\n %Iterate over betas\n for i=1:(q-1)\n %Scale the betas\n tbeta(i)=tbeta(i)./scale;\n %Use an inverse logistic\n tbeta(i)=log(tbeta(i)./(1-tbeta(i)));\n %Update the scale\n scale=scale-beta(i);\n end\nelse\n tbeta = [];\nend\n\n%Regroup the parameters\ntransParameters=[tomega;talpha;tbeta];\n", "meta": {"author": "bashtage", "repo": "mfe-toolbox", "sha": "9622b6c546bc6d649fd9bf0a36a7fcd53872e04a", "save_path": "github-repos/MATLAB/bashtage-mfe-toolbox", "path": "github-repos/MATLAB/bashtage-mfe-toolbox/mfe-toolbox-9622b6c546bc6d649fd9bf0a36a7fcd53872e04a/univariate/igarch_transform.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.6859494550081926, "lm_q1q2_score": 0.5475157851852385}} {"text": "function [eta Heta inner_it stop_tCG storedb] ...\n = tCG(problem, x, grad, eta, Delta, options, storedb)\n% tCG - Truncated (Steihaug-Toint) Conjugate-Gradient method\n% minimize + .5*\n% subject to <= Delta^2\n\n% This file is part of Manopt: www.manopt.org.\n% This code is an adaptation to Manopt of the original GenRTR code:\n% RTR - Riemannian Trust-Region\n% (c) 2004-2007, P.-A. Absil, C. G. Baker, K. A. Gallivan\n% Florida State University\n% School of Computational Science\n% (http://www.math.fsu.edu/~cbaker/GenRTR/?page=download)\n% See accompanying license file.\n% The adaptation was executed by Nicolas Boumal.\n% Change log:\n% NB Feb. 12, 2013:\n% We do not project r back to the tangent space anymore: it was not\n% necessary, and as of Manopt 1.0.1, the proj operator does not\n% coincide with this notion anymore.\n% NB April 3, 2013:\n% tCG now also returns Heta, the Hessian at x along eta. Additional\n% esthetic modifications.\n% NB Dec. 2, 2013:\n% If options.useRand is activated, we now make sure the preconditio-\n% ner is not used, as was originally intended in GenRTR. In time, we\n% may want to investigate whether useRand can be modifed to work well\n% with preconditioning too.\n% NB Jan. 9, 2014:\n% Now checking explicitly for model decrease at each iteration. The\n% first iteration is a Cauchy point, which necessarily realizes a\n% decrease of the model cost. If a model increase is witnessed\n% (which is theoretically impossible if a linear operator is used for\n% the Hessian approximation), then we return the previous eta. This\n% ensures we always achieve at least the Cauchy decrease, which\n% should be sufficient for convergence.\n\n\n% All terms involving the trust-region radius will use an inner product\n% w.r.t. the preconditioner; this is because the iterates grow in\n% length w.r.t. the preconditioner, guaranteeing that we will not\n% re-enter the trust-region.\n%\n% The following recurrences for Prec-based norms and inner\n% products come from [CGT2000], pg. 205, first edition.\n% Below, P is the preconditioner.\n%\n% = \n% beta_k-1 * ( + alpha_k-1 |delta_k-1|^2_P )\n% |delta_k|^2_P = + beta_k-1^2 |delta_k-1|^2_P\n%\n% therefore, we need to keep track of\n% 1) |delta_k|^2_P\n% 2) = _P\n% 3) |eta_k |^2_P\n%\n% initial values are given by:\n% |delta_0|_P = \n% |eta_0|_P = 0\n% _P = 0\n% because we take eta_0 = 0 (if useRand = false).\n%\n% [CGT2000] Conn, Gould and Toint: Trust-region methods, 2000.\n\ninner = problem.M.inner;\n\ntheta = options.theta;\nkappa = options.kappa;\n\nif ~options.useRand % and therefore, eta == 0\n Heta = problem.M.zerovec(x);\n r = grad;\n e_Pe = 0;\nelse % and therefore, no preconditioner\n % eta (presumably) ~= 0 was provided by the caller\n [Heta storedb] = getHessian(problem, x, eta, storedb);\n r = problem.M.lincomb(x, 1, grad, 1, Heta);\n e_Pe = inner(x, eta, eta);\nend\nr_r = inner(x, r, r);\nnorm_r = sqrt(r_r);\nnorm_r0 = norm_r;\n\n% precondition the residual\nif ~options.useRand\n [z storedb] = getPrecon(problem, x, r, storedb);\nelse\n z = r;\nend\n\n% compute z'*r\nz_r = inner(x, z, r);\nd_Pd = z_r;\n\n% Initial search direction\ndelta = problem.M.lincomb(x, -1, z);\nif ~options.useRand % and therefore, eta == 0\n e_Pd = 0;\nelse % and therefore, no preconditioner\n e_Pd = inner(x, eta, delta);\nend\n\n% If the Hessian or a linear Hessian approximation is in use, it is\n% theoretically guaranteed that the model value decreases monotonically\n% with each iteration of tCG. Hence, there is no need to monitor the model\n% value. But, when a nonlinear Hessian approximation is used (such as the\n% built-in finite-difference approximation for example), the model may\n% increase. It is then important to terminate the tCG iterations and return\n% the previous (the best-so-far) iterate. The variable below will hold the\n% model value.\nmodel_fun = @(eta, Heta) inner(x, grad, eta) + .5*inner(x, eta, Heta);\nif ~options.useRand\n model_value = 0;\nelse\n model_value = model_fun(eta, Heta);\nend\n\n% Pre-assume termination b/c j == end\nstop_tCG = 5;\n\n% Begin inner/tCG loop\nj = 0;\nfor j = 1 : options.maxinner\n \n [Hdelta storedb] = getHessian(problem, x, delta, storedb);\n \n % Compute curvature\n d_Hd = inner(x, delta, Hdelta);\n \n \n alpha = z_r/d_Hd;\n % _P =\n % _P + 2*alpha*_P + alpha*alpha*_P\n e_Pe_new = e_Pe + 2.0*alpha*e_Pd + alpha*alpha*d_Pd;\n \n if options.debug > 2,\n fprintf('DBG: (r,r) : %e\\n',r_r);\n fprintf('DBG: (d,Hd) : %e\\n',d_Hd);\n fprintf('DBG: alpha : %e\\n',alpha);\n end\n \n % Check against negative curvature and trust-region radius violation.\n % If either condition triggers, we bail out.\n if d_Hd <= 0 || e_Pe_new >= Delta^2,\n % want\n % ee = _prec,x\n % ed = _prec,x\n % dd = _prec,x\n tau = (-e_Pd + sqrt(e_Pd*e_Pd + d_Pd*(Delta^2-e_Pe))) / d_Pd;\n if options.debug > 2,\n fprintf('DBG: tau : %e\\n', tau);\n end\n eta = problem.M.lincomb(x, 1, eta, tau, delta);\n Heta = problem.M.lincomb(x, 1, Heta, tau, Hdelta);\n if d_Hd <= 0,\n stop_tCG = 1; % negative curvature\n else\n stop_tCG = 2; % exceeded trust region\n end\n break;\n end\n \n % No negative curvature and eta_prop inside TR: accept it\n e_Pe = e_Pe_new;\n new_eta = problem.M.lincomb(x, 1, eta, alpha, delta);\n new_Heta = problem.M.lincomb(x, 1, Heta, alpha, Hdelta);\n \n % Verify that the model cost decreased in going from eta to new_eta. If\n % the cost increased (which can only occur if the Hessian approximation\n % is nonlinear), then we return the previous eta (which necessarily is\n % the best reached so far, according to the model cost). Otherwise, we\n % accept the new eta and go on.\n new_model_value = model_fun(new_eta, new_Heta);\n if new_model_value > model_value\n stop_tCG = 6;\n break;\n end\n \n eta = new_eta;\n Heta = new_Heta;\n \n % Update the residual\n r = problem.M.lincomb(x, 1, r, alpha, Hdelta);\n \n % Compute new norm of r\n r_r = inner(x, r, r);\n norm_r = sqrt(r_r);\n \n % Check kappa/theta stopping criterion\n if j >= options.mininner && norm_r <= norm_r0*min(norm_r0^theta, kappa)\n % Residual is small enough to quit\n if kappa < norm_r0^theta,\n stop_tCG = 3; % linear convergence\n else\n stop_tCG = 4; % superlinear convergence\n end\n break;\n end\n \n % Precondition the residual\n if ~options.useRand\n [z storedb] = getPrecon(problem, x, r, storedb);\n else\n z = r;\n end\n \n % Save the old z'*r\n zold_rold = z_r;\n % Compute new z'*r\n z_r = inner(x, z, r);\n \n % Compute new search direction\n beta = z_r/zold_rold;\n delta = problem.M.lincomb(x, -1, z, beta, delta);\n \n % Update new P-norms and P-dots [CGT2000, eq. 7.5.6 & 7.5.7]\n e_Pd = beta*(e_Pd + alpha*d_Pd);\n d_Pd = z_r + beta*beta*d_Pd;\n \nend % of tCG loop\ninner_it = j;\n\nend\n", "meta": {"author": "andrewssobral", "repo": "lrslibrary", "sha": "06d457349cb5f1fc56a583cd61af9f1d5150e3a1", "save_path": "github-repos/MATLAB/andrewssobral-lrslibrary", "path": "github-repos/MATLAB/andrewssobral-lrslibrary/lrslibrary-06d457349cb5f1fc56a583cd61af9f1d5150e3a1/libs/manopt/manopt/solvers/trustregions/tCG.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.6859494550081926, "lm_q1q2_score": 0.5475157851852385}} {"text": "function g = getGroupOverlap(row, col)\n\n\n N = row*col;\n\n g = sparse(zeros(N,1));\n g = diag(g);\n \n \n \n %% build overlapping group\n \n % top let corner group\n \n g(1, 1 ) = 1;\n g(1, 2 ) = 1;\n g(1, 1+row ) = 1;\n g(1, 2+row ) = 1;\n \n % bottom let corner group \n \n g(row, row-1 ) = 1;\n g(row, row ) = 1;\n g(row, row-1+row ) = 1;\n g(row, row+row ) = 1;\n \n % top right corner group\n \n g((col-1)*row+1, (col-1)*row+1 ) = 1;\n g((col-1)*row+1, (col-2)*row+1 ) = 1;\n g((col-1)*row+1, (col-1)*row+2 ) = 1;\n g((col-1)*row+1, (col-2)*row+2 ) = 1;\n \n % bottom right corner group\n \n g((col-1)*row+row , (col-1)*row+row-1 ) = 1;\n g((col-1)*row+row , (col-2)*row+row-1 ) = 1;\n g((col-1)*row+row , (col-1)*row+row ) = 1;\n g((col-1)*row+row , (col-2)*row+row ) = 1;\n \n \n \n \n % boundary group\n \n for i=2:col-1\n % top row rgoup\n \n j = 1; \n \n g( (i-1)*row+j , (i-2)*row+j ) = 1;\n g( (i-1)*row+j , (i-2)*row+j+1 ) = 1;\n \n g( (i-1)*row+j , (i-1)*row+j ) = 1;\n g( (i-1)*row+j , (i-1)*row+j+1 ) = 1; \n \n g( (i-1)*row+j , i*row+j ) = 1;\n g( (i-1)*row+j , i*row+j+1 ) = 1;\n\n % bottom row group\n \n j = row;\n \n g( (i-1)*row+j , (i-2)*row+j-1 ) = 1;\n g( (i-1)*row+j , (i-2)*row+j ) = 1;\n \n g( (i-1)*row+j , (i-1)*row+j-1 ) = 1;\n g( (i-1)*row+j , (i-1)*row+j ) = 1;\n \n g( (i-1)*row+j , i*row+j-1 ) = 1;\n g( (i-1)*row+j , i*row+j ) = 1;\n \n \n \n end\n \n for j=2:row-1\n % left column rgoup\n \n \n i=1;\n \n g( (i-1)*row+j , (i-1)*row+j-1 ) = 1;\n g( (i-1)*row+j , (i-1)*row+j ) = 1;\n g( (i-1)*row+j , (i-1)*row+j+1 ) = 1; \n g( (i-1)*row+j , i*row+j-1 ) = 1;\n g( (i-1)*row+j , i*row+j ) = 1;\n g( (i-1)*row+j , i*row+j+1 ) = 1;\n\n % right column group\n \n\n i=col;\n \n \n g( (i-1)*row+j , (i-2)*row+j-1 ) = 1;\n g( (i-1)*row+j , (i-2)*row+j ) = 1;\n g( (i-1)*row+j , (i-2)*row+j+1 ) = 1;\n g( (i-1)*row+j , (i-1)*row+j-1 ) = 1;\n g( (i-1)*row+j , (i-1)*row+j ) = 1;\n g( (i-1)*row+j , (i-1)*row+j+1 ) = 1; \n \n end\n \n for i=2:col-1 \n for j=2:row-1 \n \n \n g( (i-1)*row+j , (i-2)*row+j-1 ) = 1;\n g( (i-1)*row+j , (i-2)*row+j ) = 1;\n g( (i-1)*row+j , (i-2)*row+j+1 ) = 1;\n g( (i-1)*row+j , (i-1)*row+j-1 ) = 1;\n g( (i-1)*row+j , (i-1)*row+j ) = 1;\n g( (i-1)*row+j , (i-1)*row+j+1 ) = 1; \n g( (i-1)*row+j , i*row+j-1 ) = 1;\n g( (i-1)*row+j , i*row+j ) = 1;\n g( (i-1)*row+j , i*row+j+1 ) = 1; \n\n end\n end\n \n\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/st/GOSUS/getGroupOverlap.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.782662489091802, "lm_q2_score": 0.6992544147913994, "lm_q1q2_score": 0.547280200789068}} {"text": "function Y = symmetrize(X,grps)\n%SYMMETRIZE Symmetrize a tensor X in specified modes.\n%\n% Y = symmetrize(X) will symmetrize a tensor X with respect to all\n% modes so that Y is symmetric with respect to any permutation of\n% indices.\n%\n% Y = symmetrize(X,MODES) will symmetrize a tensor X with respect to the\n% modes specified by the vector MODES of mode indices. The second\n% argument may alternatively be a cell array of vectors of modes to,\n% e.g., specify that it should be symmetric with respect to mode [1 3] as\n% well as [2 4].\n%\n% See also TENSOR, TENSOR/ISSYMMETRIC.\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%T. Kolda, April 2011\nn = ndims(X);\nsz = size(X);\n\n% Check that grps exists; if not, create it.\nif ~exist('grps','var')\n grps = {1:n};\nend\n\n% Check that grps is a cell array.\nif ~iscell(grps)\n grps = {grps};\nend\n\nif ~isnumeric(grps{1})\n error('MODES must be numeric');\nend\n\n% Check tensor dimensions for compatibility with symmetrization\nngrps = length(grps);\nfor i = 1:ngrps\n dims = grps{i};\n for j = dims(2:end)\n if sz(j) ~= sz(dims(1))\n error('Dimension mismatch for symmetrization');\n end\n end\nend\n\n% Check for no overlap in the sets\nfor i = 1:ngrps\n for j = i+1:ngrps\n if ~isempty(intersect(grps{i},grps{j}))\n error('Cannot haver overlapping symmetries');\n end\n end\nend\n\n% Create the combinations for each symmetrized subset\ncombos = cell(ngrps,1);\nfor i = 1:ngrps\n combos{i} = perms(grps{i}); \nend\n\n% Create all the permuations to be averaged\ntotal_perms = prod(cellfun(@length,combos));\nsym_perms = repmat(1:n, total_perms, 1);\nfor i = 1:ngrps\n ntimes = prod(cellfun(@length,combos(1:i-1))); \n ncopies = prod(cellfun(@length,combos(i+1:end))); \n nelems = length(combos{i});\n \n idx = 1;\n for j = 1:ntimes\n for k = 1:nelems\n for l = 1:ncopies\n sym_perms(idx,grps{i}) = combos{i}(k,:);\n idx = idx + 1;\n end\n end\n end\nend\n\n% Create an average tensor\nY = tenzeros(size(X));\nfor i = 1:total_perms\n Y = Y + permute(X,sym_perms(i,:)); \nend\nY = Y / total_perms;\n\n% It's not *exactly* symmetric due to oddities in differently ordered\n% summations and so on, so let's fix that.\n% Idea borrowed from Gergana Bounova:\n% http://www.mit.edu/~gerganaa/downloads/matlab/symmetrize.m\nfor i = 1:total_perms\n Z = permute(Y,sym_perms(i,:));\n Y.data(:) = max(Y.data(:),Z.data(:)); \nend\n\n\n\n \n\n\n\n", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/分类算法/DEEP-TENSOR-FACTORIZATION-FOR-HYPERSPECTRAL-IMAGE-CLASSIFICATION-master/code/tensor_toolbox_2.6/@tensor/symmetrize.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426303, "lm_q2_score": 0.7090191337850932, "lm_q1q2_score": 0.5472518008133372}} {"text": "% RANSACFITFUNDMATRIX - fits fundamental matrix using RANSAC\n%\n% Usage: [F, inliers] = ransacfitfundmatrix(x1, x2, t)\n%\n% Arguments:\n% x1 - 2xN or 3xN set of homogeneous points. If the data is\n% 2xN it is assumed the homogeneous scale factor is 1.\n% x2 - 2xN or 3xN set of homogeneous points such that x1<->x2.\n% t - The distance threshold between data point and the model\n% used to decide whether a point is an inlier or not. \n% Note that point coordinates are normalised to that their\n% mean distance from the origin is sqrt(2). The value of\n% t should be set relative to this, say in the range \n% 0.001 - 0.01 \n%\n% Note that it is assumed that the matching of x1 and x2 are putative and it\n% is expected that a percentage of matches will be wrong.\n%\n% Returns:\n% F - The 3x3 fundamental matrix such that x2'Fx1 = 0.\n% inliers - An array of indices of the elements of x1, x2 that were\n% the inliers for the best model.\n%\n% See Also: RANSAC, FUNDMATRIX\n\n% Copyright (c) 2004-2005 Peter Kovesi\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% February 2004 Original version\n% August 2005 Distance error function changed to match changes in RANSAC\n\nfunction [F, inliers] = ransacfitfundmatrix(x1, x2, t, feedback)\n\n if ~all(size(x1)==size(x2))\n error('Data sets x1 and x2 must have the same dimension');\n end\n \n if nargin == 3\n\tfeedback = 0;\n end\n \n [rows,npts] = size(x1);\n if rows~=2 & rows~=3\n error('x1 and x2 must have 2 or 3 rows');\n end\n \n if rows == 2 % Pad data with homogeneous scale factor of 1\n x1 = [x1; ones(1,npts)];\n x2 = [x2; ones(1,npts)]; \n end\n \n % Normalise each set of points so that the origin is at centroid and\n % mean distance from origin is sqrt(2). normalise2dpts also ensures the\n % scale parameter is 1. Note that 'fundmatrix' will also call\n % 'normalise2dpts' but the code in 'ransac' that calls the distance\n % function will not - so it is best that we normalise beforehand.\n [x1, T1] = normalise2dpts(x1);\n [x2, T2] = normalise2dpts(x2);\n\n s = 8; % Number of points needed to fit a fundamental matrix. Note that\n % only 7 are needed but the function 'fundmatrix' only\n % implements the 8-point solution.\n \n fittingfn = @fundmatrix;\n distfn = @funddist;\n degenfn = @isdegenerate;\n % x1 and x2 are 'stacked' to create a 6xN array for ransac\n [F, inliers] = ransac([x1; x2], fittingfn, distfn, degenfn, s, t, feedback);\n\n % Now do a final least squares fit on the data points considered to\n % be inliers.\n F = fundmatrix(x1(:,inliers), x2(:,inliers));\n \n % Denormalise\n F = T2'*F*T1;\n \n%--------------------------------------------------------------------------\n% Function to evaluate the first order approximation of the geometric error\n% (Sampson distance) of the fit of a fundamental matrix with respect to a\n% set of matched points as needed by RANSAC. See: Hartley and Zisserman,\n% 'Multiple View Geometry in Computer Vision', page 270.\n%\n% Note that this code allows for F being a cell array of fundamental matrices of\n% which we have to pick the best one. (A 7 point solution can return up to 3\n% solutions)\n\nfunction [bestInliers, bestF] = funddist(F, x, t);\n \n x1 = x(1:3,:); % Extract x1 and x2 from x\n x2 = x(4:6,:);\n \n \n if iscell(F) % We have several solutions each of which must be tested\n\t\t \n\tnF = length(F); % Number of solutions to test\n\tbestF = F{1}; % Initial allocation of best solution\n\tninliers = 0; % Number of inliers\n\t\n\tfor k = 1:nF\n\t x2tFx1 = zeros(1,length(x1));\n\t for n = 1:length(x1)\n\t\tx2tFx1(n) = x2(:,n)'*F{k}*x1(:,n);\n\t end\n\t \n\t Fx1 = F{k}*x1;\n\t Ftx2 = F{k}'*x2; \n\n\t % Evaluate distances\n\t d = x2tFx1.^2 ./ ...\n\t\t (Fx1(1,:).^2 + Fx1(2,:).^2 + Ftx2(1,:).^2 + Ftx2(2,:).^2);\n\t \n\t inliers = find(abs(d) < t); % Indices of inlying points\n\t \n\t if length(inliers) > ninliers % Record best solution\n\t\tninliers = length(inliers);\n\t\tbestF = F{k};\n\t\tbestInliers = inliers;\n\t end\n\tend\n \n else % We just have one solution\n\tx2tFx1 = zeros(1,length(x1));\n\tfor n = 1:length(x1)\n\t x2tFx1(n) = x2(:,n)'*F*x1(:,n);\n\tend\n\t\n\tFx1 = F*x1;\n\tFtx2 = F'*x2; \n\t\n\t% Evaluate distances\n\td = x2tFx1.^2 ./ ...\n\t (Fx1(1,:).^2 + Fx1(2,:).^2 + Ftx2(1,:).^2 + Ftx2(2,:).^2);\n\t\n\tbestInliers = find(abs(d) < t); % Indices of inlying points\n\tbestF = F; % Copy F directly to bestF\n\t\n end\n\t\n\n\n%----------------------------------------------------------------------\n% (Degenerate!) function to determine if a set of matched points will result\n% in a degeneracy in the calculation of a fundamental matrix as needed by\n% RANSAC. This function assumes this cannot happen...\n \nfunction r = isdegenerate(x)\n r = 0; \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/ransacfitfundmatrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.6619228691808012, "lm_q1q2_score": 0.5472194483689781}} {"text": "function q = times(q1,q2,takeRight)\n% quaternion .* quaternion and quaternion .* vector3d \n%\n% Syntax\n% q = q1 .* q2\n%\n% q = times(q1,q2)\n% q = times(q1,q2,takeRight)\n%\n% Input\n% q1 - @quaternion\n% q2 - @quaternion\n% takeRight - logical, use as output left or right input \n%\n% Output\n% q - @quaternion\n\nif isa(q1,'quaternion') && isa(q2,'quaternion')\n \n % which input will become the output?\n if nargin == 3 \n if takeRight, q = q2; else, q = q1; end\n elseif isa(q1,'rotation')\n q = q1;\n else\n q = q2;\n end\n \n a1 = q1.a; b1 = q1.b; c1 = q1.c; d1 = q1.d;\n a2 = q2.a; b2 = q2.b; c2 = q2.c; d2 = q2.d;\n \n %standard algorithm\n q.a = a1 .* a2 - b1 .* b2 - c1 .* c2 - d1 .* d2;\n q.b = b1 .* a2 + a1 .* b2 - d1 .* c2 + c1 .* d2;\n q.c = c1 .* a2 + d1 .* b2 + a1 .* c2 - b1 .* d2;\n q.d = d1 .* a2 - c1 .* b2 + b1 .* c2 + a1 .* d2;\n \nelseif isa(q1,'quaternion') && isa(q2,'double')\n \n q1.a = q1.a .* q2;\n q1.b = q1.b .* q2;\n q1.c = q1.c .* q2;\n q1.d = q1.d .* q2;\n q = q1;\n \nelseif isa(q2,'quaternion') && isa(q1,'double')\n \n q2.a = q1 .* q2.a;\n q2.b = q1 .* q2.b;\n q2.c = q1 .* q2.c;\n q2.d = q1 .* q2.d;\n q = q2;\n \nelse \n \n q = rotate(q2,q1);\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/@quaternion/times.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.6619228691808011, "lm_q1q2_score": 0.5472194427168677}} {"text": "% Modelling Sensor Directivity in 3D Example \n%\n% This example demonstrates how the sensitivity of a large single element\n% detector varies with the angular position of a point-like source. It is a\n% 3D version of the Modelling Sensor Directivity in 2D example.\n%\n% author: Ben Cox\n% date: 29th October 2010\n% last update: 23rd February 2012\n% \n% This function is part of the k-Wave Toolbox (http://www.k-wave.org)\n% Copyright (C) 2009-2014 Bradley Treeby and Ben Cox\n\n% This file is part of k-Wave. k-Wave is free software: you can\n% redistribute it and/or modify it under the terms of the GNU Lesser\n% General Public License as published by the Free Software Foundation,\n% either version 3 of the License, or (at your option) any later version.\n% \n% k-Wave is distributed in the hope that it will be useful, but WITHOUT ANY\n% WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n% FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for\n% more details. \n% \n% You should have received a copy of the GNU Lesser General Public License\n% along with k-Wave. If not, see . \n\nclear all;\n\n% =========================================================================\n% SIMULATION\n% =========================================================================\n\n% create the computational grid\nNx = 64; % number of grid points in the x direction\nNy = 64; % number of grid points in the y direction\nNz = 64; % number of grid points in the z direction\ndx = 100e-3/Nx; % grid point spacing in the x direction [m]\ndy = dx; % grid point spacing in the y direction [m]\ndz = dx; % grid point spacing in the z direction [m]\nkgrid = makeGrid(Nx, dx, Ny, dy, Nz, dz);\n\n% define the properties of the propagation medium\nmedium.sound_speed = 1500;\t% [m/s]\n\n% create the time array\n[kgrid.t_array, dt] = makeTime(kgrid, medium.sound_speed);\nNt = length(kgrid.t_array);\n\n% define a large area detector \nsensor.mask = zeros(Nx, Ny, Nz);\nsensor.mask(Nx/2+1, (Ny/2-9):(Ny/2+11),(Nz/2-9):(Nz/2+11)) = 1;\n\n% define equally spaced point sources lying on a circle centred at the\n% centre of the detector face \nNangles = 11;\ncircle = makeCartCircle(25*dx, Nangles, [0,0], pi);\ncircle = [circle; zeros(1,Nangles)];\n\n% find the binary sensor mask most closely corresponding to the cartesian\n% points coordinates from makeCartCircle\ncircle3D = cart2grid(kgrid,circle);\n\n% find the indices of the sources in the binary source mask\nsource_positions = find(circle3D == 1);\n\n% define a time varying sinusoidal source\nsource_freq = 0.25e6;\nsource_mag = 1;\nsource.p = source_mag*sin(2*pi*source_freq*kgrid.t_array);\n\n% filter the source to remove high frequencies not supported by the grid\nsource.p = filterTimeSeries(kgrid, medium, source.p);\n\n% pre-allocate array for storing the output time series\nsingle_element_data = zeros(Nt,length(source_positions));\n\n% run a simulation for each of these sources to see the effect that the\n% angle from the detector has on the measured signal\nfor source_loop = 1:length(source_positions)\n \n % select a point source\n source.p_mask = zeros(Nx,Ny,Nz);\n source.p_mask(source_positions(source_loop)) = 1;\n\n % create a display mask to display the transducer\n display_mask = source.p_mask + sensor.mask;\n\n % run the simulation\n input_args = {'PMLSize', 10, 'DisplayMask', display_mask, 'PlotScale', [-0.2 0.2], 'PlotFreq', 50, 'DataCast', 'single'};\n sensor_data = kspaceFirstOrder3D(kgrid, medium, source, sensor, input_args{:});\n\n % average the data recorded for each grid point to simulate the\n % measured signal from a large aperture, single element, detector\n single_element_data(:,source_loop) = sum(sum(sensor_data,1),1);\n\nend\n\n% =========================================================================\n% VISUALISATION\n% =========================================================================\n\n% plot source points and sensor mask\nvoxelPlot(circle3D + sensor.mask);\nview([-34 34])\n\n% plot the time series recorded for each of the sources\nfigure;\nplot(kgrid.t_array, single_element_data);\ncolormap(getColorMap);\nxlabel('time [s]');\nylabel('pressure');\ntitle('time series from each direction');\n\n% calculate angle between source and centre of detector face\nangles = atan((kgrid.y(source_positions))./kgrid.x(source_positions));\n\n% plot the maximum amplitudes for each of the sources, showing that the\n% detector sensitivity falls off at low angles as expected.\nfigure;\nplot(angles,max(single_element_data),'o')\ncolormap(getColorMap);\nxlabel('angle between source and centre of detector face');\nylabel('maximum detected pressure from each direction')\n", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/K-wave/k-Wave/examples/example_sd_directivity_modelling_3D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.6619228625116081, "lm_q1q2_score": 0.547219431551257}} {"text": "function adj = meshAdjacencyMatrix(faces, varargin)\n%MESHADJACENCYMATRIX Compute adjacency matrix of a mesh from set of faces\n%\n% ADJMAT = meshAdjacencyMatrix(FACES)\n% Returns a sparse NV-by-NV matrix (NV being the maximum vertex index)\n% containing vertex adjacency of the mesh represented by FACES.\n% FACES is either a NF-by-3, a NF-by-4 index array, or a Nf-by-1 cell\n% array.\n%\n% Example\n% [v f] = createCube;\n% adj = meshAdjacencyMatrix(f);\n%\n% See also\n% meshes3d, triangulateFaces, smoothMesh\n\n% ------\n% Author: David Legland\n% e-mail: david.legland@grignon.inra.fr\n% Created: 2013-04-30, using Matlab 7.9.0.529 (R2009b)\n% Copyright 2013 INRA - Cepia Software Platform.\n\n% Ensures faces is a N-by-3 or N-by-4 array\nif iscell(faces) || (isnumeric(faces) && size(faces, 2) > 4)\n faces = triangulateFaces(faces);\nend\n\n% forces faces to b efloating point array, for sparse function\nif ~isfloat(faces)\n faces = double(faces);\nend\n \n% populate a sparse matrix\nif size(faces, 2) == 3\n adj = sparse(...\n [faces(:,1); faces(:,1); faces(:,2); faces(:,2); faces(:,3); faces(:,3)], ...\n [faces(:,3); faces(:,2); faces(:,1); faces(:,3); faces(:,2); faces(:,1)], ...\n 1.0);\nelseif size(faces, 2) == 4\n adj = sparse(...\n [faces(:,1); faces(:,1); faces(:,2); faces(:,2); faces(:,3); faces(:,3); faces(:,4); faces(:,4)], ...\n [faces(:,4); faces(:,2); faces(:,1); faces(:,3); faces(:,2); faces(:,4); faces(:,3); faces(:,1)], ...\n 1.0);\nend\n \n% remove double adjacencies\nadj = min(adj, 1);\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/meshAdjacencyMatrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7248702880639791, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.5472154479914705}} {"text": "function lissajous ( )\n\n%*****************************************************************************80\n%\n%% LISSAJOUS uses MATLAB to draw a closed planar curve.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 16 May 2011\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'LISSAJOUS:\\n' );\n fprintf ( 1, ' MATLAB version\\n' );\n fprintf ( 1, ' Make a plane curve by connecting a series of points.\\n' );\n\n xy = load ( 'lissajous.txt' );\n%\n% Plot the data.\n%\n plot ( xy(:,1), xy(:,2), 'LineWidth', 2, 'Color', 'm' );\n hold on\n%\n% To avoid clutter, only plot every 10th point.\n%\n plot ( xy(1:10:end,1), xy(1:10:end,2), 'k.' );\n grid on\n axis ( [ -1.2, +1.2, -1.2, +1.2 ] )\n axis equal\n xlabel ( '<--- X --->' );\n ylabel ( '<--- Y --->' );\n title ( 'Lissajous, x=sin(3t+pi/2), y=sin(4t)' );\n hold off\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'LISSAJOUS:\\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/graphics_examples/lissajous.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149758396752, "lm_q2_score": 0.7248702642896702, "lm_q1q2_score": 0.5472154180531353}} {"text": " function [sinit, bodycoil] = ir_mri_sensemap_init(ykj, varargin)\n%function [sinit, bodycoil] = ir_mri_sensemap_init(ykj, varargin)\n%|\n%| Form initial sensitivity map estimates from surface coils and bodycoil.\n%|\n%| in\n%| ykj [(N) ncoil] surface coil data (2D or 3D)\n%|\n%| option\n%| 'type' initialization method (def: '' = 'ratio')\n%|\t\toptions: 'median', 'order1', 'order2', ...\n%|\t\tif numeric, then simply return as \"sinit\"\n%| 'bodycoil' [(N)] body coil data (def: SSoS of ykj with phase of 1st coil)\n%| 'thresh' fraction of max |bodycoil| that is \"good\" (def: 0.05)\n%| 'mask' [(N)] optional mask to pick good values instead of thresholding\n%| 'chat' 0|1 verbosity\n%|\n%| out\n%| sinit [(N) ncoil] initial sensitivity map estimates\n%| bodycoil [(N)] computed SSoS bodycoil image (if not provided)\n%|\n%| used in ir_mri_sensemap_admm - see that m-file for details.\n%|\n%| Michael Allison\n%| 2015-08-10 Jeff Fessler revise args, add tests, support 3D\n\nif nargin < 1, ir_usage(), end\nif streq(ykj, 'test', 4), ir_mri_sensemap_init_test(ykj), return, end\n\narg.type = '';\narg.thresh = 0.05;\narg.mask = [];\narg.bodycoil = [];\narg.chat = false;\narg = vararg_pair(arg, varargin);\n\nbodycoil = arg.bodycoil;\nif isempty(bodycoil)\n\tif ndims(ykj) < 3, fail('ykj must be 3D or 4D to infer bodycoil'), end\n\tndim = ndims(ykj) - 1; % 2 or 3\n\tbodycoil = sqrt(sum(abs(ykj).^2, ndim+1)); % sum-of-squares\n tmp = stackpick(ykj, 1); % ykj(:,...,:,1)\n tmp = angle(tmp); % crude estimate of phase of image f_j\n bodycoil = bodycoil .* exp(1i * tmp);\nelse\n\tndim = ndims(bodycoil);\n\tdim = size(bodycoil);\nend\n\nif ~isempty(arg.type) && isnumeric(arg.type) % trivial case\n\tsinit = arg.type;\nreturn\nend\n\ndim = size(bodycoil);\nncoil = numel(ykj) / prod(dim);\nif round(ncoil) ~= ncoil, fail('size'), end\n\nif ~isempty(arg.mask)\n\tjf_equal(size(arg.mask), dim)\n\tif arg.chat\n\t\twarn('using mask instead of threshold to determine good pixels')\n\tend\n\tgood = mask;\nend\n\nif arg.chat\n\ttell = @(s) printm(s);\nelse\n\ttell = @(s) nop(s);\nend\n\nsinit = zeros([prod(dim) ncoil], 'single');\nfor ic = 1:ncoil\n\t% cannot use stackpick because of case of just one coil\n\tif ndim == 2\n\t\tzj = ykj(:,:,ic);\n\telseif ndim == 3\n\t\tzj = ykj(:,:,:,ic);\n\tend\n\n\ttmp = div0(zj, bodycoil); % usual ratio\n\n\t% determine \"good\" pixels\n\tif isempty(arg.mask)\n\t\tgood = abs(bodycoil) > arg.thresh * max(abs(bodycoil(:)));\n\tend\n\n\tswitch arg.type\n\tcase {'', 'ratio'}\n\t\t% set all uncertain map values to median of good ones\n\t\ttell('Using zero background.')\n\t\ttmp(~good) = 0;\n\n\tcase 'median'\n\t\t% set all uncertain map values to median of good ones\n\t\ttell('Using median background.')\n\t\ttmp1 = median(abs(tmp(good)));\n\t\ttmp2 = median(angle(tmp(good))); % dubious\n\t\ttmp(~good) = tmp1 .* exp(1i*tmp2);\n\n\tcase 'avg'\n\t\t% set all uncertain map values to mean of good ones\n\t\ttell('Using mean background.')\n\t\ttmp1 = mean(abs(tmp(good)));\n\t\ttmp2 = mean(angle(tmp(good))); % dubious\n\t\ttmp(~good) = tmp1 .* exp(1i*tmp2);\n\n\tcase 'zeros'\n\t\ttmp = zeros(dim);\n\n\tcase 'order1'\n\t\ttell('Using 1st-order fit for background.')\n\t\texpo = [0 0; 1 0; 0 1];\n\t\ttmp = ortho_init(dim, expo, zj, bodycoil, good);\n\n\tcase 'order2'\n\t\ttell('Using 2nd order fit for background.')\n\t\texpo = [0 0; 1 0; 0 1; 1 1; 2 0; 0 2];\n\t\ttmp = ortho_init(dim, expo, zj, bodycoil, good);\n\n\tcase 'order3'\n\t\ttell('Using 3rd order fit for background.')\n\t\texpo = [0 0; 1 0; 0 1; 1 1; 2 0; 2 1; 0 2; 1 2; ...\n\t\t\t3 0; 0 3];\n\t\ttmp = ortho_init(dim, expo, zj, bodycoil, good);\n\n\tcase 'order4'\n\t\ttell('Using 4th order fit for background.')\n\t\texpo = [0 0; 1 0; 0 1; 1 1; 2 0; 2 1; 0 2; 1 2; ...\n\t\t\t3 0; 0 3; 2 2; 3 1; 1 3; 4 0; 0 4];\n\t\ttmp = ortho_init(dim, expo, zj, bodycoil, good);\n\n\totherwise\n\t\tfail('Unknown initialization type \"%s\"', init)\n\tend\n\n\tsinit(:,ic) = single(tmp(:));\nend % ic\nsinit = reshape(sinit, [dim ncoil]);\n\nend %\n\n\nfunction nop(varargin)\nend % nop\n\n\n% ortho_init()\n% initialize using orthogonal polynomial basis fit\nfunction init = ortho_init(dim, expo, zj, bodycoil, good)\nswitch numel(dim)\ncase 2\n\t%xx = ndgrid_jf('mat', 0:nx-1, 0:ny-1);\n\tA = cheby2d(dim(1), dim(2), expo);\ncase 3\n\tnx = dim(1);\n\tny = dim(2);\n\tny = dim(2);\n\tA = cheby3d(dim(1), dim(2), dim(3), expo);\notherwise\n\tfail('#dim = %d not done', numel(dim))\nend\n\nA = reshape(A, [prod(dim), size(expo,1)]);\nmaskBodyI = good .* bodycoil;\nAw = repmat(maskBodyI(:), [1 size(expo,1)]) .* A;\ntheta = pinv(Aw) * zj(:);\nclear Aw\ninit = A * theta; % not Aw\ninit = reshape(init, size(bodycoil));\n\nend % ortho_init()\n\n\n% cheby2d()\nfunction polys = cheby2d(nx,ny,expo)\nnbases = length(expo);\nx = linspace(-1,1,nx);\ny = linspace(-1,1,ny);\npolys = zeros(nx,ny,nbases);\nfor n = 1:nbases\n\ttmp = polyval(ir_chebyshev_poly(expo(n,1)),x);\n\ttmp = tmp';\n\tX = repmat(tmp,[1 ny]);\n\ttmp = polyval(ir_chebyshev_poly(expo(n,2)),y);\n\tY = repmat(tmp,[nx 1]);\n\tpolys(:,:,n) = X .* Y;\nend\n\nend % cheby2d()\n\n\n% cheby3d()\nfunction polys = cheby3d(nx,ny,expo)\nnbases = size(expo,1);\nx = linspace(-1,1,nx);\ny = linspace(-1,1,ny);\nz = linspace(-1,1,nz);\npolys = zeros(nx, ny, nz, nbases, 'single');\nfor n = 1:nbases\n\ttmp = polyval(ir_chebyshev_poly(expo(n,1)), x);\n\tX = repmat(tmp', [1 ny]);\n\ttmp = polyval(ir_chebyshev_poly(expo(n,2)), y);\n\tY = repmat(tmp, [nx 1]);\n\ttmp = polyval(ir_chebyshev_poly(expo(n,3)), z);\n\tZ = repmat(tmp, [nx 1]);\n\tpolys(:,:,:,n) = X .* Y .* Z;\nend\n\nend % cheby3d()\n\n\n% ir_mri_sensemap_init_test2()\n% 2D\nfunction ir_mri_sensemap_init_test2\nnx = 28; ny = 32;\nig = image_geom('nx', nx, 'ny', ny, 'fov', 22);\ntmp = ellipse_im(ig, 'shepplogan-emis', 'oversample', 2);\n%tmp = ones(nx,ny);\nxtrue = tmp .* exp(1i * (tmp-2));\nim(abs(xtrue))\nncoil = 4;\nstrue = ir_mri_sensemap_sim('nx', ig.nx, 'ny', ig.ny, 'dx', ig.dx, ...\n\t'ncoil', ncoil);\nscale = 1 / sqrt(sum(abs(strue(end/2,end/2,:).^2)));\nstrue = strue * scale; % normalize so SSoS=1 near center\nrng(0)\nykj = strue .* repmat(xtrue, [1 1 ncoil]) ...\n\t+ 2^-8 * (randn(size(strue)) + 1i * randn(size(strue)));\nim plc 5 2\nclim = minmax(abs(strue))';\nim(1, 'row', 1, abs(strue), clim, 'true'), cbar\nim(2, 'row', 1, abs(ykj)), cbar\nsinit1 = ir_mri_sensemap_init(ykj);\nim(3, 'row', 1, abs(sinit1), clim), cbar\nslist = {'ratio', 'median', 'avg', 'order1', 'order2', 'order3', 'order4', 'zeros'};\nfor is=1:numel(slist)\n\tstype = slist{is};\n\tsinit2 = ir_mri_sensemap_init(ykj, 'type', stype);\n\tim(2+is, 'row', 1, abs(sinit2), clim, stype), cbar\n\tdrawnow\nend\n\nend % ir_mri_sensemap_init_test2()\n\n\n% ir_mri_sensemap_init_test3()\n% 3D\nfunction ir_mri_sensemap_init_test3\nnx = 28; ny = 32; nz=6;\nig = image_geom('nx', nx, 'ny', ny, 'nz', nz, 'fov', 22, 'zfov', 10);\ntmp = ellipsoid_im(ig, 'shepp-logan-e3d', 'oversample', 2);\n%tmp = ig.ones;\nxtrue = tmp .* exp(1i * tmp); % arbitrary phase\n%im(abs(xtrue))\nnring = 3;\nncoil = 4 * nring;\nstrue = ir_mri_sensemap_sim('nx', ig.nx, 'ny', ig.ny, 'nz', ig.nz, ...\n\t'dx', ig.dx, 'nring', nring, 'ncoil', ncoil);\n%im('row', 3, abs(strue))\nscale = 1 / sqrt(sum(abs(strue(end/2,end/2,end/2,:).^2)));\nstrue = strue * scale; % normalize so SSoS=1 near center\nrng(0)\nykj = strue .* repmat(xtrue, [1 1 1 ncoil]) ...\n\t+ 1 * 2^-12 * (randn(size(strue)) + 1i * randn(size(strue)));\nim plc 4 1\nclim = minmax(abs(strue))';\nim(1, 'row', nring, abs(strue), clim, 'true'), cbar\ntitlef('True smaps for 3D [%d,%d,%d] with %d coils (%d rings of %d coils)', ...\n\tnx, ny, nz, ncoil, nring, ncoil/nring)\nim(2, 'row', nring, abs(ykj), 'surface coils'), cbar\nsinit1 = ir_mri_sensemap_init(ykj);\nim(3, 'row', nring, abs(sinit1), clim, 'ratio'), cbar\nslist = {'median'}; % 'avg', 'order1', 'order2', 'order3', 'order4', 'zeros'};\nfor is=1:numel(slist)\n\tstype = slist{is};\n\tsinit2 = ir_mri_sensemap_init(ykj, 'type', stype);\n\tim(3+is, 'row', nring, abs(sinit2), clim, stype), cbar\n\tdrawnow\nend\nend % ir_mri_sensemap_init_test3()\n\n\n% ir_mri_sensemap_init_test()\nfunction ir_mri_sensemap_init_test(arg)\nswitch arg\ncase 'test2'\n\tir_mri_sensemap_init_test2\ncase 'test3'\n\tir_mri_sensemap_init_test3\ncase 'test'\n\tir_mri_sensemap_init_test2\n\tif im, prompt, end\n\tir_mri_sensemap_init_test3\notherwise\n\tfail('unknown test \"%s\"', arg)\nend\nend % ir_mri_sensemap_init_test()\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/mri/ir_mri_sensemap_init.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107307, "lm_q2_score": 0.6548947425132314, "lm_q1q2_score": 0.547153770540039}} {"text": "function Stat=clusterstat(S,partition,between)\n%function Stat=clusterstat(S,partition,[between])\n%\n%PURPOSE\n%\n%To compute various intra- and extra-cluster statistics.\n%\n%INPUT \n%\n%[An argument in brackets is optional. If it isn't given or it's\n% an empty matrix/string, the function will use a default value.] \n%\n% S (matrix) NxN similarity or distance matrix between N\n% objects. Must be symmetric. \n% partition (1xN vector) partition vector (see explanation for\n% 'partition vector' in function hcluster) \n% [between] (scalar) 1: compute between-cluster similarity/distance matrix, \n% 0: (default) don't compute\n% \n%OUTPUT\n% \n% All fields are vectors of size 1xK, where K is the number of clusters\n% \n% Stat.N(i) the number of objects in cluster i\n%\n% Stat.internal.min(i) minimum/average/max internal similarity/distance \n% Stat.internal.avg(i) in cluster i\n% Stat.internal.max(i) \n% Note: if there is only one item in the cluster, the internal statistics\n% are set to NaN\n%\n% Stat.external.min(i) minimum/average/max external similarity/distance from\n% Stat.external.avg(i) objects of cluster i to the objects of other clusters\n% Stat.external.max(i)\n%\n%DETAILS\n%\n%Partition vector divides items into clusters: partition(i) is\n%the label of cluster that item i belongs to. Cluster labels must\n%be integers 1,2,...,K where K is the number of clusters. \n%\n%\"Internal\" for cluster k refers to all pairwise\n%distances/similarities between objects belonging to the same\n%cluster, i.e., for objects i for which partition(i)==k. \n%\n%\"External\" for cluster k refers to all pairwise\n%distances/similarities between the members of the cluster k and\n%members of the other clusters, i.e., the whole similarity matrix\n%excluding the internal similarities of cluster k.\n%\n%If 'between' is set to 1 the function computes also the following\n%KxK matrices \n%\n%Stat.between.min(i,j)\n%Stat.between.avg(i,j)\n%Stat.between.max(i,j)\n%\n%These include distances/similarities between clusters i and j\n%defined as min/average/max pairwise distances between objects\n%belonging to clusters i and j, respectively. \n%\n%SEE ALSO\n% clusterquality\n% icassoStability\n% icassoRindex\n% rindex\n\n%COPYRIGHT NOTICE\n%This function is a part of Icasso software library\n%Copyright (C) 2003-2005 Johan Himberg\n%\n%This program is free software; you can redistribute it and/or\n%modify it under the terms of the GNU General Public License\n%as published by the Free Software Foundation; either version 2\n%of the License, or any later version.\n%\n%This program is distributed in the hope that it will be useful,\n%but WITHOUT ANY WARRANTY; without even the implied warranty of\n%MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n%GNU General Public License for more details.\n%\n%You should have received a copy of the GNU General Public License\n%along with this program; if not, write to the Free Software\n%Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n\n% ver 1.2. 100105\n\nif nargin<2,\n error('You must give at least two input arguments.');\nend\n\nif nargin<3|isempty(between)\n between=0;\nend\n\n% Number of clusters\nNcluster=max(partition);\n\n%Initialize the struct\nStat.internal.sum(1:Ncluster,1)=NaN;\nStat.internal.min(1:Ncluster,1)=NaN;\nStat.internal.avg(1:Ncluster,1)=NaN;\nStat.internal.max(1:Ncluster,1)=NaN;\nStat.external.sum(1:Ncluster,1)=NaN;\nStat.external.min(1:Ncluster,1)=NaN;\nStat.external.avg(1:Ncluster,1)=NaN;\nStat.external.max(1:Ncluster,1)=NaN;\nStat.index = cell(1,Ncluster);\n\nfor cluster=1:Ncluster,\n thisPartition=(partition==cluster);\n Stat.index{cluster} = find(thisPartition);\n S_=S(thisPartition,thisPartition);\n Stat.N(cluster)=size(S_,1);\n S_(eye(size(S_))==1)=[];\n if ~isempty(S_),\n Stat.internal.sum(cluster)=sum(S_);\n Stat.internal.min(cluster)=min(S_);\n Stat.internal.avg(cluster)=mean(S_);\n Stat.internal.max(cluster)=max(S_);\n end \n if Ncluster>1,\n S_=S(thisPartition,~thisPartition);\n Stat.external.sum(cluster)=sum(S_(:));\n Stat.external.min(cluster)=min(S_(:));\n Stat.external.avg(cluster)=mean(S_(:));\n Stat.external.max(cluster)=max(S_(:));\n end\nend\n\nif between,\n Stat.between.min=zeros(Ncluster,Ncluster);\n Stat.between.max=zeros(Ncluster,Ncluster);\n Stat.between.avg=zeros(Ncluster,Ncluster);\n\n for i=1:Ncluster,\n Pi=find(i==partition);\n for j=i+1:Ncluster,\n Pj=find(j==partition);\n d_=S(Pi,Pj); \n Stat.between.min(i,j)=min(d_(:));\n Stat.between.avg(i,j)=mean(d_(:));\t\t\n Stat.between.max(i,j)=max(d_(:));\t\t;\t\t\n end\n end \n \n Stat.between.min=Stat.between.min+ ...\n Stat.between.min';\n Stat.between.max=Stat.between.max+ ...\n Stat.between.max';\n Stat.between.avg=Stat.between.avg+ ...\n Stat.between.avg';\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/icasso/clusterstat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.6548947290421276, "lm_q1q2_score": 0.5471537646505137}} {"text": "%-------------------------------------------------------------------------------------------------------------------%\n%\n% IB2d is an Immersed Boundary Code (IB) for solving fully coupled \n% \tfluid-structure interaction models. This version of the code is based off of\n%\tPeskin's Immersed Boundary Method Paper in Acta Numerica, 2002.\n%\n% Author: Nicholas A. Battista\n% Email: nickabattista[at]gmail.com\n% IB2d Created: May 27th, 2015\n% Institution: TCNJ\n%\n% This code is capable of creating Lagrangian Structures using:\n% \t1. Springs\n% \t2. Beams (*torsional springs or non-invariant beams*)\n% \t3. Target Points\n%\t4. Muscle-Model (combined Force-Length-Velocity model, \"HIll+(Length-Tension)\")\n% .\n% .\n% .\n%\n% One is able to update those Lagrangian Structure parameters, e.g., spring constants, resting lengths, etc\n% \n% There are a number of built in Examples, mostly used for teaching purposes. \n% \n% If you would like us to add a specific muscle model, please let Nick (nickabattista[at]gmail.co) know.\n%\n%--------------------------------------------------------------------------------------------------------------------%\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: updates the beam attributes!\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction beams_info = update_nonInv_Beams(dt,current_time,beams_info)\n\n\n% beams_info: col 1: 1ST PT.\n% col 2: MIDDLE PT. (where force is exerted)\n% col 3: 3RD PT.\n% col 4: beam stiffness\n% col 5: x-curvature\n% col 6: y-curvature\n\n%IDs = beams_info(:,1); % Gives Middle Pt.\n\n% Time initialization\nt1 = 0.25; % Period A->B (down-stroke)\nt2 = 0.25; % Period B->A (up-stroke)\ntR = 0.0; % Resting time between A->B and B->A\nperiod = (t1+t2+tR); % Time it takes to move to the right\nt = rem(current_time,period); % Recalculate Time (using modular arithmetic)\n\n% Cubic Interpolation Information\np1 = 0.10;\np2 = 0.90;\n\n% a COEFFICIENTS\na0 = 0; \na1 = 0; \na2 = 0; \na3 = 11.111111111111088;\n\n% b COEFFICIENTS\nb0 = 0.013888888888889;\nb1 = -0.416666666666666;\nb2 = 4.166666666666658;\nb3 = -2.777777777777770;\n\n% c COEFFICIENTS\nc0 = -10.111111111111073;\nc1 = 33.333333333333222;\nc2 = -33.333333333333222;\nc3 = 11.111111111111073;\n\n\n% Read In y_Pts for two Phases!\n[xP1,yP1,yP2] = read_File_In('swimmer.phases'); % NOTE xP1 = xP2\nxP2 = xP1;\n\n%\n% FIRST WE COMPUTE THE INTERPOLATE GEOMETRY BETWEEN BOTH PHASES\n%\n\n%\n% START THE INTERPOLATING BETWEEN STATES!\n% \nif t <= t1 % STATE A -> STATE B\n\n % Scaling time for appropriate use in interp. function so tTilde\\in[0,1]\n tTilde = (t/t1); \n \n % Evaluate Pieceise Cubic Interpolation Poly\n if ( tTilde<=p1 )\n gFUNC = a0 + a1*tTilde + a2*tTilde^2 + a3*tTilde^3; \n elseif ( (tTilde>p1) && (tTilde<=p2) )\n gFUNC = b0 + b1*tTilde + b2*tTilde^2 + b3*tTilde^3; \n else\n gFUNC = c0 + c1*tTilde + c2*tTilde^2 + c3*tTilde^3; \n end\n \n %xPts = xP1 + gFUNC*( xP2 - xP1 );\t\n yPts = yP1 + gFUNC*( yP2 - yP1 );\t\n \nelseif ( t >= t1+tR ) % STATE B -> A\n \n % Scaling time for appropriate use in interp. function so tTilde\\in[0,1]\n tTilde = (t-t1-tR)/(t2); \n \n % Evaluate Pieceise Cubic Interpolation Poly\n if tTilde<=p1\n gFUNC = a0 + a1*tTilde + a2*tTilde^2 + a3*tTilde^3; \n elseif tTilde<=p2\n gFUNC = b0 + b1*tTilde + b2*tTilde^2 + b3*tTilde^3; \n else\n gFUNC = c0 + c1*tTilde + c2*tTilde^2 + c3*tTilde^3; \n end\n \n %xPts = xP2 + gFUNC*( xP1 - xP2 );\n yPts = yP2 + gFUNC*( yP1 - yP2 );\n \nend\n\n\n\n%\n% NOW WE UPDATE THE CURAVTURES APPROPRIATELY\n%\n%beams_info(:,5) = xPts(1:end-2)+xPts(3:end)-2*xPts(2:end-1);\nbeams_info(:,6) = yPts(1:end-2)+yPts(3:end)-2*yPts(2:end-1);\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: reads in info from file\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [x1,y1,y2] = read_File_In(file_name)\n\nfilename = file_name; %Name of file to read in\n\nfileID = fopen(filename);\n\n % Read in the file, use 'CollectOutput' to gather all similar data together\n % and 'CommentStyle' to to end and be able to skip lines in file.\n C = textscan(fileID,'%f %f %f','CollectOutput',1);\n\nfclose(fileID); %Close the data file.\n\nmat_info = C{1}; %Stores all read in data\n\n%Store all elements in matrix\nmat = mat_info(1:end,1:end);\n\nx1 = mat(:,1); %store xVals1/2\ny1 = mat(:,2); %store yVals1 \ny2 = mat(:,3); %store yVals2", "meta": {"author": "nickabattista", "repo": "IB2d", "sha": "392d99c228cc801ff65766889c72e2e1492fe747", "save_path": "github-repos/MATLAB/nickabattista-IB2d", "path": "github-repos/MATLAB/nickabattista-IB2d/IB2d-392d99c228cc801ff65766889c72e2e1492fe747/matIB2d/Examples/Examples_Education/Interpolation/Swimmer/update_nonInv_Beams.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034369, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5471537646505136}} {"text": "function [LL, LLS, ht] = tarch_likelihood(parameters, data, fdata, fIdata, p, o, q, error_type, tarch_type, back_cast, T, estim_flag)\n% Log likelihood for TARCH(P,O,Q) estimation\n%\n% USAGE:\n% [LL, LLS, HT] = tarch_likelihood(PARAMETERS, DATA, FDATA, FIDATA, P, O, Q, ERROR_TYPE, TARCH_TYPE, BACK_CAST, T, ESTIM_FLAG)\n%\n% INPUTS:\n% PARAMETERS - A vector of GARCH process parameters\n% [omega alpha gamma beta [nu lambda]]\n% DATA - Vector of mean zero residuals\n% FDATA - Either abs(data) or data.^2, depending on tarch_type\n% FIDATA - fdata times an indicator for negative, e.g. fdata.*(data<0)\n% P - The lag order length for ARCH\n% O - The lag order of asymmetric terms\n% Q - The lag order length for GARCH\n% ERROR_TYPE - The type of error being assumed, valid types are:\n% 1 if 'NORMAL'\n% 2 if 'STUDENTST'\n% 3 if 'GED'\n% 4 if 'SKEWT'\n% TARCH_TYPE - 1 for absolute vale of return\n% - 2 for squared returns (standard case)\n% BACK_CAST - The value used for variance recursion\n% T - Length of data\n% ESTIM_FLAG - [OPTIONAL] Flag (0 or 1) to indicate if the function\n% is being used in estimation. If it is 1, then the parameters are\n% transformed from unconstrained values to constrained by standard\n% garch model constraints\n%\n% OUTPUTS:\n% LL - Minus 1 times the log likelihood\n% LLS - Time series of log likelihoods (Also multiplied by -1)\n% HT - Time series of conditional variances\n%\n% COMMENTS:\n% See also TARCH\n\n% Copyright: Kevin Sheppard\n% kevin.sheppard@economics.ox.ac.uk\n% Revision: 3 Date: 9/1/2005\n\nif nargin==12 && estim_flag\n %If for estimation, transform the parameters\n [parameters,nu,lambda]=tarch_itransform(parameters,p,o,q,error_type);\nelse\n %Otherwise the parameters simply must be parsed\n if error_type==2 || error_type==3\n %Seperate nu from the remaning parameters\n nu=parameters(p+o+q+2);\n parameters=parameters(1:1+p+o+q);\n elseif error_type==4\n lambda=parameters(p+o+q+3);\n nu=parameters(p+o+q+2);\n parameters=parameters(1:1+p+o+q);\n end\nend\n\n%Backcast length\nm = max([p o q]);\n%Compute the conditional variances\nht=tarch_core(fdata,fIdata,parameters,back_cast,p,o,q,m,T,tarch_type);\n\n%Indices for the relevant opservations\nt = (m + 1):T;\nht=ht(t);\ndata=data(t);\n%Compute the log likelihoods\nswitch error_type\n case 1\n [LL, LLS] = normloglik(data,0,ht);\n LLS = -LLS;\n LL = -LL;\n case 2\n [LL, LLS] = stdtloglik(data,0,ht,nu);\n LLS = -LLS;\n LL = -LL;\n case 3\n [LL, LLS] = gedloglik(data,0,ht,nu);\n LLS = -LLS;\n LL = -LL;\n case 4\n [LL, LLS] = skewtloglik(data,0,ht,nu,lambda);\n LLS = -LLS;\n LL = -LL;\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/univariate/tarch_likelihood.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127678225575, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5470471359727075}} {"text": "function [Estimation_X0,FirstLandmarks] = FEKF_update(Estimation_X0, CameraMeasurementThis, Sigma_OB , FirstLandmarks)\nNumberOfLandmarksObInThisStep = size(CameraMeasurementThis,1)/3;\n\n% initialise the IndexOfFeature if possible\nif size(Estimation_X0.landmarks,2) > 0\n IndexOfFeature = Estimation_X0.landmarks(4,:)';\nelse\n IndexOfFeature = [];\nend\n\nIndexObservedAlreadyThis = [];\nIndexObservedNew = []; \nfor i = 1:NumberOfLandmarksObInThisStep\n % check whether the feature is observed before or not\n M = find( IndexOfFeature== CameraMeasurementThis(3*i,2) );\n if isempty(M)\n IndexObservedNew = [IndexObservedNew;CameraMeasurementThis(3*i,2) ];\n else\n IndexObservedAlreadyThis = [IndexObservedAlreadyThis;CameraMeasurementThis(3*i,2)];\n end \nend\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% IndexObservedNew=[78; 97; 18] indicates that the \n% robot firstly observes landmarks 78 97 18 in this step\n% IndexObservedAlreadyThis=[19; 20; 53] indicates \n% that the robot observes again landmarks 19 20 53 in this step\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\norientation = Estimation_X0.orientation;\nposition = Estimation_X0.position;\ncov = Estimation_X0.cov;\n\nNumberOfFeature = size( IndexOfFeature,1);\nNumberOfOldFeatureInThisStep = size(IndexObservedAlreadyThis,1);\nNumberOfNewFeatureInThisStep = size(IndexObservedNew,1);\n \n\n\n\n% update state vector and covariance by considering \n% new feature into state and covariance\nif ~isempty(IndexObservedNew)\n \n orientation = Estimation_X0.orientation;\n position = Estimation_X0.position;\n \n % copy previous covariance\n temp = repmat({eye(3)}, NumberOfNewFeatureInThisStep, 1 );\n tempKK = blkdiag(temp{:});\n Sigma = blkdiag(Estimation_X0.cov,tempKK);\n KK = eye(6+3*(NumberOfFeature+NumberOfNewFeatureInThisStep));\n \n % add new features\n for i = 1:NumberOfNewFeatureInThisStep\n indNewf = IndexObservedNew(i);\n Estimation_X0.landmarks(4,NumberOfFeature+i) = indNewf;\n m2 = find( CameraMeasurementThis(:,2) == indNewf );\n nf = CameraMeasurementThis( m2, 1 );\n\n Estimation_X0.landmarks(1:3,NumberOfFeature+i) = orientation*nf+position;\n Newlandmark=[ orientation*nf+position; indNewf ];\n \n FirstLandmarks=[FirstLandmarks Newlandmark];\n \n% KK( 6+3*NumberOfFeature+3*i-2:6+3*NumberOfFeature+3*i,1:6 ) = [-skew(Estimation_X0.orientation*(nf)) eye(3)]; \n% KK (6+3*NumberOfFeature+3*i-2:6+3*NumberOfFeature+3*i, 6+3*NumberOfFeature+3*i-2:6+3*NumberOfFeature+3*i )=Estimation_X0.orientation;\n \n KK( 6+3*NumberOfFeature+3*i-2:6+3*NumberOfFeature+3*i,1:6 ) = [-skew(orientation*(nf)) eye(3)]; \n KK (6+3*NumberOfFeature+3*i-2:6+3*NumberOfFeature+3*i, 6+3*NumberOfFeature+3*i-2:6+3*NumberOfFeature+3*i )=orientation;\n tempKK(3*i-2:3*i,3*i-2:3*i)=diag(nf.^2)*Sigma_OB^2;\n end\n Sigma = blkdiag(Estimation_X0.cov,tempKK);\n Estimation_X0.cov = KK*Sigma*KK';\n \n NumberOfFeature=NumberOfFeature+NumberOfNewFeatureInThisStep;\nend\n\n\norientation = Estimation_X0.orientation;\nposition = Estimation_X0.position;\ncov = Estimation_X0.cov;\n\n \n% update state and covariance \nif ~isempty(IndexObservedAlreadyThis)\n Z = zeros( NumberOfOldFeatureInThisStep*3 , 1); \n Y = zeros( NumberOfOldFeatureInThisStep*3 , 1); \n H = zeros(3*NumberOfOldFeatureInThisStep, 6+3*NumberOfFeature);\n \n temp = repmat({eye(3)}, NumberOfOldFeatureInThisStep,1 );\n R = blkdiag(temp{:});\n \n \n % update old features\n for i = 1:NumberOfOldFeatureInThisStep\n ind = find(IndexOfFeature == IndexObservedAlreadyThis(i));\n \n fi = Estimation_X0.landmarks(1:3,ind);\n Y(3*i-2:3*i,1) = ObservationModel( orientation, position, fi );\n \n ind2 = find(CameraMeasurementThis(:,2) == IndexObservedAlreadyThis(i));\n Z(3*i-2:3*i,1 ) = CameraMeasurementThis(ind2,1);\n \n FirstLandmark=FirstLandmarks(1:3,ind);\n \n H(3*i-2:3*i, 1:6) = [-orientation'*skew(FirstLandmark-position) orientation'];\n H(3*i-2:3*i, 6+3*ind-2:6+3*ind) = -orientation'; \n R(3*i-2:3*i,3*i-2:3*i) = diag(CameraMeasurementThis(ind2,1).^2)*Sigma_OB^2;\n end \n \n % question @RomaTeng, different computaton scheme\n z = Z-Y;\n S = H*cov*H'+R;\n K = cov*H'*inv(S);\n s = K*z;\n \n Estimation_X0 = SpecialAdd(Estimation_X0,-s);\n cov = ( eye(6+3*NumberOfFeature) -K*H )*cov;\n Estimation_X0.cov = cov;\n \n \nend \n \n\n\n \n \n\n\n\n", "meta": {"author": "RomaTeng", "repo": "EKF-SLAM-on-Manifold", "sha": "12d7d8d88c84161baed173e38d49dedb4adb2b96", "save_path": "github-repos/MATLAB/RomaTeng-EKF-SLAM-on-Manifold", "path": "github-repos/MATLAB/RomaTeng-EKF-SLAM-on-Manifold/EKF-SLAM-on-Manifold-12d7d8d88c84161baed173e38d49dedb4adb2b96/f_ekf_3d/FEKF_update.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339756938819, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.5469648100935761}} {"text": "function [g_all, vv_all]=vifsub_est_M(org,dist, subbands, M); \n\n% uses convolution for determining the parameters of the distortion channel\n% Called by vifvec.m\n\ntol = 1e-15; % tolernace for zero variance. Variance below this is set to zero, and zero is set to this value to avoid numerical issues.\n\n\nfor i=1:length(subbands)\n sub=subbands(i);\n y=org{sub};\n yn=dist{sub};\n\n % compute the size of the window used in the distortion channel estimation\n lev=ceil((sub-1)/6);\n winsize=2^lev+1; offset=(winsize-1)/2;\n win = ones(winsize);\n \n % force subband size to be multiple of M\n newsize=floor(size(y)./M)*M;\n y=y(1:newsize(1),1:newsize(2));\n yn=yn(1:newsize(1),1:newsize(2));\n\n % Correlation with downsampling. This is faster than downsampling after\n % computing full correlation.\n winstep=[M M];\n winstart=[1 1].*floor(M/2)+1;\n winstop=size(y)-ceil(M/2)+1;\n \n % mean\n mean_x = corrDn(y,win/sum(win(:)),'reflect1',winstep, winstart,winstop);\n mean_y = corrDn(yn,win/sum(win(:)),'reflect1',winstep, winstart,winstop);\n % cov\n cov_xy = corrDn(y.*yn, win, 'reflect1',winstep, winstart,winstop) - sum(win(:)).*mean_x.*mean_y;\n % var\n ss_x = corrDn(y.^2,win, 'reflect1',winstep, winstart,winstop) - sum(win(:)).*mean_x.^2;\n ss_y = corrDn(yn.^2,win, 'reflect1',winstep, winstart,winstop) - sum(win(:)).*mean_y.^2;\n\n \n % get rid of numerical problems, very small negative numbers, or very\n % small positive numbers, or other theoretical impossibilities.\n ss_x(ss_x<0)=0;\n ss_y(ss_y<0)=0;\n \n % Regression \n g = cov_xy./(ss_x+tol);\n \n % Variance of error in regression\n vv = (ss_y - g.*cov_xy)/(sum(win(:)));\n \n % get rid of numerical problems, very small negative numbers, or very\n % small positive numbers, or other theoretical impossibilities.\n g (ss_x < tol) = 0;\n vv (ss_x < tol) = ss_y (ss_x < tol);\n ss_x(ss_x.\n%\n\nif(~exist('I_gx', 'var') || ~exist('I_gy', 'var'))\n error('Gradients are needed to compute divergence');\nend\n\nkernelX = [0 0 0; -1 1 0; 0 0 0];\nkernelY = [0 0 0; 0 1 0; 0 -1 0];\n\nI_dx = imfilter(I_gx, kernelX, 'same');\nI_dy = imfilter(I_gy, kernelY, 'same');\n\ndivI = RemoveSpecials(I_dx + I_dy);\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/util/computeDivergence.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943822145998, "lm_q2_score": 0.7217432182679956, "lm_q1q2_score": 0.5469329562049728}} {"text": "function [ degrees, minutes, seconds] = latlonvec(decimal_degrees)\n%LATLONVEC Convert decimal degrees into degrees/minutes/seconds\n%\n% Description: \n% Return degrees, minutes, seconds given decimal degrees. Sign of\n% coordinate will be returned in degrees portion of coordinate.\n%\n% Sample fuction call: \n% [ degrees, minutes, seconds] = latlonvec(decimal_degrees)\n%\n% Author: Scott Lee\n%\n% //////////////////////////////////////////\n% /// CLASSIFICATION: UNCLASSIFIED ///\n% //////////////////////////////////////////\n\ndegrees = fix(abs(decimal_degrees));\t% integer degrees\nfrac = abs(decimal_degrees) - degrees;\t% fractional degrees, used to compute minutes \nminutes = fix(frac*60);\t % integer minutes\nfrac = frac - minutes/60;\t% fractional minutes, used to compute seconds\nseconds = frac*3600;\t\t% decimal seconds\n\n% Handle sign. Degrees portion will contain the sign of the coordinate.\n% Minutes and seconds will always be positive.\n% sign function returns -1, 0, +1 for x < 0, x == 0, x > 0, respectively\ndegrees = sign(decimal_degrees).*degrees;\n\nif nargout<2\n degrees = [degrees minutes seconds];\nend\n\nend\n\n% //////////////////////////////////////////\n% /// CLASSIFICATION: UNCLASSIFIED ///\n% //////////////////////////////////////////", "meta": {"author": "ngageoint", "repo": "MATLAB_SAR", "sha": "6291feff8e200d387e271f49ec09b1acd5514c4e", "save_path": "github-repos/MATLAB/ngageoint-MATLAB_SAR", "path": "github-repos/MATLAB/ngageoint-MATLAB_SAR/MATLAB_SAR-6291feff8e200d387e271f49ec09b1acd5514c4e/Geometry/coordinates/latlonvec.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.7217432182679957, "lm_q1q2_score": 0.5469329483091314}} {"text": "function dist = codedist_bay(C1,C2,Py)\n% compute the distance using a Bayesian metric between 'C1' and 'C2'\n%\n% dist = codedist_bay(C1,C2,{Py})\n%\n% 'C1' contains the result code, \n% 'C2' contains the codebooks prototype. '0' or an infine small number 'eps' represents the don't care\n% 'Py' is a matrix containing the moderated outputs of the binary classifiers\n%\n% \n% An example:\n% >> Ye = [1 1; 1 1];\n% >> codebook = [1 2 3];\n% >> old_codebook = [1 1 -1; 1 -1 -1];\n% >> Py = [.9 -.1; -.1 .13];\n% >> code(Ye, codebook, [],old_codebook,'codedist_bay',{Py})\n% in this call, 'Ye' is not used explicitly.\n%\n% To use this distance measure in LS-SVMlab, the following\n% procedure is to be followed, assume input data 'X' and multiclass\n% output 'Y':\n%\n% >> [Ycode,codebook,old_codebook] = code(Y,'code_MOC');\n% >> [alpha,b] = trainlssvm({X,Yc,'c',gam,sig2});\n% >> Yhc = simlssvm({X,Yc,'c',gam,sig2},{alpha,b},Xt);\n%\n% The moderated output for the LS-SVM can be computed using the bayesian inference\n% framework for the LS-SVM: \n% >> Ymod = bay_modoutClass(model,Xt);\n% >> Yh = code(Yhc,old_codebook,[],codebook,'codedist_bay',{Ymod});\n% \n% see also:\n% bay_modoutClass, codedist_hamming, code_ECOC\n\n% Copyright (c) 2011, KULeuven-ESAT-SCD, License & help @ http://www.esat.kuleuven.be/sista/lssvmlab\n\n% % encode for training\n% >> model = initlssvm(X,Y,'classification',gam,sig2,'preprocess','RBF_kernel');\n% >> model = changelssvm(model,'codetype','code_MOC');\n% >> model = changelssvm(model,'codedist_fct','codedist_hamming');\n% >> model = trainlssvm(model);\n% \n% % decode for simulating\n% >> model = changelssvm(model,'codedist_fct','codedist_bay');\n% >> model = changelssvm(model,'codedist_args',{bay_modoutClass(model,Xt)});\n% >> Yt = simlssvm(model,Xt);\n\n\nif nargin<3,\n error(['moderated output needed as function arguments' ...\n\t '(for LS-SVM, model.codedist_args =' ...\n\t ' bay_modoutClass(model,X)).']);\nend\n\n\n[nb,nbin] = size(Py);\n[~,dim] = size(C2);\ndist = zeros(nb,dim);\n\nfor d = 1:dim,\n for n= 1:nb,\n dist(n,d) = sum((1-Py(n,:).*C2(:,d)'))-sum(C2(:,d)==eps);\n end\nend\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/codedist_bay.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.668880247169804, "lm_q1q2_score": 0.5468594177161273}} {"text": "function lik = lik_binomial(varargin)\n%LIK_BINOMIAL Create a Binomial likelihood structure \n%\n% Description\n% LIK = LIK_BINOMIAL creates Binomial likelihood structure.\n%\n% The likelihood is defined as follows:\n% __ n\n% p(y|f, z) = || i=1 [ p_i^(y_i)*(1-p_i)^(z_i-y_i)) * \n% gamma(z_i+1)/(gamma(y_i+1)*gamma(z_i-y_i+1))]\n% where p_i = exp(f_i)/ (1+exp(f_i)) is the succes probability,\n% which is a function of the latent variable f_i and z is a\n% vector of numbers of trials. \n%\n% When using Binomial likelihood you need to give the vector z\n% as an extra parameter to each function that requires y also. \n% For example, you should call gp_optim as follows\n% gp_optim(gp, x, y, 'z', z)\n%\n% See also\n% GP_SET, LIK_*\n%\n% Copyright (c) 2009-2010 Jaakko Riihimäki & Jarno Vanhatalo\n% Copyright (c) 2010-2011 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_BINOMIAL';\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 = 'Binomial';\n else\n if ~isfield(lik,'type') || ~isequal(lik.type,'Binomial')\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_binomial_pak;\n lik.fh.unpak = @lik_binomial_unpak;\n lik.fh.ll = @lik_binomial_ll;\n lik.fh.llg = @lik_binomial_llg; \n lik.fh.llg2 = @lik_binomial_llg2;\n lik.fh.llg3 = @lik_binomial_llg3;\n lik.fh.tiltedMoments = @lik_binomial_tiltedMoments;\n lik.fh.predy = @lik_binomial_predy;\n lik.fh.predprcty = @lik_binomial_predprcty;\n lik.fh.invlink = @lik_binomial_invlink;\n lik.fh.recappend = @lik_binomial_recappend;\n end\n\nend\n\nfunction [w,s,h] = lik_binomial_pak(lik)\n%LIK_BINOMIAL_PAK Combine likelihood parameters into one vector.\n%\n% Description \n% W = LIK_BINOMIAL_PAK(LIK) takes a likelihood structure LIK\n% and returns an empty verctor W. If Binomial likelihood had\n% parameters this would combine them into a single row vector\n% W (see e.g. likelih_negbin). This is a mandatory subfunction \n% used for example in energy and gradient computations.\n%\n% See also\n% LIK_NEGBIN_UNPAK, GP_PAK\n\n w = []; s = {}; h=[];\nend\n\n\nfunction [lik, w] = lik_binomial_unpak(lik, w)\n%LIK_BINOMIAL_UNPAK Extract likelihood parameters from the vector.\n%\n% Description\n% W = LIK_BINOMIAL_UNPAK(W, LIK) Doesn't do anything.\n% \n% If Binomial likelihood had parameters this would extracts\n% them parameters from the vector W to the LIK structure. \n% This is a mandatory subfunction used for example in energy \n% and gradient computations.\n%\n% See also\n% LIK_BINOMIAL_PAK, GP_UNPAK\n\n lik=lik;\n w=w;\n \nend\n\n\n\nfunction ll = lik_binomial_ll(lik, y, f, z)\n%LIK_BINOMIAL_LL Log likelihood\n%\n% Description\n% LL = LIK_BINOMIAL_LL(LIK, Y, F, Z) takes a likelihood\n% structure LIK, succes counts Y, numbers of trials 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_BINOMIAL_LLG, LIK_BINOMIAL_LLG3, LIK_BINOMIAL_LLG2, GPLA_E\n \n if isempty(z)\n error(['lik_binomial -> lik_binomial_ll: missing z!'... \n 'Binomial likelihood needs the expected number of '...\n 'occurrences as an extra input z. See, for '...\n 'example, lik_binomial and gp_optim. ']);\n end\n \n expf = exp(f);\n p = expf ./ (1+expf);\n N = z;\n ll = sum(gammaln(N+1)-gammaln(y+1)-gammaln(N-y+1)+y.*log(p)+(N-y).*log(1-p));\nend\n\n\nfunction llg = lik_binomial_llg(lik, y, f, param, z)\n%LIK_BINOMIAL_LLG Gradient of the log likelihood\n%\n% Description \n% LLG = LIK_BINOMIAL_LLG(LIK, Y, F, PARAM) takes a likelihood\n% structure LIK, succes counts Y, numbers of trials Z and\n% latent values F. Returns the gradient of the log likelihood\n% with respect to PARAM. At the moment PARAM can be 'param' or\n% 'latent'. This subfunction is needed when using Laplace \n% approximation or MCMC for inference with non-Gaussian \n% likelihoods.\n%\n% See also\n% LIK_BINOMIAL_LL, LIK_BINOMIAL_LLG2, LIK_BINOMIAL_LLG3, GPLA_E\n\n if isempty(z)\n error(['lik_binomial -> lik_binomial_llg: missing z!'... \n 'Binomial likelihood needs the expected number of '...\n 'occurrences as an extra input z. See, for '...\n 'example, lik_binomial and gp_optim. ']);\n end\n \n switch param\n case 'latent'\n expf = exp(f);\n N = z;\n \n llg = y./(1+expf) - (N-y).*expf./(1+expf);\n end\nend\n\n\nfunction llg2 = lik_binomial_llg2(lik, y, f, param, z)\n%LIK_BINOMIAL_LLG2 Second gradients of the log likelihood\n%\n% Description \n% LLG2 = LIK_BINOMIAL_LLG2(LIK, Y, F, PARAM) takes a\n% likelihood structure LIK, succes counts Y, numbers of trials\n% Z, and latent values F. Returns the Hessian of the log\n% likelihood with respect to PARAM. At the moment PARAM can be\n% only 'latent'. G2 is a vector with diagonal elements of the\n% Hessian matrix (off diagonals are zero). This subfunction\n% is needed when using Laplace approximation or EP for inference \n% with non-Gaussian likelihoods.\n%\n% See also\n% LIK_BINOMIAL_LL, LIK_BINOMIAL_LLG, LIK_BINOMIAL_LLG3, GPLA_E\n\n if isempty(z)\n error(['lik_binomial -> lik_binomial_llg2: missing z!'... \n 'Binomial likelihood needs the expected number of '...\n 'occurrences as an extra input z. See, for '...\n 'example, lik_binomial and gp_optim. ']);\n end\n \n switch param\n case 'latent'\n expf = exp(f);\n N = z;\n\n llg2 = -N.*expf./(1+expf).^2;\n end\nend\n\n\nfunction llg3 = lik_binomial_llg3(lik, y, f, param, z)\n%LIK_BINOMIAL_LLG3 Third gradients of the log likelihood\n%\n% Description\n% LLG3 = LIK_BINOMIAL_LLG3(LIK, Y, F, PARAM) takes a\n% likelihood structure LIK, succes counts Y, numbers of trials\n% Z 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 appoximation \n% for inference with non-Gaussian likelihoods.\n%\n% See also\n% LIK_BINOMIAL_LL, LIK_BINOMIAL_LLG, LIK_BINOMIAL_LLG2, GPLA_E, GPLA_G\n \n if isempty(z)\n error(['lik_binomial -> lik_binomial_llg3: missing z!'... \n 'Binomial likelihood needs the expected number of '...\n 'occurrences as an extra input z. See, for '...\n 'example, lik_binomial and gp_optim. ']);\n end\n \n switch param\n case 'latent'\n expf = exp(f);\n N = z;\n llg3 = N.*(expf.*(expf-1))./(1+expf).^3;\n end\nend\n\nfunction [logM_0, m_1, sigm2hati1] = lik_binomial_tiltedMoments(lik, y, i1, sigma2_i, myy_i, z)\n%LIK_BINOMIAL_TILTEDMOMENTS Returns the marginal moments for EP algorithm\n%\n% Description\n% [M_0, M_1, M2] = LIK_BINOMIAL_TILTEDMOMENTS(LIK, Y, I, S2,\n% MYY, Z) takes a likelihood structure LIK, succes counts Y,\n% numbers of trials Z, index I and cavity variance S2 and mean\n% MYY. Returns the zeroth moment M_0, mean M_1 and variance\n% M_2 of the posterior marginal (see Rasmussen and Williams\n% (2006): Gaussian processes for Machine Learning, page 55).\n% This subfunction is needed when using EP for inference with\n% non-Gaussian likelihoods.\n%\n% See also\n% GPEP_E\n \n% if isempty(z)\n% error(['lik_binomial -> lik_binomial_tiltedMoments: missing z!'... \n% 'Binomial likelihood needs the expected number of '...\n% 'occurrences as an extra input z. See, for '...\n% 'example, lik_binomial and gp_optim. ']);\n% end\n \n yy = y(i1);\n N = z(i1);\n logM_0=zeros(size(yy));\n m_1=zeros(size(yy));\n sigm2hati1=zeros(size(yy)); \n \n for i=1:length(i1)\n if isscalar(sigma2_i)\n sigma2ii = sigma2_i;\n else\n sigma2ii = sigma2_i(i);\n end\n \n % Create function handle for the function to be integrated\n % (likelihood * cavity) and useful integration limits\n [tf,minf,maxf]=init_binomial_norm(yy(i),myy_i(i),sigma2ii,N(i));\n \n % Integrate with quadrature\n RTOL = 1.e-6;\n ATOL = 1.e-10;\n [m_0, m_1(i), m_2] = quad_moments(tf,minf, maxf, RTOL, ATOL);\n if isnan(m_0)\n logM_0=NaN;\n return\n end\n sigm2hati1(i) = m_2 - m_1(i).^2;\n \n % If the second central moment is less than cavity variance\n % integrate more precisely. Theoretically for log-concave\n % likelihood should be sigm2hati1 < sigm2_i.\n if sigm2hati1(i) >= sigma2ii\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 >= sigm2_i\n % error('lik_binomial_tilted_moments: sigm2hati1 >= sigm2_i');\n % end\n end\n logM_0(i) = log(m_0);\n end\nend\n\n\nfunction [lpy, Ey, Vary] = lik_binomial_predy(lik, Ef, Varf, yt, zt)\n%LIK_BINOMIAL_PREDY Returns the predictive mean, variance and density of y\n%\n% Description \n% [LPY] = LIK_BINOMIAL_PREDY(LIK, EF, VARF YT, ZT)\n% Returns logarithm of the predictive density PY of YT, that is \n% p(yt | y, zt) = \\int p(yt | f, zt) p(f|y) df.\n% This requires also the succes counts YT, numbers of trials ZT.\n% This subfunction is needed when computing posterior predictive \n% distributions for future observations.\n%\n% [LPY, EY, VARY] = LIK_BINOMIAL_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 subfunction \n% is needed when computing posterior predictive distributions for \n% future observations.\n% \n%\n% See also \n% GPEP_PRED, GPLA_PRED, GPMC_PRED\n\n if isempty(zt)\n error(['lik_binomial -> lik_binomial_predy: missing z!'... \n 'Binomial likelihood needs the expected number of '...\n 'occurrences as an extra input z. See, for '...\n 'example, lik_binomial and gp_optim. ']);\n end\n \n if nargout > 1\n % Here we approximate the inverse logistic function by a linear combination of inverse probit function\n % logitinv(f) = a probit_inv(f/c1S) + (1 - a) probit_inv(f/c2s)\n % see Demidenko (2004). Mixed models: Theory and applications\n p1 = 0.4353; p2 = 0.5647; % these are a and (1 - a)\n c1S = 2.2967^2; c2S = 1.3017^2;\n \n z1 = Ef ./ sqrt(c1S + Varf);\n z2 = Ef ./ sqrt(c2S + Varf);\n \n % unconditional expectation \n p = (p1 .* normcdf(z1) + p2 .* normcdf(z2));\n Ey = zt .* p;\n \n % unconditional variance\n if any(zt ~= 1)\n nt = length(Ef);\n zz11 = zeros(nt, 1);\n zz12 = zeros(nt, 1);\n zz22 = zeros(nt, 1);\n \n for i = 1:length(Ef)\n zz11(i) = mvncdf([Ef(i) Ef(i)], [0 0], ... \n [Varf(i) + c1S Varf(i); Varf(i) Varf(i) + c1S]);\n \n zz12(i) = mvncdf([Ef(i) Ef(i)], [0 0], ...\n [Varf(i) + c1S Varf(i); Varf(i) Varf(i) + c2S]);\n \n zz22(i) = mvncdf([Ef(i) Ef(i)], [0 0], ...\n [Varf(i) + c2S Varf(i); Varf(i) Varf(i) + c2S]);\n \n end\n Ey12 = p1^2 * zz11 + 2*p1*p2 * zz12 + p2^2 * zz22;\n \n else\n Ey12 = 0;\n \n end\n \n % unconditional variance\n Vary = zt .* (p - Ey12) + zt.^2 .* (Ey12 - p.^2);\n \n % nt=length(Ef);\n % Ey=zeros(nt,1);\n % EVary = zeros(nt,1);\n % VarEy = zeros(nt,1);\n % for i1=1:nt\n % ci = sqrt(Varf(i1));\n % F = @(x)zt(i1)./(1+exp(-x)).*norm_pdf(x,Ef(i1),sqrt(Varf(i1)));\n % Ey(i1) = quadgk(F,Ef(i1)-6*ci,Ef(i1)+6*ci);\n % \n % F2 = @(x)zt(i1)./(1+exp(-x)).*(1-1./(1+exp(-x))).*norm_pdf(x,Ef(i1),sqrt(Varf(i1)));\n % EVary(i1) = quadgk(F2,Ef(i1)-6*ci,Ef(i1)+6*ci);\n % \n % F3 = @(x)(zt(i1)./(1+exp(-x))).^2.*norm_pdf(x,Ef(i1),sqrt(Varf(i1)));\n % VarEy(i1) = quadgk(F3,Ef(i1)-6*ci,Ef(i1)+6*ci) - Ey(i1).^2;\n % end\n % Vary = EVary+VarEy;\n end\n \n nt=length(yt);\n lpy=zeros(nt,1);\n if (size(Ef,2) > 1) && (size(Ef,2) > 1) && size(yt,2) == 1\n % Approximate integral with sum of grid points when using corrected\n % marginal posterior pf\n for i1=1:length(yt)\n py = arrayfun(@(f) exp(lik.fh.ll(lik, yt(i1), f, zt(i1))), Ef(i1,:));\n pf = Varf(i1,:)./sum(Varf(i1,:));\n lpy(i1) = log(sum(py.*pf));\n end\n else\n for i1=1:nt\n ci = sqrt(Varf(i1));\n F = @(x)exp(gammaln(zt(i1)+1)-gammaln(yt(i1)+1)-gammaln(zt(i1)-yt(i1)+1) + yt(i1).*log(1./(1+exp(-x))) + (zt(i1)-yt(i1)).*log(1-(1./(1+exp(-x))))).*norm_pdf(x,Ef(i1),sqrt(Varf(i1)));\n lpy(i1) = log(quadgk(F,Ef(i1)-6*ci,Ef(i1)+6*ci));\n end\n end\n \nend\n\nfunction prctys = lik_binomial_predprcty(lik, Ef, Varf, zt, prcty)\n%LIK_BINOMIAL_PREDPRCTY Returns the percentiled of predictive density of y\n%\n% Description \n% PRCTY = LIK_BINOMIAL_PREDPRCTY(LIK, EF, VARF YT, ZT)\n% Returns percentiles of the predictive density PY of YT, that is \n% This requires also the succes counts YT, numbers of trials ZT. This\n% subfunction is needed when using function gp_predprcty.\n%\n% See also \n% GP_PREDPCTY\n\n if isempty(zt)\n error(['lik_binomial -> lik_binomial_predprcty: missing z!'... \n 'Binomial likelihood needs the expected number of '...\n 'occurrences as an extra input z. See, for '...\n 'example, lik_binomial and gp_optim. ']);\n end\n \n opt=optimset('TolX',.5,'Display','off');\n nt=size(Ef,1);\n prctys = zeros(nt,numel(prcty));\n prcty=prcty/100;\n for i1=1:nt\n ci = sqrt(Varf(i1));\n for i2=1:numel(prcty)\n a=floor(fminbnd(@(a) (quadgk(@(f) binocdf(a,zt(i1),logitinv(f)).*norm_pdf(f,Ef(i1),ci),Ef(i1)-6*ci,Ef(i1)+6*ci,'AbsTol',1e-4)-prcty(i2)).^2,binoinv(prcty(i2),zt(i1),logitinv(Ef(i1)-1.96*ci)),binoinv(prcty(i2),zt(i1),logitinv(Ef(i1)+1.96*ci)),opt));\n if quadgk(@(f) binocdf(a,zt(i1),logitinv(f)).*norm_pdf(f,Ef(i1),ci),Ef(i1)-6*ci,Ef(i1)+6*ci,'AbsTol',1e-4)1 || isinf(delta) || isnan(delta) \n % Newton algorithm didn't work properly so do binary search\n modef=myy_i;\n a=modef-5.*sqrt(sigm2_i); b=modef+5.*sqrt(sigm2_i); delta=1;\n while ldg(a)<0\n a=a-5.*sqrt(sigm2_i);\n end\n while ldg(b)>0\n b=b+5.*sqrt(sigm2_i);\n end\n while delta > 0.1\n modef=(a+b)/2;\n if ldg(modef) > 0\n a=modef;\n else\n b=modef;\n end\n delta=b-a;\n end\n h=ldg2(modef);\n end\n % integrand limits based on Gaussian approximation at mode\n modes=sqrt(-1/h);\n minf=modef-4*modes;\n maxf=modef+4*modes;\n modeld=ld(modef);\n iter=0;\n % check that density at end points is low enough\n lddiff=12; % 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*modes;\n minld=ld(minf);\n iter=iter+1;\n step=step*2;\n if iter>100\n error(['lik_binomial -> init_binomial_norm: ' ...\n 'integration interval minimun not found ' ...\n 'even after looking hard!'])\n end\n end\n maxld=ld(maxf);\n iter=0;\n step=1;\n while maxld>(modeld-lddiff)\n maxf=maxf+step*modes;\n maxld=ld(maxf);\n iter=iter+1;\n step=step*2;\n if iter>100\n error(['lik_binomial -> init_binomial_norm: ' ...\n 'integration interval maximun not found ' ...\n 'even after looking hard!'])\n end\n end\n \n \n function integrand = binomial_norm(f)\n % Logit * Gaussian\n integrand = exp(ldconst + yy*log(1./(1.+exp(-f)))+(N-yy)*log(1-1./(1.+exp(-f)))...\n - 0.5 * (f-myy_i).^2./sigm2_i);\n% integrand = exp(ldconst ...\n% +yy*log(x)+(N-yy)*log(1-x) ...\n% -0.5*(f-myy_i).^2./sigm2_i);\n integrand(isnan(integrand)|isinf(integrand))=0;\n end\n \n function log_int = log_binomial_norm(f)\n % log(Binomial * Gaussian)\n % log_binomial_norm is used to avoid underflow when searching\n % integration interval\n \n log_int = ldconst + yy*log(1./(1.+exp(-f)))+(N-yy)*log(1-1./(1.+exp(-f)))...\n - 0.5 * (f-myy_i).^2./sigm2_i;\n% log_int = ldconst ...\n% -log(1+exp(-yy.*f)) ...\n% -0.5*(f-myy_i).^2./sigm2_i;\n log_int(isnan(log_int)|isinf(log_int))=-Inf;\n end\n \n function g = log_binomial_norm_g(f)\n % d/df log(Binomial * Gaussian)\n % derivative of log_binomial_norm\n g = -(f-myy_i)./sigm2_i - exp(-f).*(N-yy)./((1+exp(-f)).^2.*(1-1./(1+exp(-f)))) ...\n + exp(-f).*yy./(1+exp(-f));\n% g = yy./(exp(f*yy)+1)...\n% + (myy_i - f)./sigm2_i;\n end\n \n function g2 = log_binomial_norm_g2(f)\n % d^2/df^2 log(Binomial * Gaussian)\n % second derivate of log_binomial_norm\n g2 = - (1+exp(2.*f)+exp(f).*(2+N*sigm2_i)./((1+exp(f))^2*sigm2_i));\n% a=exp(f*yy);\n% g2 = -a*(yy./(a+1)).^2 ...\n% -1/sigm2_i;\n end\n \nend\n\nfunction p = lik_binomial_invlink(lik, f, z)\n%LIK_BINOMIAL_INVLINK Returns values of inverse link function\n% \n% Description \n% P = LIK_BINOMIAL_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 gp_predprctmu. \n%\n% See also\n% LIK_BINOMIAL_LL, LIK_BINOMIAL_PREDY\n \n p = logitinv(f);\nend\n\nfunction reclik = lik_binomial_recappend(reclik, ri, lik)\n%RECAPPEND Append the parameters to the record\n%\n% Description \n% RECLIK = GPCF_BINOMIAL_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 = 'Binomial';\n\n % Set the function handles\n reclik.fh.pak = @lik_binomial_pak;\n reclik.fh.unpak = @lik_binomial_unpak;\n reclik.fh.ll = @lik_binomial_ll;\n reclik.fh.llg = @lik_binomial_llg; \n reclik.fh.llg2 = @lik_binomial_llg2;\n reclik.fh.llg3 = @lik_binomial_llg3;\n reclik.fh.tiltedMoments = @lik_binomial_tiltedMoments;\n reclik.fh.invlink = @lik_binomial_invlink;\n reclik.fh.predprcty = @lik_binomial_predprcty;\n reclik.fh.predy = @lik_binomial_predy;\n reclik.fh.recappend = @likelih_binomial_recappend;\n return\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_binomial.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545425, "lm_q2_score": 0.6477982247516796, "lm_q1q2_score": 0.5466737493114692}} {"text": "function [x, info] = lewisCenter(f, x, opts)\n% x = LewisCenter(f, opts, x)\n% compute the analytic center for the domain {Ax=b} intersect the domain of f\n% \n% Input:\n% f - a ConvexProgram\n% x - a feasible initial point\n% opts - a structure for options with the following properties (optional)\n% MaxIter - maximum number of iterations\n% Output - maximum number of iterations\n% CentralityTol, FeasibilityTol - stop the following are satisfied\n% ||(A' * lambda - grad f(x)) / sqrt(hess)||_inf < CentralityTol\n% ||A x - b||_inf < FeasibilityTol\n% p - the parameter for lp Lewis weight\n% JLDim - the number of dimensions used in estimating leverage score\n% \n% Output:\n% x - It outputs the analytic center of f\n% info - a structure containing centrality, feasibility and iter.\n\ndefaultOpts = struct('MaxIter', 100, 'Output', @disp, 'CentralityTol', 0.1, 'FeasibilityTol', 1e-12, 'JLDim', 10, 'p', 4);\nif nargin >= 3\n opts = setField(defaultOpts, opts);\nelse\n opts = defaultOpts;\nend\nx = ddouble(x);\n\n%% prepare the printout\noutput = TableDisplay('Iter', '5i', 'PredStep', '13.2e', 'CorrStep', '13.2e', 'Centrality', '13.2e', 'Feasibility', '13.2e');\noutput.output = opts.Output;\noutput.header();\n\n%% initial parameters\nassert(nargin >= 2 && all(f.distance(x) > 0), 'a feasible inital point is required.');\n\nA = f.A; At = A'; b = f.b;\ny = 0*b;\nlastProgress = 0; % record the last iteration making progress\nbestCentrality = 1e32;\nd = size(f.A, 1); n = size(f.A, 2);\nw = (n-d)/n * ones(n, 1);\n\n%% find the central path\n[rs, rx, h] = updateResidual(x, y, w);\n\nfor iter = 1:opts.MaxIter\n % Compute the cholesky decomposition\n cholErr = f.solver.factorize(1./h);\n w_new = max(double(1-f.solver.leverageScore(opts.JLDim)), 0);\n w = (w + w_new)/2;\n \n % Compute the direction\n if (cholErr < f.solver.cholTol)\n v = f.solver.solve([A*(rs./h) rx]); %rs = A^T y - g; %rx = Ax - b;\n Atv = At * v;\n y = y - v(:,1);\n \n % y = y - (R\\(R'\\(A*(rs./hess))))\n % dx = (rs + At * (R\\(R'\\(rx - A*(rs./hess)))))./hess;\n\n dx = (rs - Atv(:,1))./h - Atv(:,2)./h;\n t = stepSize(x, dx, 0.95); % 0.95*(distance from x to the closest boundart in direction dx)\n x = x + t * dx; % move in direction dx with distance of t (measured in dx)\n \n [rs, rx, h] = updateResidual(x, y, w);\n \n centrality = max(abs(rs./sqrt(h))); %||(A^T y - grad \\phi)/sqrt(h)||_Inf\n feasibility = max(abs(rx)); %||Ax-b||_Inf\n if isempty(feasibility), feasibility = 0; end % Fix the case rx is []\n \n % Output the error\n o = struct('Iter', iter, 'PredStep', t, 'CorrStep', t, 'Centrality', centrality, 'Feasibility', feasibility);\n output.row(o);\n \n if (centrality < 0.9 * bestCentrality)\n bestCentrality = centrality;\n lastProgress = iter;\n end\n \n % Check stop criteria\n if centrality < opts.CentralityTol && feasibility < opts.FeasibilityTol\n break;\n end\n end\n \n if (iter > lastProgress + 10)\n break;\n end\n \n if (cholErr >= f.solver.cholTol)\n opts.Output('Failed due to numerical issue.');\n f.feasible = false;\n x = []; info = [];\n return;\n end\nend\n\ninfo = struct('centrality', centrality, 'feasibility', feasibility, 'iter', iter, 'hess', h);\n\nfunction t = stepSize(x, dx, factor)\n t = min(double(factor*min(f.barrier.distance(x, dx))),1); % min(Nan,1) = 1 for double\nend\n\nfunction [rs, rx, h, wp] = updateResidual(x, y, w)\n wp = w.^(1-2/opts.p);\n \n [gb, hb] = f.barrier.derivatives(x); % obtain gradient and hessian of log-barrier ftn \\phi(x) = -\\sum log(x-l) -\\sum log(u-x)\n % hp = diagonals of hessian matrix of log-barrier\n \n gb = gb.*wp;\n hb = hb.*wp;\n \n gc = zeros(size(gb), class(gb));\n hc = zeros(size(hb), class(hb));\n\n % Below if-end is skipped while running f.normalize() in sample.m (due to c=[])\n if ~isempty(f.c)\n gc = gc + f.c;\n end\n\n % Below if-end is skipped while running f.normalize() in sample.m (due to df=[])\n if ~isempty(f.df)\n gc_ = f.df(f.export(x));\n gc = gc + f.scale .* gc_(f.idx);\n\n hc_ = f.ddf(f.export(x));\n hc = hc + f.scale2 .* hc_(f.idx);\n end\n \n % Thus, g=gb and h=hb in f.normalize() \n g = gb + gc; h = hb + hc;\n \n rs = At * y - g;\n rx = A * x - b;\nend\n\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/sampling/BarrierRound/PolytopeSimplifier/lewisCenter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.6959583376458152, "lm_q1q2_score": 0.5465420544936382}} {"text": "function [Iq,in_avg,ext_avg,in_min,ext_max]=icassoStability(sR,L,graphmode)\n%function Iq=icassoStability(sR,L,graphmode)\n%\n%PURPOSE\n%\n%To compute and/or plot the stability (quality) indices of the ICA\n%estimate-clusters. \n%\n% Iq=avg(intra-cluster similarity) - avg(extra-cluster similarity)\n%\n%See publication Himberg et al. (2004), \"Validating the independent\n%components of neuroimaging time-series via clustering and\n%visualization\". NeuroImage, 22:3(1214-1222). Ideally, each ICA\n%estimate-cluster should have Iq=1. The smaller the value is, the\n%less stable (compact and isolated) the estimate-cluster is. \n%\n%EXAMPLES OF BASIC USAGE\n%\n% Iq=icassoStability(sR);\n%\n%returns the stability index for each estimate (centrotype) using\n%the default number of estimate-clusters. \n%\n% Iq=icassoStability(sR,13,'plotindex');\n%\n%...same as previous but also plots the values (in rank order) and\n%uses 13 estimate clusters instead of default. \n%\n%INPUT\n%\n%[An argument in brackets is optional. If it isn't given or it's\n% an empty matrix/string, the function will use a default value.] \n%\n% sR (struct) Icasso result data structure; clustering\n% must be readily computed. \n% [L] (scalar) number of clusters, default: (reduced) data\n% dimension \n% [graphmode] (string) 'none' (default) | 'plotindex' | 'plotstat' \n%\n%OUTPUTS\n%\n% Iq (Lx1 matrix) Iq(C) contains the index value for estimate C\n% (actually estimate-cluster C)\n%\n%DETAILS\n%\n%The intra-cluster similarities for cluster C mean the mutual\n%similarities between the estimates in C, and the extra-cluster\n%similarities for C are the similarities between the estimates in C\n%and the estimates not in C. The index is the average intra-cluster\n%similarity subtracted by the average intra-cluster similarity. \n%\n%In default graph mode 'none'\n% The function computes the index and returns it. No graphical\n% output. Iq(C) contains the index for cluster C (That is, for\n% estimates sR.cluster.partition(L,:)==C.\n%\n%In graph mode 'plotindex'\n% The function computes the quality index as in mode 'none' \n% and plots the index in the active axis (gca) as follows: \n% The X-axis shows the value of the index for clusters. The clusters\n% are ranked on the Y-axis in descending order according to the\n% index. The Y-axis legend shows the cluster number (the same as in\n% sR.cluster.partition(L,:)). The values are indicated by black\n% dots connected into each other by a dotted line. \n%\n%In graph mode 'plotstat'\n% As previous one but instead of the index,\n% some cluster statistics are shown: \n% Light red indicates the average intra-cluster similarity for a cluster \n% Light blue average extra-cluster\n% Clear red minimum intra-cluster \n% Clear blue maximum extra-cluster \n%\n%SEE ALSO\n% clusterquality\n% icassoViz\n% icassoShow\n\n%COPYRIGHT NOTICE\n%This function is a part of Icasso software library\n%Copyright (C) 2003-2005 Johan Himberg\n%\n%This program is free software; you can redistribute it and/or\n%modify it under the terms of the GNU General Public License\n%as published by the Free Software Foundation; either version 2\n%of the License, or any later version.\n%\n%This program is distributed in the hope that it will be useful,\n%but WITHOUT ANY WARRANTY; without even the implied warranty of\n%MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n%GNU General Public License for more details.\n%\n%You should have received a copy of the GNU General Public License\n%along with this program; if not, write to the Free Software\n%Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n\n% ver 1.2 100501 johan\n\nif nargin<2|isempty(L),\n L=icassoGet(sR,'rdim');\n disp([sprintf('\\n') 'Number of estimate-clusters not given: using (reduced)' ...\n\t ' data dimension.']);\nend\n\nif nargin<3 | isempty(graphmode),\n graphmode='none';\nend\n\nclusternumber=1:L;\npartition=sR.cluster.partition(L,:);\n\nfor i=1:L,\n NofEstimates(i)=sum(partition==i);\nend\n\n% compute cluster quality index\n\n[Iq,in_avg,ext_avg]=clusterquality('mean',sR.cluster.similarity,partition);\n[tmp,in_min,ext_max]=clusterquality('minmax',sR.cluster.similarity,partition);\n\n% Sort entries according to score\n\n[tmp,order]=sort(-Iq); \nscore=Iq(order);\nin_avg=in_avg(order); \next_avg=ext_avg(order); \nin_min=in_min(order); \next_max=ext_max(order);\nclusternumber=clusternumber(order);\nNofEstimates=NofEstimates(order);\n\n% make tick mark labels\nfor i=1:L,\n ticklabel{i}=num2str(clusternumber(i));\nend\n\n% Plot \nswitch lower(graphmode)\n case 'none'\n return;\n case 'plotindex'\n cla reset;\n h_score=plot(score,1:L,'o:');\n set(h_score,'color','k','markersize',8,'markerfacecolor','k');\n set(gca,'ytick',1:L,'yticklabel',ticklabel,'ydir','reve');\n ax=axis; \n \n if ax(1)<0,\n axis([ax(1) 1 0.5 L+.5]); \n else\n axis([0 1 0.5 L+.5]); \n end\n \n grid on;\n xlabel('I_q=avg(S(i)_{int})-avg(S(i)_{ext})');\n title('Stability index (I_q) for ICA estimate-clusters');\n case 'plotstat'\n cla reset;\n \n h_in_avg=barh(in_avg,0.7); hold on\n h_ext_max=barh(-ext_max,0.35); \n h_in_min=barh(in_min,0.35); \n h_ext_avg=barh(-ext_avg,0.7); \n \n axis on;\n set(h_in_avg,'facecolor',[1 0.7 0.7]); hold on;\n set(h_in_min,'facecolor',[1 0 0]);\n set(h_ext_avg,'facecolor',[0.7 0.7 1]);\n set(h_ext_max,'facecolor',[0 0 1]);\n axis([-1 1 0.5 L+.5]); \n \n set(gca,'ytick',1:L,'yticklabel',ticklabel,...\n\t 'ydir','reve','xtick',[-1 -.5 0 .5 1],...\n\t 'xgrid','on',...\n\t 'xticklabel',{'1' '0.5 ' '0' '0.5' '1'});\n \n title('Statistics on within- and between-cluster similarities');\n xlabel('clusters are ordered according to I_q=avg(S(i)_{int})-avg(S(i)_{ext})'); \n legend([h_in_avg(1),h_ext_avg(1),h_in_min(1),h_ext_max(1)],...\n\t {'mean S_{in}' 'mean S_{ex}' 'min S_{in}' 'max S_{ex}'},-1);\n otherwise\n error('Graphmode must be ''none'',''plotindex'' or ''plotstat''.');\nend\n\nylabel('Label')\n\n\n\n \n\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/icasso/icassoStability.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.5465420445890417}} {"text": "function p2 = project_3D_to_2D(p3)\nd = distmatrix(p3);\np2_0 = p3(:,1:2);\nfun = @(x)myfunc(x,d);\n\nwarnid = {'optim:fsolve:NonSquareSystem'};\nfor ii = 1:length(warnid)\n warning('OFF', warnid{ii});\nend\n\np2 = fsolve(fun, p2_0, optimset('Display','off'));\n\nfor ii = 1:length(warnid)\n warning('ON', warnid{ii});\nend\n\n\n\n\n% -------------------------------------------------------\nfunction F = myfunc(p, d)\nF = [];\nkk = 1;\nc = 1.2;\nfor ii = 1:size(d,1)\n for jj = 1:size(d,2)\n if d(ii,jj) == 0\n continue\n end\n F(kk) = sqrt((p(ii,1) - p(jj,1))^2 + (p(ii,2) - p(jj,2))^2) - d(ii,jj)*c;\n kk = kk+1;\n end\nend\n\n\n\n% -------------------------------------------------------------------\nfunction d = distmatrix(varargin)\n\nd=[];\n\nv1 = double(varargin{1});\nif size(v1,2) == 2\n v1 = [v1, zeros(size(v1,1),1)];\nend\n\nif length(varargin)==1\n \n n = size(v1,1);\n d = zeros(n);\n for i = 1:n\n for j = i+1:n \n d(i,j) = ((v1(i,1) - v1(j,1))^2 + ...\n (v1(i,2) - v1(j,2))^2 + ...\n (v1(i,3) - v1(j,3))^2)^0.5;\n end \n end\n\nelseif length(varargin)==2\n\n v2 = double(varargin{2});\n m = size(v1,1);\n n = size(v2,1);\n d = zeros(m,n); \n for i = 1:m\n for j=1:n\n d(i,j) = ((v1(i,1) - v2(j,1))^2 + ...\n (v1(i,2) - v2(j,2))^2 + ...\n (v1(i,3) - v2(j,3))^2)^0.5;\n end \n end \n\nend\n\n", "meta": {"author": "BUNPC", "repo": "Homer3", "sha": "d0fac4b22d1069eaa5cba268a225eb117ddcdca1", "save_path": "github-repos/MATLAB/BUNPC-Homer3", "path": "github-repos/MATLAB/BUNPC-Homer3/Homer3-d0fac4b22d1069eaa5cba268a225eb117ddcdca1/Utils/Shared/project_3D_to_2D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5465313299847161}} {"text": "function [r, pol, res, zer, zj, fj, wj, errvec, wt] = aaa(F, varargin)\n%AAA AAA and AAA-Lawson (near-minimax) real or complex rational approximation.\n% R = AAA(F, Z) computes the AAA rational approximant R (function handle) to\n% data F on the set of sample points Z. F may be given by its values at Z,\n% or as a function handle or chebfun. R = AAA(F, Z, 'degree', N) attempts to\n% compute the minimax approximation of degree N (i.e., rational type (N,N)).\n%\n% [R, POL, RES, ZER] = AAA(F, Z) returns vectors of poles, residues, and zeros\n% of R.\n%\n% [R, POL, RES, ZER, ZJ, FJ, WJ] = AAA(F, Z) also returns the vectors of\n% support points ZJ, approximation values FJ = r(ZJ), and weights WJ of the\n% barycentric representation of R. \n%\n% [R, POL, RES, ZER, ZJ, FJ, WJ, ERRVEC] = AAA(F, Z) also returns the vector\n% of errors ||f-r||_infty in successive iterative steps of AAA. Note that the\n% rational degrees are not 1,...,length(ERRVEC) but 0,...,length(ERRVEC)-1.\n%\n% R = AAA(F, Z, NAME, VALUE) sets the following parameters:\n% - 'tol', TOL: relative tolerance (default TOL = 1e-13),\n% - 'degree', N: maximal degree (default N = 99). \n% The output rational approximant will be of degree at most N. Like\n% 'mmax', N+1, except that Lawson is turned on by default: see below.\n% - 'mmax', MMAX: maximal number of terms in the barycentric representation\n% (default MMAX = 100). R will be of degree at most MMAX-1. Like\n% 'degree', MMAX-1, except that Lawson is not turned on by default.\n% - 'dom', DOM: domain (default DOM = [-1, 1]). No effect if Z is provided.\n% - 'cleanup', 'off' or 0: turns off automatic removal of Froissart doublets.\n% - 'cleanuptol', CLEANUPTOL: cleanup tolerance (default CLEANUPTOL = TOL).\n% Poles with residues less than this number times the geometric mean size\n% of F times the minimum distance to Z are deemed spurious by the cleanup\n% procedure. If TOL = 0, then CLEANUPTOL defaults to 1e-13.\n% - 'lawson', NLAWSON: take NLAWSON iteratively reweighted least-squares steps\n% to bring approximation closer to minimax. Specifying NLAWSON = 0 \n% ensures there is no Lawson iteration. See next paragraph.\n%\n% If 'degree' is specified and 'lawson' is not, AAA attempts to find a minimax\n% approximant of degree N by AAA-Lawson iteration. This will generally be\n% successful only if the minimax error is well above machine precision, and\n% is more reliable for complex problems than real ones. If 'degree' and \n% 'lawson' are both specified, then exactly NLAWSON Lawson steps are taken\n% (so NLAWSON = 0 corresponds to AAA approximation with no Lawson iteration).\n% The final weight vector WT of the Lawson iteration is available with\n% [R, POL, RES, ZER, ZJ, FJ, WJ, ERRVEC, WT] = AAA(F, Z).\n%\n% Note that R may have fewer than N poles and zeros. This may happen, for\n% example, if N is too large, or if F is even and N is odd, or if F is odd\n% and N is even.\n%\n% One can also execute R = AAA(F), with no specification of a set Z. If F is\n% a vector, this is equivalent to R = AAA(F, Z) with\n% Z = LINSPACE(-1, 1, LENGTH(F)). If F is a function handle, AAA attempts\n% to resolve F on [-1,1] by default.\n%\n% This standalone code works in GNU Octave as well as MATLAB.\n%\n% Examples:\n% r = aaa(@exp); xx = linspace(-1,1); plot(xx,r(xx)-exp(xx))\n%\n% r = aaa(@exp,'degree',4); xx = linspace(-1,1); plot(xx,r(xx)-exp(xx))\n%\n% X = linspace(-1,1,30); r = aaa(gamma(X),X);\n% fplot(r,[-5,5]), axis([-5 5 -15 15]), grid on \n%\n% Z = exp(2i*pi*linspace(0,1,500)); \n% [r,pol,res] = aaa(@tan,Z); disp([pol res])\n%\n% X = linspace(-1,1,1000); F = tanh(20*X);\n% subplot(1,2,1)\n% r = aaa(F,X,'degree',15,'lawson',0); plot(X,F-r(X)), hold on\n% r = aaa(F,X,'degree',15); plot(X,F-r(X)), hold off\n% \n% Z = exp(1i*pi*linspace(-1,1,1000)); G = exp(Z);\n% subplot(1,2,2)\n% r = aaa(G,Z,'degree',3,'lawson',0); plot(G-r(Z)), axis equal, hold on\n% r = aaa(G,Z,'degree',3); plot(G-r(Z)), axis equal, hold off\n%\n% References on AAA and AAA-Lawson, respectively:\n%\n% [1] Y. Nakatsukasa, O. Sete, and L. N. Trefethen, \"The AAA algorithm\n% for rational approximation\", SIAM J. Sci. Comp. 40 (2018), A1494-A1522.\n%\n% [2] Y. Nakatsukasa and L. N. Trefethen, An algorithm for real and\n% complex rational minimax approximation, SIAM J. Sci. Comp. 42 (2020),\n% A3157-A3179.\n%\n% See also AAATRIG, CF, CHEBPADE, MINIMAX, PADEAPPROX, RATINTERP.\n\n% Copyright 2023 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\n% Parse inputs:\n[F, Z, M, dom, tol, mmax, cleanup_flag, cleanup_tol, needZ, mmax_flag, ...\n nlawson, degree_flag, degree] = parseInputs(F, varargin{:});\n\nif ( needZ )\n % Z was not provided. Try to resolve F on its domain.\n [r, pol, res, zer, zj, fj, wj, errvec] = ...\n aaa_autoZ(F, dom, tol, mmax, cleanup_flag, cleanup_tol, mmax_flag, ...\n nlawson, degree_flag, degree);\n return\nend\n\n% Remove infinite or NaN function values and repeated entries:\ntoKeep = ~isinf(F) & ~isnan(F);\nF = F(toKeep); Z = Z(toKeep);\n[Z, uni] = unique(Z,'stable'); F = F(uni);\n\n% Initialization for AAA iteration:\nM = length(Z);\nabstol = tol*norm(F, inf); % Absolute tolerance\nJ = (1:M)';\nzj = []; fj = []; C = []; A = [];\nerrvec = [];\nR = mean(F)*ones(size(J));\n\n% AAA iteration:\nfor m = 1:mmax\n % Introduce next support point:\n [~, jj] = max(abs(F(J) - R(J))); % Select next support point\n zj = [zj; Z(J(jj))]; % Update support points\n fj = [fj; F(J(jj))]; % Update data values\n C = [C 1./(Z - Z(J(jj)))]; % Next column of Cauchy matrix\n J(jj) = []; % Update index vector\n A = [A, (F-fj(end)).*C(:,end)]; % Update Loewner matrix\n\n % Compute weights:\n if ( length(J) >= m ) % The usual tall-skinny case\n [~, S, V] = svd(A(J,:), 0); % Reduced SVD\n s = diag(S);\n mm = find( s == min(s) ); % Treat case of multiple min sing val\n nm = length(mm);\n wj = V(:,mm)*ones(nm,1)/sqrt(nm); % Aim for non-sparse wt vector\n elseif ( length(J) >= 1 )\n V = null(A(J,:)); % Fewer rows than columns\n nm = size(V,2); \n wj = V*ones(nm,1)/sqrt(nm); % Aim for non-sparse wt vector\n else\n wj = ones(m,1)/sqrt(m); % No rows at all (needed for Octave)\n end\n \n % Compute rational approximant:\n i0 = find(wj~=0); % Omit columns with wj = 0\n N = C(:,i0)*(wj(i0).*fj(i0)); % Numerator\n D = C(:,i0)*wj(i0); % Denominator\n R = N./D;\n Dinf = isinf(D);\n R(Dinf) = F(Dinf); % Interpolate at supp pts with wj~=0\n \n % Check if converged:\n maxerr = norm(F - R, inf);\n errvec = [errvec; maxerr];\n if ( maxerr <= abstol )\n break\n end\nend\nmaxerrAAA = maxerr; % Error at end of AAA \n\n% We now enter Lawson iteration: barycentric IRLS = iteratively reweighted\n% least-squares if 'lawson' is specified with NLAWSON > 0 or 'mmax' is\n% specified and 'lawson' is not. In the latter case the number of steps\n% is chosen adaptively. Note that the Lawson iteration is unlikely to be\n% successful when the errors are close to machine precision.\n\nwj0 = wj; fj0 = fj; % Save params in case Lawson fails\nwt = NaN(M,1); wt_new = ones(M,1);\nif ( nlawson > 0 ) % Lawson iteration\n\n maxerrold = maxerrAAA;\n maxerr = maxerrold;\n nj = length(zj);\n A = [];\n for j = 1:nj % Cauchy/Loewner matrix\n A = [A 1./(Z-zj(j)) F./(Z-zj(j))];\n end\n for j = 1:nj\n [i,~] = find(Z==zj(j)); % support pt rows are special\n A(i,:) = 0;\n A(i,2*j-1) = 1;\n A(i,2*j) = F(i);\n end\n stepno = 0;\n while ( (nlawson < inf) && (stepno < nlawson) ) || ...\n ( (nlawson == inf) && (stepno < 20) ) || ...\n ( (nlawson == inf) && (maxerr/maxerrold < .999) && (stepno < 1000) ) \n stepno = stepno + 1;\n wt = wt_new;\n W = spdiags(sqrt(wt),0,M,M);\n [~,~,V] = svd(W*A,0);\n c = V(:,end);\n denom = zeros(M,1); num = zeros(M,1);\n for j = 1:nj\n denom = denom + c(2*j)./(Z-zj(j));\n num = num - c(2*j-1)./(Z-zj(j));\n end\n R = num./denom;\n for j = 1:nj\n [i,~] = find(Z==zj(j)); % support pt rows are special\n R(i) = -c(2*j-1)/c(2*j);\n end\n err = F - R; abserr = abs(err);\n wt_new = wt.*abserr; wt_new = wt_new/norm(wt_new,inf);\n maxerrold = maxerr;\n maxerr = max(abserr);\n end\n wj = c(2:2:end);\n fj = -c(1:2:end)./wj;\n % If Lawson has not reduced the error, return to pre-Lawson values.\n if ( (maxerr > maxerrAAA) && (nlawson == Inf) )\n wj = wj0; fj = fj0; \n end\nend\n\n% Remove support points with zero weight:\nI = find(wj == 0);\nzj(I) = []; wj(I) = []; fj(I) = [];\n\n% Construct function handle and compute poles, residues and zeros:\nr = @(zz) reval(zz, zj, fj, wj);\n[pol, res, zer] = prz(zj, fj, wj);\n\nif ( cleanup_flag == 1 && nlawson == 0 ) % Remove Froissart doublets\n [r, pol, res, zer, zj, fj, wj] = ...\n cleanup(r, pol, res, zer, zj, fj, wj, Z, F, cleanup_tol);\nelseif ( cleanup_flag == 2 && nlawson == 0 ) % Alternative cleanup. Currently\n a.zj = zj; a.fj = fj; a.wj = wj; % an undocumented feature,\n a.Z = Z; a.F = F; % pending further investigation.\n a.cleanup_tol = max(cleanup_tol, eps);\n c = cleanup2(a);\n zj = c.zj; fj = c.fj; wj = c.wj;\n r = @(zz) reval(zz, zj, fj, wj);\n [pol, res, zer] = prz(zj, fj, wj);\nend\n\nend % of AAA()\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% PARSEINPUTS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [F, Z, M, dom, tol, mmax, cleanup_flag, cleanup_tol, ...\n needZ, mmax_flag, nlawson, degree_flag, degree] = parseInputs(F, varargin)\n\n% Check if F is empty:\nif ( isempty(F) )\n error('AAA:emptyF', 'No function given.')\nelseif ( isa(F, 'chebfun') )\n if ( size(F, 2) ~= 1 )\n error('AAA:nColF', 'Input chebfun must have one column.')\n end\nend\n\n% Sample points:\nif ( ~isempty(varargin) && isfloat(varargin{1}) )\n % Z is given.\n Z = varargin{1};\n if ( isempty(Z) )\n error('AAA:emptyZ', ...\n 'If sample set is provided, it must be nonempty.')\n end\n varargin(1) = [];\nend\n\n% Set defaults for other parameters:\ntol = 1e-13; % Relative tolerance\nmmax = 100; % Maximum number of terms\ndegree = NaN; % Specified degree\ncleanup_tol = 1e-13; % Cleanup tolerance\nnlawson = Inf; % Number of Lawson steps (Inf means adaptive)\n% Domain:\nif ( isa(F, 'chebfun') )\n dom = F.domain([1, end]);\nelse\n dom = [-1, 1];\nend\ncleanup_flag = 1; % Cleanup on\nmmax_flag = 0; % Checks if mmax manually specified\ndegree_flag = 0; % Checks if degree specified\ncleanup_set = 0; % Checks if cleanup_tol manually specified\nwhile ( ~isempty(varargin) ) % Check if parameters have been provided\n if ( strncmpi(varargin{1}, 'tol', 3) )\n if ( isfloat(varargin{2}) && isequal(size(varargin{2}), [1, 1]) )\n tol = varargin{2};\n if ( ~cleanup_set && tol > 0 ) % If not set, set cleanup_tol to tol\n cleanup_tol = tol;\n end\n end\n varargin([1, 2]) = [];\n \n elseif ( strncmpi(varargin{1}, 'degree', 6) )\n if ( isfloat(varargin{2}) && isequal(size(varargin{2}), [1, 1]) )\n if ( mmax_flag == 1 ) && ( mmax ~= varargin{2}+1 )\n error('AAA:degmmaxmismatch', ' mmax must equal degree+1.')\n end \n degree = varargin{2};\n mmax = degree + 1;\n mmax_flag = 1; \n degree_flag = 1;\n end\n varargin([1, 2]) = [];\n \n elseif ( strncmpi(varargin{1}, 'mmax', 4) )\n if ( isfloat(varargin{2}) && isequal(size(varargin{2}), [1, 1]) ) \n if ( mmax_flag == 1 ) && ( mmax ~= varargin{2}) \n error('AAA:degmmaxmismatch', ' mmax must equal degree+1.')\n end\n mmax = varargin{2};\n mmax_flag = 1;\n end\n varargin([1, 2]) = [];\n \n elseif ( strncmpi(varargin{1}, 'lawson', 6) )\n if ( isfloat(varargin{2}) && isequal(size(varargin{2}), [1, 1]) )\n nlawson = varargin{2};\n end\n varargin([1, 2]) = [];\n \n elseif ( strncmpi(varargin{1}, 'dom', 3) )\n if ( isfloat(varargin{2}) && isequal(size(varargin{2}), [1, 2]) )\n dom = varargin{2};\n end\n varargin([1, 2]) = [];\n if ( isa(F, 'chebfun') )\n if ( ~isequal(dom, F.domain([1, end])) )\n warning('AAA:dom', ...\n ['Given domain does not match that of the chebfun.\\n', ...\n 'Results may be inaccurate.'])\n end\n end\n \n elseif ( strncmpi(varargin{1}, 'cleanuptol', 10) )\n if ( isfloat(varargin{2}) && isequal(size(varargin{2}), [1, 1]) )\n cleanup_tol = varargin{2};\n cleanup_set = 1;\n end\n varargin([1, 2]) = [];\n\n elseif ( strncmpi(varargin{1}, 'cleanup', 7) )\n if ( strncmpi(varargin{2}, 'off', 3) || ( varargin{2} == 0 ) )\n cleanup_flag = 0;\n elseif ( varargin{2} == 2 ) % Alternative cleanup\n cleanup_flag = 2;\n end\n varargin([1, 2]) = [];\n \n else\n error('AAA:UnknownArg', 'Argument unknown.')\n end\nend\n\n% Deal with Z and F:\nif ( ~exist('Z', 'var') && isfloat(F) )\n % F is given as data values, pick same number of sample points:\n Z = linspace(dom(1), dom(2), length(F)).';\nend\n\nif ( exist('Z', 'var') )\n % Z is given:\n needZ = 0;\n \n % Work with column vector:\n Z = Z(:);\n M = length(Z);\n \n % Function values:\n if ( isa(F, 'function_handle') || isa(F, 'chebfun') )\n % Sample F on Z:\n F = F(Z);\n elseif ( isnumeric(F) )\n % Work with column vector and check that it has correct length.\n F = F(:);\n if ( length(F) ~= M )\n error('AAA:lengthFZ', ...\n 'Inputs F and Z must have the same length.')\n end\n elseif ( ischar(F) )\n % F is given as a string input. Convert it to a function handle.\n F = inline(vectorize(F));\n F = F(Z);\n else\n error('AAA:UnknownF', 'Input for F not recognized.')\n end\n \nelse\n % Z was not given. Set flag that Z needs to be determined.\n % Also set Z and M since they are needed as output.\n needZ = 1;\n Z = [];\n M = length(Z);\nend\n\nif ( ~degree_flag && (nlawson == Inf) )\n nlawson = 0; \nend\n\nend % End of PARSEINPUTS.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% CLEANUP %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [r, pol, res, zer, z, f, w] = ...\n cleanup(r, pol, res, zer, z, f, w, Z, F, cleanup_tol) \n% Remove spurious pole-zero pairs.\n\n% Find negligible residues:\nif any(F)\n geometric_mean_of_absF = exp(mean(log(abs(F(F~=0)))));\nelse\n geometric_mean_of_absF = 0;\nend\nZdistances = NaN(size(pol));\nfor j = 1:length(Zdistances)\n Zdistances(j) = min(abs(pol(j)-Z));\nend\nii = find(abs(res)./Zdistances < cleanup_tol * geometric_mean_of_absF);\nni = length(ii);\nif ( ni == 0 )\n return\nelseif ( ni == 1 )\n warning('AAA:Froissart','1 Froissart doublet');\nelse\n warning('AAA:Froissart',[int2str(ni) ' Froissart doublets']);\nend\n\n% For each spurious pole find and remove closest support point:\nfor j = 1:ni\n azp = abs(z-pol(ii(j)));\n jj = find(azp == min(azp),1);\n \n % Remove support point(s):\n z(jj) = []; f(jj) = [];\nend\n\n% Remove support points z from sample set:\nfor jj = 1:length(z)\n F(Z == z(jj)) = [];\n Z(Z == z(jj)) = [];\nend\nm = length(z);\nM = length(Z);\n\n% Build Loewner matrix:\nSF = spdiags(F, 0, M, M);\nSf = diag(f);\nC = 1./(Z-z.'); % Cauchy matrix.\nA = SF*C - C*Sf; % Loewner matrix.\n\n% Solve least-squares problem to obtain weights:\n[~, ~, V] = svd(A, 0);\nw = V(:,m);\n\n% Build function handle and compute poles, residues and zeros:\nr = @(zz) reval(zz, z, f, w);\n[pol, res, zer] = prz(z, f, w);\n\nend % End of CLEANUP.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% CLEANUP2 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction c = cleanup2(a)\n%% Alternative cleanup procedure to remove spurious pole-zero pairs.\n% This considers pole-zero distances. Stefano Costa, August 2022.\n\nz = a.zj; f = a.fj; w = a.wj;\n[pol, res, zer] = prz(z, f, w);\n\ncleanup_tol = a.cleanup_tol;\n\nniter = 0;\nwhile(true)\n niter = niter+1;\n Z = a.Z; F = a.F;\n ii = [];\n for jj = 1:length(pol)\n dz = min(abs(zer-pol(jj))); if isempty(dz), dz = 1e100; end\n dS = abs(Z-pol(jj));\n ds = min(dS);\n if any(F)\n q = 4*pi*abs(F).*dS;\n Q = mean(q); % Arithmetic mean\n else\n Q = 0;\n end\n R = 8*cleanup_tol*Q/(4*pi); % Equivalent residue value\n \n % Conditions to expunge poles\n % Expunge if either minimum distance is zero\n if (ds==0) || (dz==0)\n ii = [ii; jj];\n % Expunge if Z is a real interval\n elseif isreal(Z) && (abs(imag(pol(jj)))=min(Z)) && (real(pol(jj))<=max(Z))\n ii = [ii; jj];\n % Expunge if Z is the unit disk\n elseif all(abs(Z)==1) && (abs(abs(pol(jj))-1),\n% arXiv, 2022\n%\n\n% generate clusters\nif nargin == 1 || ~isnumeric(clusterId), clusterId = ones(length(grains),1); end\nnotZero = all(clusterId>0,2);\ncSize = accumarray(clusterId(notZero,:),grains.grainSize(notZero));\nic = find(cSize > get_option(varargin,'minClusterSize',100));\n\n% prepare output\nsz = [max(clusterId),1];\nomega = nan(sz);\nrel = zeros(sz);\n\n% extract grain geometry\nV = grains.boundary.V;\nF = grains.boundary.F;\nI_BG = grains.boundary.I_FG;\ngrainId = grains.id;\n\n% get method to use\nuseHist = check_option(varargin,'hist');\nuseCalliper = check_option(varargin,'calliper');\n\n% loop over all relevant clusters\nfor i = 1:length(ic)\n\n % combine grains according to clusterIndex\n [sub{1:size(clusterId,2)}] = ind2sub(sz,ic(i));\n ind = all(clusterId == [sub{:}],2);\n \n % the boundary segments\n lF = F(any(I_BG(:,grainId(ind)),2),:);\n\n % shifted into the origin\n lS = V(lF(:,1),:) - V(lF(:,2),:);\n\n if isempty(lF), continue; end\n\n if useHist % density function method\n\n rho = atan2(lS(:,2),lS(:,1));\n \n %fun = calcDensity(rho, 'weights',sqrt(sum(lS.^2,2)),'periodic','sigma',10*degree);\n fun = calcDensity(rho, 'weights',vecnorm(lS,2,2),'periodic','sigma',10*degree);\n fun.antipodal = true;\n\n phi = linspace(0,2*pi,360);\n [m,ind] = max(real(fun.eval(phi)));\n \n omega(ic(i)) = phi(ind);\n rel(ic(i)) = (m-1)/m;\n\n else % characteristic shape method\n \n %cS = shape2d.byFV(F(any(I_BG(:,ind),2),:),V,'noSimplify');\n %[omega(ic(i)),a,b] = principalComponents(cS);\n %traces(ic(i)) = cS.caliper('shortestPerp'); % this is a bit more precise but slower\n\n % the following lines are from shape2d.byFV\n % just consider one direction\n fcond = lS(:,2)<0;\n lS(fcond,:)=lS(fcond,:).*-1;\n dxy = [lS; -lS];\n\n % sort segments according to angle\n [~,id]= sort(atan2(dxy(:,2),dxy(:,1)));\n dxy = dxy(id,:);\n\n % sum up\n xyn = cumsum(dxy);\n\n % shift again\n xyn = [xyn(:,1) - mean(xyn(:,1)) xyn(:,2) - mean(xyn(:,2))];\n \n if useCalliper\n \n mid = round(size(xyn,1)/2);\n dxyn = xyn - [xyn(1+mid:end,:);xyn(1:mid,:)];\n delta = vecnorm(dxyn,2,2);\n\n % minimum and maximum Ferret diameter\n a = max(delta); [b,ib] = min(delta);\n \n % use vector perpendicular to short axis\n omega(ic(i)) = pi/2 + atan2(dxyn(ib,2),dxyn(ib,1));\n \n else\n \n % the following lines are taken from grain2d/principleComponent\n % compute length of line segments\n dist = sqrt(sum((xyn(1:end-1,:) - xyn(2:end,:)).^2,2));\n dist = 0.5*(dist(1:end) + [dist(end);dist(1:end-1)]);\n \n % weight vertices according to half the length of the adjacent faces\n xyn = xyn(1:end-1,:) .* [dist,dist] .* sum(xyn(1:end-1,:).^2,2).^(0.25);\n \n % compute eigen values and vectors\n [ew, omega(ic(i))] = eig2(xyn' * xyn);\n \n % halfaxes are square roots of the eigenvalues\n b = sqrt(ew(1)); a = sqrt(ew(2));\n end\n rel(ic(i)) = (a-b)./a;\n end\n\nend\n\ntraces = vector3d.byPolar(pi/2,omega,'antipodal');\n", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/EBSDAnalysis/@grain2d/calcTraces.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182186, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.5464246927693638}} {"text": "close all\nclear\n\n%--------------------------------------iMPC-DCBF------------------------------------------------\nxo = 0;\nyo = 0;\nr = 1;\nN = 24;%Number of horizon\nK1 = 1000;%Maximum iteration times, jmax\nK = 1000;%Maximum iteration times, jmax\ndt = 0.1;\ngamma1 = 4;\ngamma2 = 4;\nnsim = 100;%Total time steps\nItera_x = [];%This is to store iterative convergence of location x\nItera_y = [];%This is to store iterative convergence of location y\nItera_theta = [];%This is to store iterative convergence of orientation theta\nItera_v = [];%This is to store iterative convergence of speed v\n\n% Constraints\n\numin = [-7; -5; -inf; -inf;];\numax = [7; 5; Inf; Inf];\nxmin = [-10; -10; -10; -10];\nxmax = [ 10; 10; 10; 10];\n\n% Objective function\nQ = diag([10 10 10 10]);\nQN = Q;\nR = 1 * eye(4);\nR(3,3) = 1000;\nR(4,4) = 1000;\n% Initial and reference states\nx0 = [-3 0 0 0];\nxr = [3; 0.01; 0; 0];\nur = [0; 0; 1; 1];\n\n% Dynamic system initialization\nBB = [0 0 0 0;0 0 0 0;dt 0 0 0;0 dt 0 0];\n\n% Convex MPC frame\n[nx, nu] = size(BB);\n% Initialize states set (x00,x01,,,x0N)\nx_0 = [];\nx0 = x0';\nu_0 = zeros(nu, N);\nu0 = zeros(nu, 1);% we may need to change this for a better warm-up start\nimpc = zeros(nx, nsim + 1);\nimpc(:, 1) = x0;\nx0new = x0;\nfor i=1 : (N+1)\n x_0 = [x_0 x0new];\n x0new = [dt*x0new(4)*cos(x0new(3))+x0new(1);dt*x0new(4)*sin(x0new(3))+x0new(2);dt*u0(1)+x0new(3);dt*u0(2)+x0new(4)];\nend\n\nabc = tangentline(x_0, r);\nAcbf = cbfmat(abc, nx, nu, dt, gamma1, x0);\nlcbf = -abc(3, :);\nlcbf(1) = [];\nlcbf = lcbf';\nucbf = inf * ones(N, 1);\nA2cbf = cbfmat2(abc, nx, nu, dt, gamma1, gamma2, x0);\nlcbf2 = getlcbf2(abc, dt, gamma1, gamma2);\nucbf2 = inf * ones(N-1, 1);\n\n% Cast MPC problem to a QP: x = (x(0),x(1),...,x(N),u(0),...,u(N-1))\n% - quadratic objective\nP = blkdiag( kron(speye(N), Q), QN, kron(speye(N), R) );\n% - linear objective\nq = [repmat(-Q*xr, N, 1); -QN*xr; repmat(-R*ur, N, 1)];\n% - linear dynamics\nAx = getax(x_0, dt, N, nx);\nBu = kron([sparse(1, N); speye(N)], BB);\nCx = getcx(x_0, u_0, dt, N, nx);\nAeq = [Ax, Bu];\nleq = [-x0; -Cx];\nueq = leq;\n% - input and state constraints\nAineq = speye((N+1)*nx + N*nu);\nlineq = [repmat(xmin, N+1, 1); repmat(umin, N, 1)];\nuineq = [repmat(xmax, N+1, 1); repmat(umax, N, 1)];\n\n% - OSQP constraints\nA = [Aeq; Aineq; Acbf; A2cbf];%Highest order mcbf=2\nl = [leq; lineq; lcbf; lcbf2];\nu = [ueq; uineq; ucbf; ucbf2];\n\n% Create an OSQP object\nprob = osqp;\n% Setup workspace\nprob.setup(P, q, A, l, u, 'warm_start', true);\n% Solve\nres = prob.solve();\n\n% Check solver status\nif ~strcmp(res.info.status, 'solved')\n error('OSQP did not solve the problem!')\nend\nctrlx = res.x(1:(N+1)*nx);\nctrlu = res.x((N+1)*nx+1:(N+1)*nx+N*nu);\n\nfor j = 1 : (K1-1)\n storagex = ctrlx;\n storageu = ctrlu;\n x_0 = trans(x0, ctrlx, nx, N+1);\n u_0 = transu(ctrlu, nu, N);\n abc = tangentline(x_0, r);\n Acbf = cbfmat(abc, nx, nu, dt, gamma1, x0);\n lcbf = -abc(3, :);\n lcbf(1) = [];\n lcbf = lcbf';\n ucbf = inf * ones(N, 1);\n A2cbf = cbfmat2(abc, nx, nu, dt, gamma1, gamma2, x0);\n lcbf2 = getlcbf2(abc, dt, gamma1, gamma2);\n ucbf2 = inf * ones(N-1, 1);\n % Cast MPC problem to a QP: x = (x(0),x(1),...,x(N),u(0),...,u(N-1))\n % - quadratic objective\n P = blkdiag( kron(speye(N), Q), QN, kron(speye(N), R) );\n % - linear objective\n q = [repmat(-Q*xr, N, 1); -QN*xr; repmat(-R*ur, N, 1)];\n % - linear dynamics\n Ax = getax(x_0, dt, N, nx);\n Bu = kron([sparse(1, N); speye(N)], BB);\n Cx = getcx(x_0, u_0, dt, N, nx);\n Aeq = [Ax, Bu];\n leq = [-x0; -Cx];\n ueq = leq;\n % - input and state constraints\n Aineq = speye((N+1)*nx + N*nu);\n lineq = [repmat(xmin, N+1, 1); repmat(umin, N, 1)];\n uineq = [repmat(xmax, N+1, 1); repmat(umax, N, 1)];\n\n % - OSQP constraints\n A = [Aeq; Aineq; Acbf; A2cbf];%Highest order mcbf=2\n l = [leq; lineq; lcbf; lcbf2];\n u = [ueq; uineq; ucbf; ucbf2];\n % Create an OSQP object\n prob = osqp;\n % Setup workspace\n prob.setup(P, q, A, l, u, 'warm_start', true);\n % Solve\n res = prob.solve();\n\n % Check solver status\n if ~strcmp(res.info.status, 'solved')\n error('OSQP did not solve the problem!')\n end\n ctrlx = res.x(1:(N+1)*nx);\n ctrlu = res.x((N+1)*nx+1:(N+1)*nx+N*nu);\n testx = (storagex - ctrlx)'*(storagex - ctrlx);\n testu = (storageu - ctrlu)'*(storageu - ctrlu);\n test = (testx)/(storagex'*storagex);\n if (test)^(0.5)<=10^(-2)&& (testx/((N+1)*nx))^(0.5)<=10^(-4)%Convergence criterion\n break\n end\nend % Move for the first step\nctrl = ctrlu(1:nu);\nx0 = [dt*x0(4)*cos(x0(3))+x0(1);dt*x0(4)*sin(x0(3))+x0(2);dt*ctrl(1)+x0(3);dt*ctrl(2)+x0(4)];\nctrlu = rewrite(ctrlu, nu, N);\nx_0 = newinit(x0, ctrlu, nx, nu, N, dt);\nu_0 = transu(ctrlu, nu, N);\nimpc(:, 2) = x0;\nstoragex = ctrlx;\nstorageu = ctrlu;\n\nfor i = 1 : (nsim-1)\n\n for j = 1 : K\n abc = tangentline(x_0, r);\n Acbf = cbfmat(abc, nx, nu, dt, gamma1, x0);\n lcbf = -abc(3, :);\n lcbf(1) = [];\n lcbf = lcbf';\n ucbf = inf * ones(N, 1);\n A2cbf = cbfmat2(abc, nx, nu, dt, gamma1, gamma2, x0);\n lcbf2 = getlcbf2(abc, dt, gamma1, gamma2);\n ucbf2 = inf * ones(N-1, 1);\n % Cast MPC problem to a QP: x = (x(0),x(1),...,x(N),u(0),...,u(N-1))\n % - quadratic objective\n P = blkdiag( kron(speye(N), Q), QN, kron(speye(N), R) );\n % - linear objective\n q = [repmat(-Q*xr, N, 1); -QN*xr; repmat(-R*ur, N, 1)];\n % - linear dynamics\n Ax = getax(x_0, dt, N, nx);\n Bu = kron([sparse(1, N); speye(N)], BB);\n Cx = getcx(x_0, u_0, dt, N, nx);\n Aeq = [Ax, Bu];\n leq = [-x0; -Cx];\n ueq = leq;\n % - input and state constraints\n Aineq = speye((N+1)*nx + N*nu);\n lineq = [repmat(xmin, N+1, 1); repmat(umin, N, 1)];\n uineq = [repmat(xmax, N+1, 1); repmat(umax, N, 1)];\n\n % - OSQP constraints\n A = [Aeq; Aineq; Acbf; A2cbf];%Highest order mcbf=2\n l = [leq; lineq; lcbf; lcbf2];\n u = [ueq; uineq; ucbf; ucbf2];\n % Create an OSQP object\n prob = osqp;\n % Setup workspace\n prob.setup(P, q, A, l, u, 'warm_start', true);\n % Solve\n res = prob.solve();\n\n % Check solver status\n if ~strcmp(res.info.status, 'solved')\n error('OSQP did not solve the problem!')\n end\n ctrlx = res.x(1:(N+1)*nx);\n ctrlu = res.x((N+1)*nx+1:(N+1)*nx+N*nu);\n if i == 6 %Get several open-loop trajectories at different iterations predicted at t = 6\n Itera_x = [Itera_x; ctrlx(1:4:(N*nx)+1)'];\n Itera_y = [Itera_y; ctrlx(2:4:(N*nx)+2)'];\n Itera_theta = [Itera_theta; ctrlx(3:4:(N*nx)+3)'];\n Itera_v = [Itera_v; ctrlx(4:4:(N*nx)+4)'];\n end\n x0 = ctrlx(1:nx);\n x_0 = trans(x0, ctrlx, nx, N+1);\n u_0 = transu(ctrlu, nu, N);\n testx = (storagex - ctrlx)'*(storagex - ctrlx);\n testu = (storageu - ctrlu)'*(storageu - ctrlu);\n test = (testx)/(storagex'*storagex);\n if (test)^(0.5)<=10^(-2)&& (testx/((N+1)*nx))^(0.5)<=10^(-4)%Convergence criterion\n break\n end\n storagex = ctrlx;\n storageu = ctrlu;\n end\n ctrl = ctrlu(1:nu);\n x0 = [dt*x0(4)*cos(x0(3))+x0(1);dt*x0(4)*sin(x0(3))+x0(2);dt*ctrl(1)+x0(3);dt*ctrl(2)+x0(4)];\n ctrlu = rewrite(ctrlu, nu, N);\n x_0 = newinit(x0, ctrlu, nx, nu, N, dt);\n u_0 = transu(ctrlu, nu, N);\n impc(:, i+2) = x0;\nend\n\nsave('trajectory','impctra');%Close-loop 2D-trajectory where tsim=100\nsave('iteration_x','Itera_x');\nsave('iteration_y','Itera_y');\nsave('iteration_theta','Itera_theta');\nsave('iteration_v','Itera_v');\n\n% Linerize the CBF constraints (get a, b, c for lines)\nfunction abc = tangentline(xy, r)% x and y from initialize states set, abc are coeeficients for linear equation a*x+b*y+c=0\n[xx, ~] = size(xy);%xx=2,yy=N+1\nxy(xx,:) = []; % this part should be changed for other case\nxy((xx-1),:) = []; % this part should be changed other case\n[xx, yy] = size(xy);%xx=2,yy=N+1\nxyjiao = zeros(xx, yy);%intersection points\nfor i = 1 : xx\n for j = 1 : yy\n xyjiao(i, j) = r * xy(i, j) * (1 / (xy(:, j)' * xy(:, j)))^(0.5);%calculate coordinates of intersection points\n end\nend\ncc = -r^2 * ones(1, yy);\nabc = [xyjiao; cc];\nend\n\n% Get CBF constraints matrix \nfunction Acbf = cbfmat(abc, nx, nu, dt, gamma, x0)\n[~, yy] = size(abc);\nAcbfx = zeros((yy-1), yy*nx);\nAcbfu = zeros((yy-1), (yy-1)*nu);\nfor i = 1 : (yy-1)\n Acbfx(i, (i*nx)+1) = abc(1, (i+1));\n Acbfx(i, (i*nx)+2) = abc(2, (i+1));\nend\nfor i = 1 : (yy-1)\n Acbfu(i, ((i-1)*nu+3)) = - (1 - dt * gamma)^(i) * (abc(1, 1) * x0(1, 1) + abc(2, 1) * x0(2, 1) + abc(3, 1));\nend\nAcbf = [Acbfx Acbfu];\nend\n\n% Transfer vector x into matrix \nfunction res = trans(x0, vector, nxx, nyy)%nxx=nx,nyy=N+1\n res = zeros(nxx, nyy);\n res(:,1) = x0;\n for i = 1 : (nyy -1)\n res(:,i+1)= vector(((i)*nxx+1):(i+1)*nxx);\n end \nend\n\n% Transfer vector u into matrix \nfunction resu = transu(vector, nxx, nyy)%nxx=nu,nyy=N\n resu = zeros(nxx, nyy);\n for i = 1 : (nyy)\n resu(:,i)= vector(((i-1)*nxx+1):(i)*nxx);\n end \nend\n\n% Rewrite u vector\nfunction reu = rewrite(vector, nu, N)\nappend = vector((N-1)*nu+1:N*nu);\nvector(1:nu) = [];\nreu = [vector;append];\nend\n\n% Get new x_0\nfunction x_0 = newinit(x0, ctrlu, nx, nu, N, dt)\n x_0 = zeros(nx, N+1);\n x_0(:, 1) = x0;\n for i=1 : N\n u0 = ctrlu((i-1)*nu+1:i*nu);\n x0 = [dt*x0(4)*cos(x0(3))+x0(1);dt*x0(4)*sin(x0(3))+x0(2);dt*u0(1)+x0(3);dt*u0(2)+x0(4)];\n x_0(:, i + 1) = x0;\n end\nend\n\n% Get AA matrix\nfunction AA = getaa(x0, dt)\n AA = [1 0 -x0(4)*sin(x0(3))*dt cos(x0(3))*dt;0 1 x0(4)*cos(x0(3))*dt sin(x0(3))*dt;0 0 1 0;0 0 0 1];\nend\n% Get CC matrix\nfunction CC = getcc(x0, x1, u0, dt)\n CC = [x0(4)*sin(x0(3))*x0(3)*dt-x0(4)*cos(x0(3))*dt+x1(1)-x0(1);-x0(4)*cos(x0(3))*x0(3)*dt-x0(4)*sin(x0(3))*dt+x1(2)-x0(2);-u0(1)*dt+x1(3)-x0(3);-u0(2)*dt+x1(4)-x0(4)];\nend\n% Get Ax matrix\nfunction Ax = getax(x_0, dt, N, nx)\nx0 = x_0(:,1);\nAA = getaa(x0, dt);\nAx = kron(speye(N+1), -speye(nx)) + kron(sparse(diag(ones(N, 1), -1)), AA);\nfor i = 1 : (N-1)\n x0 = x_0(:,i+1);\n AA = getaa(x0, dt);\n Ax(nx*(i+1)+1:nx*(i+1)+nx,nx*i+1:nx*i+nx) = AA;\nend\nend\n% Get Cx matrix\nfunction Cx = getcx(x_0, u_0, dt, N, nx)\nCx = zeros(N*nx, 1);\nfor i = 1 : N\n u0 = u_0(:,i);\n x0 = x_0(:,i);\n x1 = x_0(:,i+1);\n CC = getcc(x0, x1, u0, dt);\n Cx((i-1)*nx+1:(i-1)*nx+nx) = CC;\nend\nend\n% Get A2cbf\nfunction A2cbf = cbfmat2(abc, nx, nu, dt, gamma1, gamma2, x0)\n[~, yy] = size(abc);\nAcbfx2 = zeros((yy-2), yy*nx);\nAcbfx22 = zeros((yy-2), yy*nx);\nAcbfu2 = zeros((yy-2), (yy-1)*nu);\nfor i = 1 : (yy-2)\n Acbfx2(i, (i*nx)+1) = (gamma1-1/dt)*abc(1, (i+1));\n Acbfx2(i, (i*nx)+2) = (gamma1-1/dt)*abc(2, (i+1));\n Acbfx2(i, ((i+1)*nx)+1) = (1/dt)*abc(1, (i+2));\n Acbfx2(i, ((i+1)*nx)+2) = (1/dt)*abc(2, (i+2));\nend\nfor i = 1 : (yy-2)\n Acbfx22(i, (1*nx)+1) = -(1-dt*gamma2)^(i)/dt*abc(1, (1+1));\n Acbfx22(i, (1*nx)+2) = -(1-dt*gamma2)^(i)/dt*abc(2, (1+1));\nend\nAcbfx2 = Acbfx2 + Acbfx22;\nfor i = 1 : (yy-2)\n Acbfu2(i, ((i-1)*nu+4)) = - (1 - dt * gamma2)^(i)*(gamma1-1/dt)*(abc(1, 1) * x0(1, 1) + abc(2, 1) * x0(2, 1) + abc(3, 1));\nend\nA2cbf = [Acbfx2 Acbfu2];\nend\n% Get lcbf2\nfunction lcbf2 = getlcbf2(abc, dt, gamma1, gamma2)\n[~, yy] = size(abc);\nlcbf2 = zeros((yy-2),1);\nfor i = 1 : (yy-2)\n lcbf2(i, 1) = -abc(3, (i+2))/dt-(gamma1-1/dt)*abc(3, (i+1))+(1 - dt * gamma2)^(i)*abc(3, (1+1))/dt;\nend\nend", "meta": {"author": "HybridRobotics", "repo": "NMPC-DCLF-DCBF", "sha": "3f40c67578f49114301b02e744e5a86fa671a981", "save_path": "github-repos/MATLAB/HybridRobotics-NMPC-DCLF-DCBF", "path": "github-repos/MATLAB/HybridRobotics-NMPC-DCLF-DCBF/NMPC-DCLF-DCBF-3f40c67578f49114301b02e744e5a86fa671a981/matlab/acc2023/closedloop_performance/Iterative_Convergence.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680904463334, "lm_q2_score": 0.6370307875894139, "lm_q1q2_score": 0.5464246822260954}} {"text": "%MDL_QUADCOPTER Dynamic parameters for a quadrotor.\n%\n% MDL_QUADCOPTER is a script creates the workspace variable quad which\n% describes the dynamic characterstics of a quadrotor flying robot.\n%\n% Properties::\n%\n% This is a structure with the following elements:\n%\n% nrotors Number of rotors (1x1)\n% J Flyer rotational inertia matrix (3x3)\n% h Height of rotors above CoG (1x1)\n% d Length of flyer arms (1x1)\n% nb Number of blades per rotor (1x1)\n% r Rotor radius (1x1)\n% c Blade chord (1x1)\n% e Flapping hinge offset (1x1)\n% Mb Rotor blade mass (1x1)\n% Mc Estimated hub clamp mass (1x1)\n% ec Blade root clamp displacement (1x1)\n% Ib Rotor blade rotational inertia (1x1)\n% Ic Estimated root clamp inertia (1x1)\n% mb Static blade moment (1x1)\n% Ir Total rotor inertia (1x1)\n% Ct Non-dim. thrust coefficient (1x1)\n% Cq Non-dim. torque coefficient (1x1)\n% sigma Rotor solidity ratio (1x1)\n% thetat Blade tip angle (1x1)\n% theta0 Blade root angle (1x1)\n% theta1 Blade twist angle (1x1)\n% theta75 3/4 blade angle (1x1)\n% thetai Blade ideal root approximation (1x1)\n% a Lift slope gradient (1x1)\n% A Rotor disc area (1x1)\n% gamma Lock number (1x1)\n%\n%\n% Notes::\n% - SI units are used.\n%\n% References::\n% - Design, Construction and Control of a Large Quadrotor micro air vehicle.\n% P.Pounds, PhD thesis, \n% Australian National University, 2007.\n% http://www.eng.yale.edu/pep5/P_Pounds_Thesis_2008.pdf\n% - This is a heavy lift quadrotor\n%\n% See also sl_quadrotor.\n\n% MODEL: quadrotor\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\nquad.nrotors = 4; % 4 rotors\nquad.g = 9.81; % g Gravity 1x1\nquad.rho = 1.184; % rho Density of air 1x1\nquad.muv = 1.5e-5; % muv Viscosity of air 1x1\n\n% Airframe\nquad.M = 4; % M Mass 1x1\nIxx = 0.082;\nIyy = 0.082;\nIzz = 0.149;%0.160;\nquad.J = diag([Ixx Iyy Izz]); % I Flyer rotational inertia matrix 3x3\n\nquad.h = -0.007; % h Height of rotors above CoG 1x1\nquad.d = 0.315; % d Length of flyer arms 1x1\n\n%Rotor\nquad.nb = 2; % b Number of blades per rotor 1x1\nquad.r = 0.165; % r Rotor radius 1x1\n\nquad.c = 0.018; % c Blade chord 1x1\n\nquad.e = 0.0; % e Flapping hinge offset 1x1\nquad.Mb = 0.005; % Mb Rotor blade mass 1x1\nquad.Mc = 0.010; % Mc Estimated hub clamp mass 1x1\nquad.ec = 0.004; % ec Blade root clamp displacement 1x1\nquad.Ib = quad.Mb*(quad.r-quad.ec)^2/4 ; % Ib Rotor blade rotational inertia 1x1\nquad.Ic = quad.Mc*(quad.ec)^2/4; % Ic Estimated root clamp inertia 1x1\nquad.mb = quad.g*(quad.Mc*quad.ec/2+quad.Mb*quad.r/2); % mb Static blade moment 1x1\nquad.Ir = quad.nb*(quad.Ib+quad.Ic); % Ir Total rotor inertia 1x1\n\nquad.Ct = 0.0048; % Ct Non-dim. thrust coefficient 1x1\nquad.Cq = quad.Ct*sqrt(quad.Ct/2); % Cq Non-dim. torque coefficient 1x1\n\nquad.sigma = quad.c*quad.nb/(pi*quad.r); % sigma Rotor solidity ratio 1x1\nquad.thetat = 6.8*(pi/180); % thetat Blade tip angle 1x1\nquad.theta0 = 14.6*(pi/180); % theta0 Blade root angle 1x1\nquad.theta1 = quad.thetat - quad.theta0; % theta1 Blade twist angle 1x1\nquad.theta75 = quad.theta0 + 0.75*quad.theta1;% theta76 3/4 blade angle 1x1\nquad.thetai = quad.thetat*(quad.r/quad.e); % thetai Blade ideal root approximation 1x1\nquad.a = 5.5; % a Lift slope gradient 1x1\n\n% derived constants\nquad.A = pi*quad.r^2; % A Rotor disc area 1x1\nquad.gamma = quad.rho*quad.a*quad.c*quad.r^4/(quad.Ib+quad.Ic);% gamma Lock number 1x1\n\nquad.b = quad.Ct*quad.rho*quad.A*quad.r^2; % T = b w^2\nquad.k = quad.Cq*quad.rho*quad.A*quad.r^3; % Q = k w^2\n\nquad.verbose = false;\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/robot/mdl_quadrotor.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677622198947, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.546282110328751}} {"text": "function lengths = trk_length(tracks)\n%TRK_LENGTH - Calculate the lengths of tracks\n%\n% Syntax: lengths = trk_length(tracks)\n%\n% Inputs:\n% tracks - TrackVis track group. For tracks all of the same length (i.e.\n% TRK_INTERP has been run), either structure or matrix form is fine.\n%\n% Outputs:\n% lengths [1 x nTracks]\n%\n% Example: \n% [header tracks] = read_trk(trkPath);\n% lengths = trk_length(tracks);\n% mean(lengths), std(lengths)\n%\n% Other m-files required: trk_restruc\n% Subfunctions: none\n% MAT-files required: none\n%\n% See also: TRK_READ\n\n% Author: John Colby (johncolby@ucla.edu)\n% UCLA Developmental Cognitive Neuroimaging Group (Sowell Lab)\n% Apr 2010\n \n% Put in matrix form if possible\nif isstruct(tracks) && length(unique(cat(tracks.nPoints)))==1\n tracks = trk_restruc(tracks);\nend\n\n% Fast matrix operation if all tracks are the same length\nif isnumeric(tracks)\n lengths = sum(sqrt(squeeze(sum((tracks(2:end,1:3,:) - tracks(1:(end-1),1:3,:)).^2, 2))), 1);\n\n% Slow forloop if tracks are not the same length\nelse\n lengths = zeros(1,length(tracks));\n for i=1:length(tracks)\n lengths(i) = sum(sqrt(squeeze(sum((tracks(i).matrix(2:end,1:3) - tracks(i).matrix(1:(end-1),1:3)).^2, 2))), 1);\n end\nend\n", "meta": {"author": "yetianmed", "repo": "subcortex", "sha": "76179cf552b773e79b06a54568eae1fdd13722f4", "save_path": "github-repos/MATLAB/yetianmed-subcortex", "path": "github-repos/MATLAB/yetianmed-subcortex/subcortex-76179cf552b773e79b06a54568eae1fdd13722f4/functions/trk_length.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.626124191181315, "lm_q1q2_score": 0.5461977943995374}} {"text": "function imgOut = TumblinTMO(img, L_da, Ld_Max, C_Max, L_wa)\n%\n% imgOut = TumblinTMO(img, L_da, Ld_Max, C_Max, L_wa)\n%\n%\n% Input:\n% -img: an HDR image\n% -L_da: adaptation display luminance in [10,30] cd/m^2\n% -Ld_Max: maximum display luminance in [80, 180] cd/m^2\n% -C_Max: maximum LDR monitor contrast typically between 30 to 100\n%\n% Output:\n% -imgOut: a tone mapped image in [0,1]\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% \"Two Methods for Display of High Contrast Images\"\n% \t by JACK TUMBLIN, JESSICA K. HODGINS, and BRIAN K. GUENTER\n% in ACM Transactions on Graphics, Vol. 18, No. 1, January 1999, Pages 56?94.\n%\n\n%is it a three color channels image?\ncheck13Color(img);\n\ncheckNegative(img);\n\n%check parameters\nif(~exist('L_da', 'var'))\n L_da = 20;\nend\n\nif(~exist('Ld_Max', 'var'))\n Ld_Max = 100;\nend\n\nif(~exist('C_Max', 'var'))\n C_Max = 100;\nend\n\nif(~exist('L_wa', 'var'))\n L_wa = logMean(lum(img)); %luminance world adaptation \nend\n\n%compute luminance channel\nL = lum(img);\n\n%range compression\ngamma_w = StevensCSF(L_wa);\ngamma_d = StevensCSF(L_da);\ngamma_wd = gamma_w / (1.855 + 0.4 * log(L_da));\nm = C_Max.^((gamma_wd - 1) / 2.0);\nLd = L_da * m .* ((L ./ L_wa).^(gamma_w / gamma_d));\nLd = Ld / Ld_Max;\n\n%change luminance\nimgOut = ChangeLuminance(img, L, Ld);\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/Tmo/TumblinTMO.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8774767938900121, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5461936182699245}} {"text": "%%**********************************************************************\n%% NTpred: Compute (dX,dy,dZ) for NT direction. \n%% \n%% compute SVD of Xchol*Zchol via eigenvalue decompostion of\n%% Zchol * X * Zchol' = V * diag(sv2) * V'. \n%% compute W satisfying W*Z*W = X. \n%% W = G'*G, where G = diag(sqrt(sv)) * (invZchol*V)'\n%%\n%% SDPT3: version 3.1\n%% Copyright (c) 1997 by\n%% K.C. Toh, M.J. Todd, R.H. Tutuncu\n%% Last Modified: 16 Sep 2004\n%%**********************************************************************\n\n function [par,dX,dy,dZ,coeff,L,hRd] = ...\n NTpred(blk,At,par,rp,Rd,sigmu,X,Z,Zchol,invZchol);\n\n global schurfun schurfun_par \n%%\n%% compute NT scaling matrix\n%%\n [par.W,par.G,par.sv,par.gamx,par.gamz,par.dd,par.ee,par.ff] = ...\n NTscaling(blk,X,Z,Zchol,invZchol);\n%%\n%% compute schur matrix\n%%\n m = length(rp); \n schur = sparse(m,m); \n UU = []; EE = []; Afree = []; \n dX = cell(size(blk,1),1); dy = []; dZ = cell(size(blk,1),1); \n%%\n for p = 1:size(blk,1)\n pblk = blk(p,:); \n if strcmp(pblk{1},'l')\n [schur,UU,EE] = schurmat_lblk(blk,At,par,schur,UU,EE,p,par.dd);\n elseif strcmp(pblk{1},'q'); \n [schur,UU,EE] = schurmat_qblk(blk,At,par,schur,UU,EE,p,par.dd,par.ee);\n elseif strcmp(pblk{1},'s')\n if isempty(schurfun{p})\n schur = schurmat_sblk(blk,At,par,schur,p,par.W); \n elseif isstr(schurfun{p}) \n schurtmp = sparse(m,m);\n if ~isempty(par.permZ{p})\n Wp = par.W{p}(par.permZ{p},par.permZ{p}); \n else\n Wp = par.W{p};\n end\n eval(['schurtmp = ',schurfun{p},'(Wp,Wp,schurfun_par(p,:));']); \n schur = schur + schurtmp;\n end\n elseif strcmp(pblk{1},'u') \n Afree = [Afree, At{p}'];\n end\n end\n%%\n%% compute rhs\n%%\n [rhs,EinvRc,hRd] = NTrhsfun(blk,At,par,X,Z,rp,Rd,sigmu);\n%%\n%% solve linear system\n%%\n [xx,coeff,L] = linsysolve(par,schur,UU,Afree,EE,rhs); \n%%\n%% compute (dX,dZ)\n%%\n [dX,dy,dZ] = NTdirfun(blk,At,par,Rd,EinvRc,xx,m); \n%%**********************************************************************\n", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/dependencies/cvx-1.21.b795/sdpt3/Solver/NTpred.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099069987088003, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.5461155886344123}} {"text": "function [values,modes] = max(SO3F,varargin)\n% global, local and pointwise maxima of functions on SO(3)\n%\n% Syntax\n% [v,pos] = max(SO3F) % the position where the maximum is atained\n%\n% [v,pos] = max(SO3F,'numLocal',5) % the 5 largest local maxima\n%\n% SO3F = max(SO3F, c) % maximum of a rotational functions and a constant\n% SO3F = max(SO3F1, SO3F2) % maximum of two rotational functions\n% SO3F = max(SO3F1, SO3F2, 'bandwidth', bw) % specify the new bandwidth\n%\n% % compute the maximum of a multivariate function along dim\n% SO3F = max(SO3Fmulti,[],dim)\n%\n% Input\n% SO3F, SO3F1, SO3F2 - @SO3Fun\n% SO3Fmulti - a multivariate @SO3Fun\n% c - double\n%\n% Output\n% v - double\n% pos - @rotation / @orientation\n%\n% Options\n% kmax - number of iterations\n% numLocal - number of peaks to return\n% startingNodes - @rotation / @orientation\n% tolerance - minimum distance between two peaks\n% resolution - minimum step size \n% maxStepSize - maximm step size\n%\n% Example\n%\n% %find the local maxima of the ODF\n% mode = calcModes(SantaFe)\n% plotPDF(SantaFe,Miller(0,0,1,mode.CS))\n% annotate(mode)\n%\n% See also\n% SO3Fun/min SO3Fun/max\n\nif isa(SO3F,'SO3FunHarmonic') && ~SO3F.isReal\n SO3F = SO3F.isReal;\n warning('By taking the maxima of SO3Funs, the functions should be real valued.')\nend\nif nargin>1 && isa(varargin{1},'SO3FunHarmonic') && ~varargin{1}.isReal\n varargin{1}.isReal = 1;\n warning('By taking the maxima of SO3Funs, the functions should be real valued.')\nend\n\nif numel(SO3F)==1\n [values,modes] = max@SO3Fun(SO3F,varargin{:});\n return\nend\n\n% multivariate functions\ns = size(SO3F);\n\nif nargin>1 && (isa(varargin{1},'SO3FunHarmonic') || isnumeric(varargin{1}))\n t = size(varargin{1});\n SO3F1 = SO3F.*ones(t);\n SO3F2 = varargin{1}.*ones(s);\n values = [];\n for k=1:numel(SO3F1)\n if isa(SO3F2,'SO3FunHarmonic')\n A = max@SO3Fun(SO3F1.subSet(k),SO3F2.subSet(k),varargin{:});\n else\n A = max@SO3Fun(SO3F1.subSet(k),SO3F2(k),varargin{:});\n end\n values = [values,A];\n end\n values = reshape(values,size(SO3F1));\n return\nend\n\nlen = get_option(varargin,'numLocal',1);\nvalues = zeros(len,prod(s));\nmodes = rotation.id(len,prod(s));\nfor k=1:numel(SO3F)\n [v,m] = max@SO3Fun(SO3F.subSet(k),varargin{:});\n values(:,k)=v; modes(:,k)=m;\nend\n\nend", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/SO3Fun/@SO3FunHarmonic/max.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7772998714925403, "lm_q2_score": 0.7025300573952052, "lm_q1q2_score": 0.54607652333294}} {"text": "function r=v_rotqr2ro(q)\n%ROTQR2RO converts a real quaternion to a 3x3 rotation matrix\n% Inputs:\n%\n% Q(4,...) Real-valued quaternion array (possibly unnormalized)\n%\n% Outputs:\n%\n% R(3,3,...) Rotation matrix array\n% Plots a diagram if no output specified\n%\n% In the quaternion representation of a rotation, and q(1) = cos(t/2)\n% where t is the angle of rotation in the range 0 to 2pi\n% and q(2:4)/sin(t/2) is a unit vector lying along the axis of rotation\n% a positive rotation about [0 0 1] takes the X axis towards the Y axis.\n%\n% Copyright (C) Mike Brookes 2007-2018\n% Version: $Id: v_rotqr2ro.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\npersistent a b c d e f g h m\nif isempty(a)\n a=[1 5 9];\n b=[11 16 6];\n c=[16 6 11];\n d=[4 8 3];\n e=[10 15 14];\n f=[4 2 3];\n g=[2 6 7];\n h=[1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4]';\n m=[1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4]';\nend\nsz=size(q);\nq=reshape(q,4,[]); % convert to 2D matrix\nnq =size(q,2); % number of quaternions to convert\np=2*q(h,:).*q(m,:)./repmat(sum(q.^2,1),16,1); % force normalized and calculate quadratic terms \nr=zeros(9,nq); % space for nq rotation matrices\nr(a,:)=1-p(b,:)-p(c,:);\nr(d,:)=p(e,:)-p(f,:);\nr(g,:)=p(e,:)+p(f,:);\nr=reshape(r,[3 3 sz(2:end)]);\nif ~nargout\n % display rotated cube\n q1=q(:,1);\n q1=q1/sqrt(q1'*q1); % normalize the first quaternion\n clf('reset'); % clear current axis\n v0=[-1 1 1 -1 -1 1 1 -1; -1 -1 1 1 -1 -1 1 1; -1 -1 -1 -1 1 1 1 1]*0.5; % unrotated coordinates\n v=r(:,:,1)*v0; % use first elemnt of r to rotate\n fv=[4 1 5 8; 2 3 7 6; 1 2 6 5; 3 4 8 7; 2 1 4 3; 5 6 7 8]; % verices for each face\n fc=[0 1 1; 1 0 0; 1 0 1; 0 1 0; 1 1 0; 0 0 1]; % colours for faces\n xc={[25 46 46 25; 55 55 49 49]/100,\n [25 33 33 39 39 46 46 39 39 33 33 25; 55 55 63 63 55 55 49 49 42 42 49 49]/100,\n [48 56 62 69 76 66 76 69 62 56 48 59; 68 68 58 68 68 53 37 37 47 37 37 53]/100,\n [48 55 62 69 77 65 65 59 59; 68 68 55 68 68 50 37 37 50]/100,\n [50 74 74 57 74 74 50 50 67 50; 68 68 62 43 43 37 37 43 62 62]/100};\n xf=[1 3; 2 3; 1 4; 2 4; 1 5; 2 5]; % characters to plot on each face\n nf=size(fv,1); % number of faces\n for i=1:6\n p(i)=patch(v(1,fv(i,:)),v(2,fv(i,:)),v(3,fv(i,:)),fc(i,:));\n set(p(i),'FaceAlpha',0.65);\n k=1.001; % factor to move out labels slightly to get correct depth ordering\n for j=1:2\n xij=xc{xf(i,j)}; % relative coordinates of character vertices\n patch(k*(v(1,fv(i,1))+(v(1,fv(i,2))-v(1,fv(i,1)))*xij(1,:)+(v(1,fv(i,4))-v(1,fv(i,1)))*xij(2,:)), ...\n k*(v(2,fv(i,1))+(v(2,fv(i,2))-v(2,fv(i,1)))*xij(1,:)+(v(2,fv(i,4))-v(2,fv(i,1)))*xij(2,:)), ...\n k*(v(3,fv(i,1))+(v(3,fv(i,2))-v(3,fv(i,1)))*xij(1,:)+(v(3,fv(i,4))-v(3,fv(i,1)))*xij(2,:)),1-fc(i,:));\n end\n end\n qa=q1(2:4);\n qm=max(abs(qa));\n if qm>1e-6*abs(q1(1))\n qa=qa/(qm/0.7); % scale so axis extends outside the cube\n hold on;\n plot3([1 -1]*qa(1),[1 -1]*qa(2),[1 -1]*qa(3),'-');\n hold off\n end\n th=360/pi*acos(abs(q1(1)));\n xlabel('x axis');\n ylabel('y axis');\n zlabel('z axis');\n q=q(:,1)*((2*(q(find(q1(:)~=0,1))>0)-1)); % force leading coefficient to be positive\n title(sprintf('%d^\\\\circ, qr'' = [%.2f,%.2f,%.2f,%.2f], eu_{xyzo}'' = [%d, %d, %d]^\\\\circ',round(th),q1(:),round(v_rotqr2eu('xyz',q1)*180/pi)));\n axis([-1 1 -1 1 -1 1 0 1]*sqrt(3)/2);\n axis equal\n grid on\n view(3);\nend\n\n", "meta": {"author": "ImperialCollegeLondon", "repo": "sap-voicebox", "sha": "28f2654b7584f724277ec81de533debe28ff51ac", "save_path": "github-repos/MATLAB/ImperialCollegeLondon-sap-voicebox", "path": "github-repos/MATLAB/ImperialCollegeLondon-sap-voicebox/sap-voicebox-28f2654b7584f724277ec81de533debe28ff51ac/voicebox/v_rotqr2ro.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.5460765160843408}} {"text": "function [safety, order, union, alg_conn, safety_obs, min_d_obs ] = ...\n compute_swarm_performance(pos_history, vel_history, ...\n p_swarm, dirname)\n% Compute swarm performance - This function allows to compute the \n% performance from the history of the swarming variables (time, position, \n% velocity, acceleration).\n%\n% Inputs:\n% pos_history: series of agents' positions\n% vel_history: series of agents' velocities\n% p_swarm: structure with swarm parameters\n% dirname: path of the directory where results are saved\n%\n% Outputs:\n% safety: safety metric. It reflects the number of agent-agent collisions\n% order: order metric. It measures the correlation between velocity\n% vectors\n% union: union metric. It measures the number of connected components of\n% the undirected graph\n% alg_conn: algebraic connectivity metric.\n% safety_obs: safety againt obstacles metric. reflects the number of \n% agent-obstacle collisions\n% min_d_obs: minimum distance agent-obstacle\n%\n\n%% Init variables\n\n[t_steps,nx] = size(pos_history);\nnb_agents = nx/3;\nM = zeros(t_steps,nb_agents,nb_agents);\nnb_ag_coll = zeros(t_steps,1);\nnb_obs_coll = zeros(t_steps,1);\nnb_conn_comp = zeros(t_steps,1);\n\nsafety = ones(t_steps,1);\norder = zeros(t_steps,1);\nunion = zeros(t_steps,1);\nalg_conn = zeros(t_steps,1);\nsafety_obs = zeros(t_steps,1);\nmin_d_obs = zeros(t_steps,nb_agents);\n\n%% Loop over time\n\nfor k = 1:t_steps\n \n %% Safety: reflects the number of collisions among the swarm agents\n \n pos_k = pos_history(k,:);\n pos_k = reshape(pos_k,3,[]);\n dist_vect_k = pdist(pos_k');\n if ~isempty(dist_vect_k)\n nb_ag_coll(k) = sum(dist_vect_k < 2*p_swarm.r_coll);\n safety(k) = 1 - (sum(nb_ag_coll(k)) / length(dist_vect_k));\n else\n nb_ag_coll(k)=0;\n safety(k) = 1;\n end\n \n %% Order: reflects the correlation of the velocity vectors\n distance_matrix_k = squareform(dist_vect_k);\n M(k,:,:) = compute_neighborhood(distance_matrix_k, p_swarm.r, p_swarm.max_neig);\n for agent = 1:nb_agents\n neig = (M(k,:,agent)==true);\n nn = sum(neig);\n vel_k = vel_history(k,:);\n vel_k = reshape(vel_k,3,[]);\n if nn ~= 0\n scalar_prod = vel_k(:, agent)' * vel_k(:, neig);\n speed_agent = norm(vel_k(:, agent));\n speed_neig = sqrt(sum((vel_k(:, neig) .^ 2), 1));\n order(k) = order(k) + ...\n sum (scalar_prod ./ (speed_agent * speed_neig)) / nn;\n else\n order(k) = order(k) + 1;\n end\n end\n order(k) = order(k)/nb_agents;\n \n %% Union: reflects the number of connected components in the related\n % symeetric graph\n \n M_k = squeeze(M(k,:,:));\n A = ((M_k + M_k') > 0);\n [nb_conn_comp(k), ~, ~] = network_components(A);\n union(k) = (nb_agents - nb_conn_comp(k))/(nb_agents-1);\n \n %% Connectivity: reflects the algebraic connectivity in the related\n % symmetric graph\n \n alg_conn(k) = compute_alg_connectivity(A)/nb_agents;\n \n %% Safety with obstacles: reflects the number of collisions between swarm agents and obstacles\n \n nb_possible_coll = 0;\n if p_swarm.is_active_spheres | p_swarm.is_active_cyl | p_swarm.is_active_arena\n \n pos_k = pos_history(k,:);\n pos_k = reshape(pos_k,3,[]);\n \n if p_swarm.is_active_spheres\n c_spheres = p_swarm.spheres(1:3,:);\n r_spheres = p_swarm.spheres(4,:);\n \n D_spheres = pdist2(pos_k',c_spheres');\n min_d_obs(k,:) = min(pdist2(pos_k(1:2,:)',c_spheres') - repmat(r_spheres, nb_agents, 1),[],2); \n nb_obs_coll(k) = nb_obs_coll(k) + sum(sum(D_spheres < repmat(r_spheres, nb_agents, 1)));\n nb_possible_coll = nb_possible_coll + nb_agents*length(r_spheres);\n end\n if p_swarm.is_active_cyl\n c_cyl = p_swarm.cylinders(1:2,:);\n r_cyl = p_swarm.cylinders(3,:);\n \n D_cyl = pdist2(pos_k(1:2,:)',c_cyl');\n min_d_obs(k,:) = min(pdist2(pos_k(1:2,:)',c_cyl') - repmat(r_cyl, nb_agents, 1),[],2); \n nb_obs_coll(k) = nb_obs_coll(k) + sum(sum(D_cyl < repmat(r_cyl, nb_agents, 1)));\n nb_possible_coll = nb_possible_coll + nb_agents*length(r_cyl);\n end\n if p_swarm.is_active_arena\n x_coll = sum(pos_k(1,:)< p_swarm.x_arena(1,1) | pos_k(1,:)> p_swarm.x_arena(1,2));\n y_coll = sum(pos_k(2,:)< p_swarm.x_arena(2,1) | pos_k(2,:)> p_swarm.x_arena(2,2));\n z_coll = sum(pos_k(3,:)< p_swarm.x_arena(3,1) | pos_k(3,:)> p_swarm.x_arena(3,2));\n nb_obs_coll(k) = nb_obs_coll(k) + x_coll + y_coll + z_coll;\n nb_possible_coll = nb_possible_coll + nb_agents;\n end\n \n safety_obs(k) = 1 - (nb_obs_coll(k)/nb_possible_coll);\n end\n \nend\n\n%% Save workspace\n\nif ~isempty(dirname)\n path = strcat(dirname,'/performance');\n save(path);\nend\n\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction connectivity = compute_alg_connectivity(A)\n% Compute alg connectivity - compute algebraic connectivity of the graph\n% associated to the swarm at a given time step.\n\nD = diag(sum(A, 2)); % degree matrix\nL = D - A; % laplacian matrix\neigenvalues = eig(L);\neigenvalues = sort(eigenvalues);\nconnectivity = eigenvalues(2);\n\nend\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/math_tools/compute_swarm_performance.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357735451835, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.5460371138899998}} {"text": "function linpack_c_test17 ( )\n\n%*****************************************************************************80\n%\n%% TEST17 tests CPBCO.\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 m = 1;\n n = 3;\n lda = m + 1;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST17\\n' );\n fprintf ( 1, ' For a single precision complex (C)\\n' );\n fprintf ( 1, ' positive definite hermitian band matrix (PB),\\n' );\n fprintf ( 1, ' CPBCO estimates the reciprocal condition number.\\n' );\n fprintf ( 1, ' The matrix size is N = %d\\n', n );\n%\n% Set the value of the superdiagonal and diagonal.\n%\n a(1,1) = complex ( 0.0000, 0.0000 );\n a(1,2) = complex ( 2.1341, -0.2147 );\n a(1,3) = complex ( 2.0905, 1.1505 );\n\n a(2,1) = complex ( 4.5281, 0.0000 );\n a(2,2) = complex ( 5.0371, 0.0000 );\n a(2,3) = complex ( 4.7638, 0.0000 );\n%\n% Estimate the condition.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Estimate the condition.\\n' );\n\n [ a, rcond, info ] = cpbco ( a, lda, n, m );\n\n if ( info ~= 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' CPBCO returned INFO = %d\\n', info );\n fprintf ( 1, ' The factorization was not completed.\\n' );\n return\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Reciprocal condition = %f\\n', rcond );\n\n return\nend\n", "meta": {"author": "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/linpack_c_test17.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321964553657, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.5457790045448971}} {"text": "function value = r8_cos ( x )\n\n%*****************************************************************************80\n%\n%% R8_COS evaluates the cosine of an R8 argument.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 28 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 cosine of X.\n%\n persistent ntsn\n persistent pi2\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% pihi + pilo = pi. pihi is exactly representable on all machines\n% with at least 8 bits of precision. whether it is exactly\n% represented depends on the compiler. this routine is more\n% accurate if it is exactly represented.\n%\n pi2 = 1.57079632679489661923132169163975;\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 absx = abs ( x );\n y = absx + pi2;\n\n if ( xmax < y )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8_COS - 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_COS - Warning!\\n' );\n fprintf ( 1, ' Answer < half precision because |X| is big.\\n' );\n end\n\n value = 1.0;\n\n if ( absx < 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 xn = xn - 0.5;\n f = ( absx - 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 ( n2 ~= 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_cos.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.545778990502851}} {"text": "function a = kershaw_llt ( a )\n\n%*****************************************************************************80\n%\n%% KERSHAW_LLT returns the Cholesky factor of the KERSHAW matrix.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 15 March 2015\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Output, real A(4,4), the matrix.\n%\n a = [ ...\n 1.732050807568877, 0.0, 0.0, 0.0; ...\n -1.154700538379252, 1.290994448735805, 0.0, 0.0; ...\n 0.0, -1.549193338482967, 0.774596669241483, 0.0; ...\n 1.154700538379252, 1.032795558988645, -0.516397779494321, 0.577350269189626 ];\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_mat/kershaw_llt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.545754220924719}} {"text": "% Fig. 5.8 Feedback Control of Dynamic Systems, 6e \n% Franklin, Powell, Emami\n\nclf\nn9=1;\nd9=[1 8 32 0];\nrlocus(n9,d9)\ntitle('Fig.5.08 The root locus for L(s)=1/s(s^2+8s+32)')\naxis([-14 2 -6 6])\nz=0:.1:.9;\n wn= 1:6;\n sgrid(z, wn) \nhold on\nx=[-2.67 2 -2.67 2];\ny=[0 4.67*sqrt(3) 0 -4.67*sqrt(3)];\nplot(x,y)\nr=roots([1 0 32]);\n plot(r,'*')\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/26412-feedback-control-of-dynamic-systems-6th-edition-prentice-hall-2010/fig5_08.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311856832191, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.5457542190253288}} {"text": "function [xopt,fval,exitflag,output] = spcompsearch(z, xbox, options)\n% SPCOMPSEARCH Modified compass (coordinate) search algorithm \n% performing a local search of the sparse grid inpterpolant. \n% X = SPCOMPSEARCH(Z) Finds a local optimizer X for the given \n% sparse grid interpolant Z using a modified compass search \n% algorithm starting from the best available sparse grid point. \n% The entire range of the sparse grid interplant is searched.\n%\n% X = SPCOMPSEARCH(Z, XBOX) Uses the search box XBOX, X = [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 = SPCOMPSEARCH(Z, XBOX, OPTIONS) Additionally, an OPTIONS\n% structure can be provided, see SPOPTIMSET for further details.\n%\n% [X,FVAL] = SPCOMPSEARCH(...) returns the value of the \n% sparse grid interpolant at X.\n%\n% [X,FVAL,EXITFLAG] = SPCOMPSEARCH(...) returns an EXITFLAG \n% that describes the exit condition of SPCOMPSEARCH. Possible\n% values of EXITFLAG and the corresponding exit conditions are\n%\n% 1 SPCOMPSEARCH converged to a solution X.\n% 0 Maximum number of iterations reached.\n%\n% [X,FVAL,EXITFLAG,OUTPUT] = SPCOMPSEARCH(...) returns a \n% structure OUTPUT with the number of function evaluations in \n% OUTPUT.nFevals 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% z = spvals(f, 2, range, options);\n% [xopt, fval] = spcompsearch(z)\n%\n% See also SPOPTIMSET.\n \n% Author : Andreas Klimke\n% Version: 2.1\n% Date : September 1, 2007\n\t\n% Change log:\n% V2.1 : September 1, 2007\n% Changed calling syntax to match other optimization\n% methods. Added maximum number of iterations.\n% V2.0 : January 23, 2006\n% Added TolFun break criterium.\n% V1.9 : June 9, 2005\n% Removed multiple start processing from V1.5; moved to\n% separate routine SPMULTISTART. Removed start point\n% computation; moved to separate routine.\n% V1.8 : April 15, 2005\n% Corrected bug concerning testCorners option; Modified\n% slightly to cope with new dimension-adaptive format.\n% V1.7 : January 14, 2005\n% Corrected bug that lead to wrong rescaling of parts of the\n% grid data if previous results were used.\n% V1.6 : January 11, 2005\n% Added capability for handling polynomial sparse grid\n% interpolants. Added tolerance on X as options.\n% V1.5 : November 13, 2004\n% Added feature for performing multiple searches at a time.\n% V1.4 : September 6, 2004\n% Added capability for handling dimension-adaptive data.\n% V1.3 : September 6, 2004\n% : Added check if the spvals structure contains a valid\n% range; otherwise, set it to [0,1]^d.\n% V1.2 : March 9, 2004\n% Added random start point option\n% V1.1 : February 18, 2004\n% Moved search for optimum of sparse grid points to separate\n% routine (spfindopt.m).\n% V1.0 : January 7, 2004\n% Initial version\t \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. \nif isempty(z.range)\n\tz.range = [zeros(d,1) ones(d,1)];\nend\nif isempty(xbox)\n\txbox = z.range;\nend\n\nif isfield(z, 'dimAdapt')\n\tn = z.maxLevel';\nelse\n\tn = z.maxLevel*ones(d,1,'uint8');\nend\n\n% savepoints = [];\n\n% Determine optimization start point(s)\n[xopt, fval] = spgetstartpoint(z, xbox, options);\n\nminimize = spoptimget(options, 'Minimize', 'on');\nmaximize = spoptimget(options, 'Maximize', 'off');\nif strcmpi(minimize, 'on'), isminimize = 1; else isminimize = 0; end\nif strcmpi(maximize, 'on'), ismaximize = 1; else ismaximize = 0; end\n\nymin = []; ymax = [];\nif isminimize \n\tymin = fval(1);\n\tif ismaximize\n\t\tymax = fval(2);\n\tend\nelse\n\tymax = fval(1);\nend\n\n\nswitch(lower(z.gridType))\n case {'maximum', 'noboundary', 'clenshaw-curtis'}\n\tlinear = 1;\n case {'chebyshev', 'gauss-patterson'}\n\tlinear = 0;\n otherwise\n\t\terror('MATLAB:spinterp:badopt',['Unknown grid type ''' gridtype '''.']);\nend\n\nmaxiter = spoptimget(options, 'MaxIter', 100);\n\ntolx = spoptimget(options, 'TolX', []);\nif isempty(tolx)\n\tif linear\n\t\ttolx = inf;\n\telse\n\t\ttolx = max(z.estRelError * 1e-2, 10*eps);\n\tend\nend\n\ntolfun = spoptimget(options, 'TolFun', 1e-6);\ndispopt = spoptimget(options, 'Display', 'off');\n\nnfevals = 0;\n\nx = zeros(2*d,d);\n\nexitflag = zeros(size(xopt,2));\n\nfor k = 1:size(xopt,2)\n\t\n\t% Compute the step length parameters\n\tdx = 1./2.^(floor(double(n)/double(d))).*(z.range(:,2)-z.range(:,1));\n\tdxunit = 1./2.^(floor(double(n)/double(d)));\n\tdxmin = 1./2.^double(n);\n\tdxminvec = 1./2.^double(n).*(z.range(:,2)-z.range(:,1));\n\t\n\t% correct the start values to lie on a full grid point\n\tif linear\n\t\tupdated = 0;\n\t\tfor l = 1:d\n\t\t\txtemp = floor((xopt(l,k) - z.range(l,1)) / ...\n\t\t\t\t\t\t\t\t\t\tdxminvec(l))*dxminvec(l) + z.range(l,1);\n\t\t\twhile xtemp < xbox(l,1)\n\t\t\t\txtemp = xtemp + dxminvec(l);\n\t\t\tend\n\t\t\tif xtemp > xbox(l,2)\n\t\t\t\t% this can only be true if the search box is smaller than the\n\t\t\t\t% step width dx. In this case, take the center of the search\n\t\t\t\t% box as the starting point.\n\t\t\t\txtemp = (xbox(l,1) + xbox(l,2))/2;\n\t\t\tend\n\t\t\tif xtemp ~= xopt(l,k)\n\t\t\t\txopt(l,k) = xtemp;\n\t\t\t\tupdated = 1;\n\t\t\tend\n\t\tend\n\t\tif updated\n\t\t\txoptcell = num2cell(xopt(:,k));\n\t\t\tnfevals = nfevals + 1;\n if k == 1 && isminimize\n ymin = spinterp(z, xoptcell{:});\n else\n ymax = spinterp(z, xoptcell{:});\n end\n end\n\tend\n\t\n [isdispiter, iterstr] = initoptidisp(dispopt);\n if isdispiter\n\t if k == 1 && isminimize\n\t\t disp(sprintf(iterstr, 0, nfevals, 0, ymin, 'start point'));\n\t else\n\t\t disp(sprintf(iterstr, 0, nfevals, 0, ymax, 'start point'));\n\t\tend\n\tend\n\tif k == 2\n\t\tisminimize = 0;\n\tend\n\t\n\texitflag(k) = 0;\n\tfor kit = 1:maxiter\n\t\t\n\t\t% save the points for later processing, if requested by the\n % user\n\t\t%if nargout == 3\n\t\t%\tif isminimize\n\t\t%\t\tsavepoints = [savepoints; [xopt(:,k)' ymin]];\n\t\t%\telse\n\t\t%\t\tsavepoints = [savepoints; [xopt(:,k)' ymax]];\n\t\t%\tend\n\t\t%end\n\t\t\n\t\tnfevals = nfevals + uint32(d)*2;\n\t\t\n\t\t% Generate search points\n\t\tid = uint32(1);\n\t\tfor l = 1:d\n\t\t\tfor l2 = 1:d\n\t\t\t\tif l == l2\n\t\t\t\t\tx(id,l) = xopt(l,k) - dx(l);\n\t\t\t\t\tx(id+1,l) = xopt(l,k) + dx(l);\n\t\t\t\t\tif x(id,l) < xbox(l,1)\n x(id,l) = xbox(l,1);\n end\n if x(id+1,l) > xbox(l,2)\n x(id+1,l) = xbox(l,2);\n end\n\t\t\t\telse\n\t\t\t\t\tx(id,l2) = xopt(l2,k);\n\t\t\t\t\tx(id+1,l2) = xopt(l2,k);\n\t\t\t\tend\n\t\t\tend\n\t\t\tid = id + 2;\n\t\tend\n\t\t\n\t\t% Perform sparse grid interpolation\n\t\txcell = num2cell(x,1);\n\t\tytemp = spinterp(z, xcell{:});\n\t\t\n\t\tif isminimize\n\t\t\t[ymintemp, id] = min(ytemp);\n\t\t\tif ymintemp < ymin\n\t\t\t\txopt(:,k) = x(id,:)'; \n \tif isdispiter, disp(sprintf(iterstr, kit, nfevals, ...\n\t 0, ymintemp, 'coordinate step')); end\n % Terminate if function value change is below tolerance\n if abs(ymin-ymintemp) < tolfun\n\t\t\t\t ymin = ymintemp;\n\t\t\t\t\texitflag(k) = 1;\n break;\n end\n ymin = ymintemp; \n\t\t\telse\n \tif isdispiter, disp(sprintf(iterstr, kit, nfevals, ...\n\t 0, ymin, 'contract step')); end\n\t\t\t\tif all(dxunit <= dxmin) && all(dxunit <= tolx)\n\t\t\t\t\texitflag(k) = 1;\n\t\t\t\t\tbreak;\n\t\t\t\tend\n\t\t\t\tfor l = 1:d\n\t\t\t\t\tif dxunit(l) > dxmin(l) || dxunit(l) > tolx\n\t\t\t\t\t\tdxunit(l) = dxunit(l) / 2;\n\t\t\t\t\t\tdx(l) = dx(l) / 2;\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend\n\t\telse\n\t\t\t[ymaxtemp, id] = max(ytemp);\n\t\t\tif ymaxtemp > ymax\n\t\t\t\txopt(:,k) = x(id,:)';\n \tif isdispiter, disp(sprintf(iterstr, kit, nfevals, ...\n\t 0, ymaxtemp, 'coordinate step')); end\n % Terminate if function value change is below tolerance\n if abs(ymax-ymaxtemp) < tolfun\n\t\t\t\t ymax = ymaxtemp;\n\t\t\t\t\texitflag(k) = 1;\n break;\n end\n\t\t\t\tymax = ymaxtemp;\n\t\t\telse\n \tif isdispiter, disp(sprintf(iterstr, kit, nfevals, ...\n\t 0, ymax, 'contract step')); end\n\t\t\t\tif all(dxunit <= dxmin) && all(dxunit <= tolx)\n\t\t\t\t\texitflag(k) = 1;\n\t\t\t\t\tbreak;\n\t\t\t\tend\n\t\t\t\tfor l = 1:d\n\t\t\t\t\tif dxunit(l) > dxmin(l) || dxunit(l) > tolx\n\t\t\t\t\t\tdxunit = dxunit / 2;\n\t\t\t\t\t\tdx = dx / 2;\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\tend\nend\n\nfval = [ymin ymax];\n\nif nargout == 4\n\toutput.nFEvals = nfevals;\n\toutput.time = etime(clock, t0);\n\t% output.points = savepoints;\nend\n", "meta": {"author": "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/spcompsearch.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.6926419704455589, "lm_q1q2_score": 0.5457542159256198}} {"text": "function [M1,MW,MW1] = perform_wavelet_matching(M1,M,options)\n\n% perform_wavelet_matching - match multiscale histograms\n%\n% M1 = perform_wavelet_matching(M1,M,options);\n%\n% M1 is the image to synthesize.\n% M is the exemplar image.\n%\n% This function match the histogram of the image and the histogram \n% of each sub-band of a wavelet-like pyramid.\n%\n% To do texture synthesis, one should apply several time this function.\n% You can do it by setting the value of options.niter_synthesis.\n% This leads to the synthesis as described in \n%\n% Pyramid-Based Texture Analysis/Synthesis\n% D. Heeger, J. Bergen,\n% Siggraph 1995\n%\n% Copyright (c) 2007 Gabriel Peyre\n\noptions.null = 0;\nniter_synthesis = getoptions(options, 'niter_synthesis', 1);\n\nif not(isfield(options, 'color_mode'))\n options.color_mode = 'pca';\nend\nif isfield(options, 'color_mode') && strcmp(options.color_mode, 'pca') && ~isfield(options, 'ColorP') && size(M,3)==3\n [tmp,options.ColorP] = change_color_mode(M,+1,options); \nend\nrgb_postmatching = getoptions(options, 'rgb_postmatching', 0);\n\nif size(M,3)==3\n options.niter_synthesis = 1;\n for iter=1:niter_synthesis\n % color images\n M = change_color_mode(M, +1,options);\n M1 = change_color_mode(M1,+1,options);\n for i=1:size(M,3)\n M1(:,:,i) = perform_wavelet_matching(M1(:,:,i),M(:,:,i), options);\n end\n M = change_color_mode(M, -1,options);\n M1 = change_color_mode(M1,-1,options);\n if rgb_postmatching\n for i=1:size(M,3)\n M1(:,:,i) = perform_histogram_equalization(M1(:,:,i),M(:,:,i));\n end\n end\n end\n return;\nend\n\nif size(M,3)>1\n for i=1:size(M,3)\n [M1(:,:,i),MW,MW1] = perform_wavelet_matching(M1(:,:,i),M(:,:,i),options);\n end\n return;\nend\n\nn = size(M,1);\nn1 = size(M1,1);\n\nsynthesis_method = getoptions(options, 'synthesis_method', 'steerable');\n\nm = 2^( ceil(log2(n)) );\nm1 = 2^( ceil(log2(n1)) );\nM = perform_image_extension(M,m);\nM1 = perform_image_extension(M1,m1);\n\n% precompute input\nMW = my_transform(M, +1, options);\n\nfor iter=1:niter_synthesis\n % spatial equalization\n M1 = my_equalization(M1,M);\n % forward transforms\n MW1 = my_transform(M1, +1, options);\n % wavelet domain equalization\n MW1 = my_equalization(MW1,MW);\n % backward transform\n M1 = my_transform(MW1, -1, options);\n % spatial equalization\n M1 = my_equalization(M1,M);\nend\n\nM1 = M1(1:n1,1:n1);\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction M = my_equalization(M,M0)\n\noptions.absval = 0;\noptions.rows = 0;\noptions.cols = 0;\noptions.dim3 = 1;\n\nif iscell(M)\n for i=1:min(length(M),length(M0))\n M{i} = my_equalization(M{i},M0{i}); \n end\n return;\nend\nif size(M,3)>1\n for i=1:min(size(M,3),size(M0,3))\n M(:,:,i) = my_equalization(M(:,:,i),M0(:,:,i)); \n end\n return;\nend\nM = perform_histogram_equalization(M,M0);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction M = my_transform(M, dir, options)\n\nn = size(M,1);\ndeltaJ = 5;\nJmax = log2(n)-1;\nJmin = max(Jmax-deltaJ+1,3);\n \nsynthesis_method = getoptions(options, 'synthesis_method', 'steerable');\n% steerable options\nif not(isfield(options, 'nb_orientations'))\n options.nb_orientations = 4;\nend\n% wave ortho options\noptions.wavelet_type = 'biorthogonal_swapped';\noptions.wavelet_vm = 4;\n\nswitch synthesis_method\n case 'steerable'\n M = perform_steerable_transform(M, Jmin, options);\n case 'wavelets-ortho'\n if dir==-1\n M = convert_wavelets2list(M, Jmin);\n end\n M = perform_wavelet_transform(M, Jmin, dir, options);\n if dir==1\n M = convert_wavelets2list(M, Jmin); \n end \n case 'quincunx-ti'\n M = perform_quicunx_wavelet_transform_ti(M,Jmin,options);\n case 'wavelets-ti'\n options.wavelet_type = 'biorthogonal';\n options.wavelet_vm = 3;\n M = perform_atrou_transform(M,Jmin,options);\n otherwise \n error('Unknown transform.');\nend", "meta": {"author": "gpeyre", "repo": "matlab-toolboxes", "sha": "0cd622c988cda6f63f64d35cd7bd096fa578e5c6", "save_path": "github-repos/MATLAB/gpeyre-matlab-toolboxes", "path": "github-repos/MATLAB/gpeyre-matlab-toolboxes/matlab-toolboxes-0cd622c988cda6f63f64d35cd7bd096fa578e5c6/toolbox_nlmeans/toolbox/perform_wavelet_matching.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503205, "lm_q2_score": 0.6619228625116081, "lm_q1q2_score": 0.5457301926291022}} {"text": "function x = line_ccvt_lloyd ( n, a, b, it_num, header, x )\n\n%*****************************************************************************80\n%\n%% LINE_CCVT_LLOYD carries out the constrained Lloyd algorithm.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 28 July 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of generators.\n%\n% Input, real A, B, the left and right endpoints.\n%\n% Input, integer IT_NUM, the number of iterations to take.\n%\n% Input, string HEADER, an identifying string.\n%\n% Input, real X(N), the initial point locations.\n%\n% Output, real X(N), the final point locations.\n%\n x = x(:);\n%\n% Print the initial generators.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Initial generators:\\n' );\n fprintf ( 1, '\\n' );\n for k = 1 : n\n fprintf ( 1, ' %4d %f\\n', k, x(k,1) );\n end\n%\n% Initialize the plotting arrays.\n%\n step = 1 : it_num;\n e = nan ( it_num, 1 );\n xm = nan ( it_num, 1 );\n\n for it = 1 : it_num\n\n x_plot ( 1:n, it ) = x(1:n,1);\n\n x_new = line_ccvt_lloyd_step ( n, a, b, x );\n\n e(it) = line_cvt_energy ( n, a, b, x );\n e(it) = max ( e(it), eps );\n%\n% Display the energy.\n%\n figure ( 1 )\n plot ( step, log ( e ), 'm-*' )\n title ( 'Log (Energy)' )\n xlabel ( 'Step' )\n ylabel ( 'Energy' )\n grid\n%\n% Compute the generator motion.\n%\n xm(it,1) = sum ( ( x_new(:) - x(:) ).^2 ) / n;\n%\n% Display the generator motion.\n%\n figure ( 2 )\n plot ( step, log ( xm ), 'm-*' )\n title ( 'Log (Average generator motion)' )\n xlabel ( 'Step' )\n ylabel ( 'Motion' )\n grid\n%\n% Update the generators.\n%\n x(1:n,1) = x_new(1:n,1);\n \n end\n\n x_plot(1:n,it_num+1) = x(1:n,1);\n%\n% Print the current generators.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Current generators:\\n' );\n fprintf ( 1, '\\n' );\n for k = 1 : n\n fprintf ( 1, ' %4d %f\\n', k, x(k,1) );\n end\n%\n% Plot the evolution of the locations of the generators.\n%\n figure ( 3 )\n\n y = ( 0 : it_num );\n for k = 1 : n\n plot ( x_plot(k,1:it_num+1), y, 'LineWidth', 1 )\n hold on;\n end\n grid on\n hold off;\n\n title ( 'Generator evolution.' );\n xlabel ( 'Generator positions' );\n ylabel ( 'Iterations' ); \n%\n% Save the plots.\n%\n figure ( 1 )\n filename = strcat ( header, '_energy.png' );\n print ( '-dpng', filename );\n figure ( 2 )\n filename = strcat ( header, '_motion.png' );\n print ( '-dpng', filename );\n figure ( 3 )\n filename = strcat ( header, '_evolution.png' );\n print ( '-dpng', filename );\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/line_cvt_lloyd/line_ccvt_lloyd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743735019595, "lm_q2_score": 0.7371581568543043, "lm_q1q2_score": 0.5456255769214938}} {"text": "function [dat, W, A, lambda]= proc_ssd(dat, freqs, varargin)\n% PROC_SSD - Spatio-Spectral Decomposition for a given frequency band of\n% interest\n%\n%Synopsis:\n% [DAT, W, A, LAMBDA]= PROC_SSD(DAT, FREQS, )\n%\n% INPUT: \n% DAT - data structure of continous data\n% FREQS - 3 x 2 matrix with the cut-off frequencies for the following\n% bands:\n% - first row: pass-band for the signal of interest\n% - second row: pass-band for the noise\n% - third row: stop-band for the noise\n% See the example below. \n% OPT - struct or property/value list of optional properties:\n% .filterOrder - filter order used for butterworth bandpass and \n% bandstop filtering. Default: 2\n% .epochIndices - a matrix of size N x 2, where N is the number of \n% good (i.e. artifact free) data segments. Each row of \n% this matrix contains the first and the last sample index of\n% a data segment, i.e. epoch_indices(n,:) = [1000, 5000]\n% means that the n'th segment starts at sample 1000 and\n% ends at sample 5000. \n%\n% OUTPUT:\n% DAT - updated data structure\n% W - SSD projection matrix (filters are in the columns)\n% A - estimated mixing matrix (spatial patterns are in the columns)\n% LAMBDA - generalized eigenvalue score of SSD objective function\n%\n% \n% \n% Description:\n% This is a function for the extraction of neuronal oscillations \n% with optimized signal-to-noise ratio. The algorithm maximizes \n% the power at the center frequency (signal of interest) while simultaneously suppressing it\n% at the flanking frequency bins (noise band). \n% \n% Example for FREQS:\n% Let us consider that we want to extract oscillations in the 10-12 Hz\n% frequency range. Then we define: \n% freqs = [10 12; 8 14; 9 13]. \n% The first row defines the frequency band of interest, here 10-12 Hz. The \n% second and third row define the pass-pand and stop-band for the noise, respectively.\n% Here we have a passband of 8-14 Hz and a stop-band of 9-13 Hz in order \n% to get the noise activity just below and just above the band of interest.\n%\n%\n%\n% References:\n%\n% Nikulin VV, Nolte G, Curio G. A novel method for reliable and fast extraction\n% of neuronal EEG/MEG oscillations on the basis of spatio-spectral decomposition.\n% NeuroImage, 2011, 55: 1528-1535.\n%\n% Haufe, S., Dahne, S., & Nikulin, V. V. Dimensionality reduction for the \n% analysis of brain oscillations. NeuroImage, 2014 (accepted for publication)\n% DOI: 10.1016/j.neuroimage.2014.06.073\n\nprops= {'filterOrder' 3 'INT'\n 'epochIndices' [] 'DOUBLE[- -2]'};\n\nif nargin==0,\n dat = props; return\nend\n\ndat = misc_history(dat);\nmisc_checkType(dat, 'STRUCT(x clab fs)'); \nopt = opt_proplistToStruct(varargin{:});\nopt = opt_setDefaults(opt, props);\nopt_checkProplist(opt, props); \n\n%% check if data is segmented or continous\nis_epoched = ndims(dat.x) == 3;\nif is_epoched\n % if the data is segmented (i.e. epoched), then concatenate epochs\n [Te, Nc, Ne] = size(dat.x);\n dat.x = reshape(permute(dat.x, [1,3,2]), [Te*Ne, Nc]);\nend\n \n%% compute SSD\n[W, A, lambda, ~, X_ssd] = ssd(dat.x, freqs, dat.fs, opt.filterOrder, opt.epochIndices);\n\n%% store the bandpass-filtered data, projected onto the SSD filters\n\n% make sure to put the data in the correct format \nif is_epoched\n X_ssd = permute(reshape(X_ssd, [Te, Ne, size(X_ssd,2)]), [1,3,2]);\nend\n% store the transformed data\ndat.x = X_ssd;\n\n\n%% rename channel labels and save old channel labels\ndat.origClab= dat.clab;\ndat.clab=cell(1,size(dat.x,2));\nfor k=1:size(dat.x,2)\n dat.clab{k} = sprintf('ssd %d',k);\nend\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_ssd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199592797929, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.5455878465560648}} {"text": "% Multi-Frame Analysis based on Discrete Cepstral Envelope (DCE-MFA)\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% Dk : [log] Log energy corrections\n% af : As in input, plus the aligned amplitudes values in the\n% 'a' field.\n% E : The amplitude cepstral envelope\n% \n% References\n% [1] Y. Shiga and S. King, \"Estimation of voice source and vocal tract \n% characteristics based on multi-frame analysis,\" EUROSPEECH, 2003.\n% [2] M. Campedel-Oudot, O. Cappe and E. Moulines, \"Estimation of the Spectral\n% Envelope of Voiced Sounds Using a Penalized Likelihood Approach\"\n%\n% Copyright (c) Yannis Stylianou, 2011, Bilbao\n%\n% License\n% This file is part of libphoni. libphoni is free software: 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. libphoni 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% Authors\n% Yannis Stylianou \n% Gilles Degottex (regularization term)\n%\n\nfunction [cc Dk af E] = env_dce_mfa(af, fs, order, extrap_dcny, scale, Bw, lr, dftlen)\n\n debug = 0; % 0:Do nothing; 1:Plot iterations info; 2:Plot results\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% 2kHz with 16kHz[1]\n if nargin<7 || isempty(lr); lr = 0; end\n if nargin<8; dftlen=4096; end\n\n if ~isempty(scale)\n Bw = 100*fs; % To make it as similar as possible to the DCE-SFA\n lr = 3.5e-2; % To make it as similar as possible to the DCE-SFA [2]\n eval(['fnscale=@frq2' scale ';']);\n for n=1:numel(af)\n af(n).f = 0.5*fs*fnscale(af(n).f)/fnscale(fs/2);\n end\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 for n=1:numel(af)\n af(n).f = af(n).sins(1,:);\n af(n).a = log(af(n).sins(2,:));\n end\n\n if debug>1; subplot(211); hold off; end\n\n M = length(af);\n\n BWB = 0; % [1](9)\n erI = 0; % Error of previous step (initialization error)\n iter = 0; % Iteration number\n cc = zeros(order+1,1); % initialization for ceps\n rt = 0;\n\n for k=1:M\n fk = af(k).f;\n ak = af(k).a;\n Nk = length(fk);\n fk = fk(:);\n ak = ak(:);\n Bk = [ones(Nk,1) 2*cos(2*pi*fk/fs*(1:order))];\n\n wk = exp(-fk.^2 / (2 * Bw * Bw))'; % Bottom-right paragraph p.3\n Wk = diag(wk)/Nk; % (8)\n\n % keep the main matrices\n BWB = BWB+(Bk'*Wk*Bk); % order by order\n af(k).Bk = Bk; % keep Bk\n af(k).Wk = Wk; % keep Wk\n uk = ones(Nk,1);\n\n dk = uk'*Wk*(ak)/(uk'*Wk*uk); % (10) with c=0\n erI = erI + ((ak-dk*uk)'*Wk*(ak-dk*uk));% (7) with c=0\n rt = rt + (Bk'*Wk*(ak-dk*uk)); % Right-hand term of (9)\n end\n\n if debug>0; disp(['iter:' num2str(iter) ' error=' num2str(erI) 'log']); end\n\n % first estimation of ceps\n if lr==0\n cc = BWB\\rt; % Solution of (9)\n else\n cc = (BWB+lr*diag(ones(size(BWB,1),1)))\\rt; % Solution of (9) + Regul term\n end\n cc(1) = 0;\n\n iter = 1;\n while(1)\n er = 0;\n rt = 0; % Right-hand term of (9)\n Dk = zeros(M,1); % log energy corrections\n\n for k=1:M \n ak = af(k).a;ak= ak(:);\n Bk = af(k).Bk;\n Wk = af(k).Wk;\n\n Nk = length(ak);\n uk = ones(Nk,1);\n\n dk = uk'*Wk*(ak-Bk*cc)/(uk'*Wk*uk);% (10)\n h = (ak-dk*uk-Bk*cc);\n er = er + (h'*Wk*h);% (7)\n rt = rt + (Bk'*Wk*(ak-dk*uk)); % Right-hand term of (9)\n\n Dk(k) = dk;\n end\n if lr==0\n cc = BWB\\rt; % Solution of (9)\n else\n cc = (BWB+lr*diag(ones(size(BWB,1),1)))\\rt; % Solution of (9) + Regul term\n end\n cc(1) = 0;\n\n if debug>0; disp(['iter:' num2str(iter) ' error=' num2str(er) 'log']); end\n % disp(['reldiff=' num2str(abs((erI-er)/er))]);\n\n if debug>1\n % plot\n subplot(211);\n plot(iter-1,log(erI), 'o');\n hold on\n plot(iter,log(er), 'x');\n title(num2str(iter));\n subplot(212);\n hold off;\n for k=1:M\n plot(af(k).f,af(k).a-Dk(k),'+');\n hold on;\n end\n dftlen = 2048;\n fv = fs*(0:dftlen/2)/dftlen;\n lF = 2*cos(2*pi*fv'/fs*(1:order))*cc(2:order+1);\n plot(fv,lF,'r', 'LineWidth', 2);\n keyboard\n end\n\n if( abs((erI-er)/er)<0.001 ) % Stop if error doesn't improve more than 0.1%\n break;\n else\n erI = er;\n iter = iter+1;\n end\n end\n\n\n % Align the gain corrections with respect to the central frame\n ci = floor((numel(af)-1)/2)+1;\n cc(1) = cc(1)+Dk(ci);\n Dk = Dk - Dk(ci);\n cc(2:end) = 2*cc(2:end);\n\n % Include the log energy corrections into the output\n for fi=1:numel(af)\n af(fi).a = af(fi).a - Dk(fi);\n end\n\n % If asked, compute the envelope\n if nargout>2\n if isempty(scale)\n E = exp(fft(cc, dftlen));\n E = 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\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_mfa.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.5455878378585399}} {"text": "% WAVELET_3D_PYRAMID Compute the roto-translation wavelet transfrom\n%\n% Usage\n% [y_Phi, y_Psi, meta_Phi, meta_Psi] = wavelet_3d_pyramid(y, filters, filters_rot, options)\n%\n% Input\n% y (numeric): a 3d matrix whose first two dimension corresponds to spatial\n% postion and third dimension corresponds to orientation.\n% filters (struct): a 2d pyramid filter bank (applied along spatial variable)\n% filters_rot (struct): a 1d filter bank (applied along orientation)\n% options (struct): containing the following optional fields\n% x_resolution (int): the log of spatial resolution\n% psi_mask (bool array): a mask for determining which filter to apply\n% oversampling (int): the log of spatial oversampling\n% oversampling_rot (int): the log of orientation oversampling\n%\n% Output\n% y_Phi (numeric): the roto-translation convolution y * Phi\n% y_Psi (cell): containing all the roto-translation convolution y * Psi\n% meta_phi (struct): meta associated to y_Phi\n% meta_psi (struct): meta associated to y_Psi\n%\n% Description\n% This is a pyramid implementation of the roto-translation wavelet\n% transform. Another (slower, FFT-based) implementation is available as\n% WAVELET_3D.\n%\tThis function computes the roto-translation convolution of a three dimensional\n%\tsignal y, with roto-translation wavelets defined as the separable product\n%\tlow pass :\n%\t\tPHI(U,V) * PHI(THETA)\n%\thigh pass :\n%\t\tPHI(U,V) * PHI(THETA)\n%\t\tPSI(U,V) * PHI(THETA)\n%\t\tPSI(U,V) * PSI(THETA)\n%\n% Reference\n%\tRotation, Scaling and Deformation Invariant Scattering for Texture\n%\tDiscrimination, Laurent Sifre, Stephane Mallat\n%\tProc of CVPR 2013\n%\thttp://www.cmapx.polytechnique.fr/~sifre/research/cvpr_13_sifre_mallat_final.pdf\n%\n% See also\n% WAVELET_LAYER_3D, WAVELET_FACTORY_3D\n\nfunction [y_Phi, y_Psi, meta_Phi, meta_Psi] = wavelet_3d_pyramid(y,...\n filters, filters_rot, options)\n \n % retrieve info on input\n Q = filters.meta.Q;\n L = filters_rot.meta.size_filter / 2;\n % do not compute any convolution with high pass if y_Psi is not\n % outputed\n calculate_psi = (nargout>=2);\n [N, M, T] = size(y);\n \n % retrieve options\n white_list = {'J', 'angular_range', 'oversampling_rot', 'j_min', 'q_mask'};\n check_options_white_list(options, white_list);\n options = fill_struct(options, 'J', 4);\n options = fill_struct(options, 'angular_range', 'non_specified');\n options = fill_struct(options, 'oversampling_rot', -1);\n options = fill_struct(options, 'j_min', 0);\n options = fill_struct(options, 'q_mask', ones(1, Q));\n \n % angular resolution\n switch (options.angular_range)\n case 'zero_pi'\n angular_res = floor(log2(2*L/(2*T)));\n case 'zero_2pi'\n angular_res = floor(log2(2*L/T));\n otherwise\n error('unspecified angular range');\n end\n \n if (isa(filters.h.filter.coefft, 'single'))\n cast = @single;\n else\n cast = @double;\n end\n \n %%%%%%%%%%%%%%%%%%\n %%% low passes %%%\n %%%%%%%%%%%%%%%%%%\n \n %%%%%%%%%%%%%%%%%%\n %%% phi - phi %%%%\n %%%%%%%%%%%%%%%%%%\n \n %% low pass filter spatial : cascade with h for every slice\n % initialize structure\n hy.signal{1} = y;\n hy.meta.j(1) = 0;\n \n % low pass spatial using a pyramid\n h = filters.h.filter;\n for j = 1:options.J\n for theta = 1:T % filter each slice\n if (theta == 1) % allocate when size is known\n tmp_slice = pad_conv_sub_unpad(hy.signal{j}(:,:,theta), h);\n tmp = cast(zeros([size(tmp_slice), T]));\n tmp(:,:,theta) = tmp_slice;\n else\n clear tmp_slice;\n tmp(:,:,theta) = ...\n pad_conv_sub_unpad(hy.signal{j}(:,:,theta), h);\n end\n end\n hy.signal{j+1} = tmp;\n hy.meta.j(j+1) = j;\n end\n y_phi.signal{1} = hy.signal{options.J+1};\n y_phi.meta.j(1) = hy.meta.j(options.J+1);\n \n %% low pass filter anguler : fft along anguler\n % initialize structure (recopy if range is zero_pi)\n ds = max(filters_rot.meta.J/filters_rot.meta.Q - options.oversampling_rot, 0);\n if (2^ds == 2*L)\n % in this case it is faster to compute the sum along the angle\n y_Phi = sum(y_phi.signal{1},3) / 2^(ds/2);\n else\n if (strcmp(options.angular_range, 'zero_pi'))\n % divide by sqrt(2) for energy preservation\n y_phi.signal{1} = repmat(y_phi.signal{1}, [1 1 2]) / sqrt(2);\n end\n y_phi_f = fft(y_phi.signal{1}, [], 3);\n phi_angle = filters_rot.phi.filter;\n y_Phi = real(...\n sub_conv_1d_along_third_dim_simple(y_phi_f, phi_angle, ds));\n end\n meta_Phi.j2 = options.J;\n meta_Phi.k2 = filters_rot.meta.J;\n \n \n %%\n \n %%%%%%%%%%%%%%%%%%%\n %%% high passes %%%\n %%%%%%%%%%%%%%%%%%%\n \n if (calculate_psi)\n p = 1;\n %%%%%%%%%%%%%%%%%%\n %%% phi - psi %%%%\n %%%%%%%%%%%%%%%%%%\n \n %% low pass spatial - already computed\n %% high pass angular\n % NOTE : y_phi_f\n % (the (angular) fourier transform of y * (spatial) phi)\n % might have already been computed\n if ~exist('y_phi_f', 'var')\n % fourier angle\n if (strcmp(options.angular_range, 'zero_pi'))\n % divide by sqrt(2) for energy preservation\n y_phi.signal{1} = repmat(y_phi.signal{1}, [1 1 2]) / sqrt(2);\n end\n y_phi_f = fft(y_phi.signal{1}, [], 3);\n end\n for k2 = 0:numel(filters_rot.psi.filter)-1\n psi_angle = filters_rot.psi.filter{k2+1};\n ds = max(k2/filters_rot.meta.Q - options.oversampling_rot, 0);\n y_Psi{p} = ...\n sub_conv_1d_along_third_dim_simple(y_phi_f, psi_angle, ds);\n meta_Psi.j2(p) = options.J;\n meta_Psi.q2(p) = 0;\n meta_Psi.theta2(p) = 0;\n meta_Psi.k2(p) = k2;\n p = p + 1;\n end\n \n \n %%%%%%%%%%%%%%%%%%\n %%% psi - phi %%%%\n %%%%%%%%%%%%%%%%%%\n % AND %\n %%%%%%%%%%%%%%%%%%\n %%% psi - phi %%%%\n %%%%%%%%%%%%%%%%%%\n \n %% high pass spatial - with pyramid\n if (angular_res == 0)\n g = filters.g.filter;\n \n for j2 = options.j_min:options.J-1\n for q = find(options.q_mask==1)-1\n for theta2 = 1:L\n if (strcmp(options.angular_range, 'zero_pi'))\n for theta = 1:L\n % convolution with psi_{j1, theta + theta2}\n theta_sum_mod2L = 1 + mod(theta + theta2 - 2, 2*L);\n theta_sum_modL = 1 + mod(theta + theta2 - 2, L);\n tmp_slice = pad_conv_unpad(hy.signal{j2+1}(:,:,theta), g{theta_sum_modL + L*q});\n if (theta == 1) % allocate\n tmp = cast(zeros([size(tmp_slice), 2*L]));\n end\n if (theta_sum_mod2L <= L)\n tmp(:,:,theta) = tmp_slice;\n tmp(:,:,theta+L) = conj(tmp_slice);\n else\n tmp(:,:,theta) = conj(tmp_slice);\n tmp(:,:,theta+L) = tmp_slice;\n end\n end\n else % options.angular_range is 'zero_2pi'\n for theta = 1:2*L\n % convolution with psi_{j1, theta + theta2}\n theta_sum_mod2L = 1 + mod(theta + theta2 - 2, 2*L);\n theta_sum_modL = 1 + mod(theta + theta2 - 2, L);\n if (theta_sum_mod2L <= L)\n curr_g = g{theta_sum_modL + L*q};\n else\n curr_g = conjugate_filter(g{theta_sum_modL + L*q});\n end\n tmp_slice = pad_conv_unpad(hy.signal{j2+1}(:,:,theta), curr_g);\n if (theta == 1) % allocate\n tmp = cast(zeros([size(tmp_slice), 2*L]));\n end\n tmp(:,:,theta) = tmp_slice;\n \n end\n end\n \n % tmp can now be filtered along the orientation\n tmp_f = fft(tmp, [], 3);\n %% low pass angle\n ds = min(2*L, max(filters_rot.meta.J/filters_rot.meta.Q - options.oversampling_rot, 0));\n if (2^ds == 2*L)\n % faster to compute the sum along the angle\n y_Psi{p} = sum(tmp, 3) / 2^(ds/2);\n else\n y_Psi{p} = ...\n sub_conv_1d_along_third_dim_simple(tmp_f, phi_angle, ds);\n end\n meta_Psi.j2(p) = j2;\n meta_Psi.theta2(p) = theta2;\n meta_Psi.k2(p) = filters_rot.meta.J;\n meta_Psi.q2(p) = q;\n p = p + 1;\n \n %% high pass angle\n for k2 = 0:numel(filters_rot.psi.filter)-1\n psi_angle = filters_rot.psi.filter{k2+1};\n ds = max(k2/filters_rot.meta.Q - options.oversampling_rot, 0);\n y_Psi{p} = ...\n sub_conv_1d_along_third_dim_simple(tmp_f, psi_angle, ds);\n meta_Psi.j2(p) = j2;\n meta_Psi.theta2(p) = theta2;\n meta_Psi.k2(p) = k2;\n meta_Psi.q2(p) = q;\n p = p + 1;\n end\n \n end\n end\n end\n else\n error('not yet supported');\n end\n \n \n end\n \n function out = pad_conv_sub_unpad(in, filter)\n Npad = size(in) + filters.meta.size_filter - 1;\n out = pad_signal(in, Npad, 'symm', 1);\n out = conv_sub_2d(out, filter, 1);\n out = unpad_signal(out, 1, size(in), filters.meta.offset);\n end\n \n \n function out = pad_conv_unpad(in, filter)\n Npad = size(in) + filters.meta.size_filter - 1;\n out = pad_signal(in, Npad, 'symm', 1);\n out = conv_sub_2d(out, filter, 0);\n out = unpad_signal(out, 0, size(in), filters.meta.offset);\n end\n \n function conj_filter = conjugate_filter(filter)\n conj_filter = filter;\n conj_filter.coefft = conj(filter.coefft);\n end\nend\n\n", "meta": {"author": "scatnet", "repo": "scatnet", "sha": "59d935afa20359845282a3518134e24244862c1f", "save_path": "github-repos/MATLAB/scatnet-scatnet", "path": "github-repos/MATLAB/scatnet-scatnet/scatnet-59d935afa20359845282a3518134e24244862c1f/core/wavelet_3d_pyramid.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8418256631249076, "lm_q2_score": 0.6477982043529715, "lm_q1q2_score": 0.5453331529505646}} {"text": "function [w, infos] = subsamp_tr(problem, in_options)\n\n% Trust Region Method \n% Authors: Jonas Kohler and Aurelien Lucchi, 2017\n\n% Minimize a continous, unconstrained function using the Trust Region method.\n% \n% References\n% ----------\n% Conn, A. R., Gould, N. I., & Toint, P. L. (2000). Trust region methods. Society for Industrial and Applied Mathematics.\n% \n%\n% Original Python code was created by J. M. Kohler and A. Lucchi (https://github.com/dalab/subsampled_cubic_regularization)\n%\n%\n% This file is part of SGDLibrary.\n%\n% Ported to MATLAB code by K.Yoshikawa and H.Kasai on March, 2018.\n% Modified by H.Kasai on Apr. 17, 2018 \n\n\n % set dimensions and samples\n d = problem.dim();\n n = problem.samples(); \n \n %% set local options \n local_options.sampling_scheme = 'exponential'; % 'linear', 'exponential'\n local_options.penalty_increase_multiplier = 2; % multiply by..\n local_options.penalty_derease_multiplier = 2; % divide by..\n local_options.initial_tr_radius = 1;\n local_options.successful_treshold = 0.1;\n local_options.very_successful_treshold = 0.9;\n local_options.grad_tol = 1e-9;\n local_options.max_trust_radius = 1e4;\n\n % sampling\n local_options.Hessian_sampling = 1;\n local_options.gradient_sampling = 0;\n local_options.initial_sample_size_Hessian = 0.025;\n local_options.initial_sample_size_gradient = 0.25;\n\n % subproblem\n local_options.subproblem_solver = 'GLTR'; \n\n\n local_options.krylov_tol = 1e-1;\n local_options.exact_tol = 1e-2;\n \n % merge options\n options = mergeOptions(get_default_options(d), local_options); \n options = mergeOptions(options, in_options); \n \n if options.verbose > 1\n fprintf('- Subproblem_solver:%s\\n', options.subproblem_solver)\n fprintf('- Hessian_sampling:%d\\n', options.Hessian_sampling)\n fprintf('- Gradient_sampling:%d\\n', options.gradient_sampling)\n fprintf('- Sampling_scheme:%s\\n\\n', options.sampling_scheme)\n end\n \n % decide mode\n if options.gradient_sampling == 0 && options.Hessian_sampling == 0\n mode = 'TR';\n else\n mode = 'Subsamp TR';\n end \n \n\n % initialize\n iter = 0;\n grad_calc_count = 0;\n w = options.w_init;\n lambda_k = 0;\n successful_flag = false;\n tr_radius = options.initial_tr_radius; % intial tr radius \n\n grad = problem.full_grad(w);\n \n % compute exponential growth constant such that full sample size is reached in n_iterations\n if strcmp(options.sampling_scheme, 'exponential')\n exp_growth_constant = ((1-options.initial_sample_size_Hessian)*n)^(1/options.max_iter);\n end\n \n % store first infos\n clear infos; \n [infos, f_val, optgap] = store_infos(problem, w, options, [], iter, grad_calc_count, 0);\n \n % display infos\n if options.verbose > 0\n fprintf('%s: : Iter = %03d, cost = %.16e, optgap = %.4e\\n', mode, iter, f_val, optgap);\n end \n\n % set start time\n start_time = tic();\n \n for i = 0 : options.max_iter-1\n \n %% I: Subsampling \n % a) determine batchsize\n if strcmp(options.sampling_scheme, 'exponential')\n \n sample_size_Hessian = options.Hessian_sampling*(fix(min([n, n*options.initial_sample_size_Hessian + exp_growth_constant^(i+1)]))+1) + (1-options.Hessian_sampling)*n;\n sample_size_gradient = options.gradient_sampling*(fix(min([n, n*options.initial_sample_size_gradient + exp_growth_constant^(i+1)]))+1) + (1-options.gradient_sampling)*n;\n \n elseif strcmp(options.sampling_scheme, 'linear')\n \n sample_size_Hessian = options.Hessian_sampling*fix(min([n, max([n*options.initial_sample_size_Hessian, n/options.max_iter*(i+1)])]))+(1-options.Hessian_sampling)*n;\n sample_size_gradient = options.gradient_sampling*fix(min([n, max([n*options.initial_sample_size_gradient, n/options.max_iter*(i+1)])]))+(1-options.gradient_sampling)*n;\n \n elseif strcmp(options.sampling_scheme, 'fix') % Added by HK\n\n sample_size_Hessian = options.Hessian_sampling*fix(min(n, n*options.initial_sample_size_Hessian))+(1-options.Hessian_sampling)*n;\n sample_size_gradient = options.gradient_sampling*fix(min(n, n*options.initial_sample_size_gradient))+(1-options.gradient_sampling)*n;\n \n else\n \n sample_size_Hessian = n;\n sample_size_gradient = n;\n \n end\n \n % b) draw batches\n if sample_size_Hessian < n\n int_idx_Hessian = randi([1, n], sample_size_Hessian,1); % KY\n bool_idx_Hessian = false(n,1);\n bool_idx_Hessian(int_idx_Hessian) = true;\n sub_hess_indices = find(bool_idx_Hessian); \n else\n sub_hess_indices = 1:n;\n end\n \n if sample_size_gradient < n\n int_idx_gradient = randi([1, n], sample_size_gradient,1);\n bool_idx_gradient = false(n,1);\n bool_idx_gradient(int_idx_gradient) = true;\n sub_grad_indices = find(bool_idx_gradient); \n else\n sub_grad_indices = 1:n;\n end\n \n n_samples_per_step = sample_size_Hessian+sample_size_gradient;\n \n \n % recompute gradient either because of accepted step or because of re-sampling\n if options.gradient_sampling == 1 || successful_flag == 1\n %grad = gradient_f(w, new_X2, new_Y2, alpha);\n grad = problem.grad(w, sub_grad_indices');\n grad_norm = norm(grad);\n if grad_norm < options.grad_tol\n fprintf('Norm of gradient (%e) reached: grad_tol = %g\\n', grad_norm, options.grad_tol);\n break;\n end\n end \n \n %% II: Step computation\n % b) call subproblem solver\n [s, lambda_k] = tr_subsolver(problem, w, grad, tr_radius, sub_hess_indices, successful_flag, lambda_k, options.subproblem_solver,...\n options.exact_tol, options.krylov_tol);\n\n %sn = norm(s);\n \n %% III: Regularization Update \n f_prev = problem.cost(w);\n f_curr = problem.cost(w+s); \n function_decrease = f_prev - f_curr; % f(w) - f(w+w)\n \n %Hs = Hv_f(w, new_X, new_Y, s, alpha);\n Hs = problem.hess_vec(w, s, sub_hess_indices);\n \n model_decrease = -((grad'*s) + 0.5 * (s'*Hs));\n\n rho = function_decrease / model_decrease;\n \n if model_decrease >=0\n if options.verbose > 2\n fprintf('\\tNegative model decrease (%e). This should not have happened\\n', model_decrease);\n end\n end \n\n % update w if step s is successful\n if rho >= options.successful_treshold\n w = w + s;\n loss = f_curr;\n successful_flag = true;\n accstr = 'ACC';\n else\n loss = f_prev;\n accstr = 'REJ';\n end\n \n % Update trust region radius\n tr_radius_ = tr_radius;\n if rho < options.successful_treshold\n tr_radius = tr_radius * (1/options.penalty_increase_multiplier);\n %fprintf('unscuccesful iteration\\n');\n successful_flag = false;\n trstr = 'TR-';\n elseif rho > options.very_successful_treshold && ((norm(s) - tr_radius) < 1e-10)\n tr_radius = min([options.penalty_derease_multiplier * tr_radius, options.max_trust_radius]);\n trstr = 'TR+';\n else\n trstr = ' ';\n end\n \n% % recompute gradient either because of accepted step or because of re-sampling\n% if options.gradient_sampling == 1 || successful_flag == 1\n% %grad = gradient_f(w, new_X2, new_Y2, alpha);\n% grad = problem.grad(w, sub_grad_indices');\n% grad_norm = norm(grad);\n% if grad_norm < options.grad_tol\n% break;\n% end\n% end\n\n \n % measure elapsed time\n elapsed_time = toc(start_time);\n \n % count gradient evaluations\n grad_calc_count = grad_calc_count + n_samples_per_step; \n iter = iter + 1;\n\n % store infos\n [infos, f_val, optgap] = store_infos(problem, w, options, infos, iter, grad_calc_count, elapsed_time); \n\n % display infos\n if options.verbose > 0\n fprintf('%s: %s %s: Iter = %03d, cost = %.16e, optgap = %.4e', mode, accstr, trstr, iter, f_val, optgap);\n if options.verbose > 1\n fprintf(', sample (H,G)= (%d, %d)\\n', sample_size_Hessian, sample_size_gradient)\n else\n fprintf('\\n');\n end \n end\n \n if optgap < options.tol_optgap\n fprintf('Optimality gap tolerance reached: tol_optgap = %g\\n', options.tol_optgap);\n break;\n end\n end\n \n \n if iter == options.max_iter\n fprintf('Max epoch reached: max_iter = %g\\n', options.max_iter);\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/sgd_solver/subsamp_tr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324983301568, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.5452929203649576}} {"text": "function gram_vector = find_gram_vector(samplesf, new_sample, num_training_samples, params)\n% Find the inner product of the new sample with the existing samples. TO be\n% used for distance calculation\n\n% Note: Since getting the 'exact' distance between the samples is not important,\n% the inner product computation is done by using only the half spectrum for\n% efficiency. In practice the error incurred by this is negligible. Also\n% since we wannt to merge samples that are similar, and finding the best\n% match is not important, small error in the distance computation doesn't\n% matter\n\ngram_vector = inf(params.nSamples,1,'like', params.data_type);\n\nnum_feature_blocks = numel(new_sample);\n\nif num_training_samples == params.nSamples\n % This if statement is only for speed\n ip = zeros(1,'like', params.data_type);\n for k = 1:num_feature_blocks\n ip_block = 2*reshape(samplesf{k}, num_training_samples, []) * conj(new_sample{k}(:));\n ip = ip + real(ip_block);\n end\n \n gram_vector = ip;\nelseif num_training_samples > 0\n ip = zeros(1,'like', params.data_type);\n for k = 1:num_feature_blocks\n ip_block = 2*reshape(samplesf{k}(1:num_training_samples,:,:,:),num_training_samples, []) * conj(new_sample{k}(:));\n ip = ip + real(ip_block);\n end\n \n gram_vector(1:num_training_samples) = ip;\nend\nend\n\n\n", "meta": {"author": "martin-danelljan", "repo": "ECO", "sha": "27e8ae565cd63ec14bafcaad8b5b993bec8f3e69", "save_path": "github-repos/MATLAB/martin-danelljan-ECO", "path": "github-repos/MATLAB/martin-danelljan-ECO/ECO-27e8ae565cd63ec14bafcaad8b5b993bec8f3e69/implementation/sample_space_model/find_gram_vector.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232480373843, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5452929191163846}} {"text": "function [K] = kv1u1(x, y, xp, yp, hyp, i)\n\nlogsigma = hyp(1);\nlogthetax = hyp(2);\nlogthetay = hyp(3);\n\nn_x = size(x,1);\nn_y = size(y,1);\nn_xp = size(xp,1);\nn_yp = size(yp,1);\n\nx = repmat(x,1,n_xp);\ny = repmat(y,1,n_yp);\nxp = repmat(xp',n_x,1);\nyp = repmat(yp',n_y,1);\n\nswitch i\n\n\ncase 0\n\nK=exp(1).^(logsigma+(-1).*logthetax+(-1).*logthetay+(-1/2).*exp(1).^((-1) ...\n .*logthetax).*(x+(-1).*xp).^2+(-1/2).*exp(1).^((-1).*logthetay).*(y+(-1) ...\n .*yp).^2).*(x+(-1).*xp).*(y+(-1).*yp);\n\n\ncase 1 % logsigma\n\nK=exp(1).^(logsigma+(-1).*logthetax+(-1).*logthetay+(-1/2).*exp(1).^((-1) ...\n .*logthetax).*(x+(-1).*xp).^2+(-1/2).*exp(1).^((-1).*logthetay).*(y+(-1) ...\n .*yp).^2).*(x+(-1).*xp).*(y+(-1).*yp);\n\n\ncase 2 % logthetax\n\nK=exp(1).^(logsigma+(-1).*logthetax+(-1).*logthetay+(-1/2).*exp(1).^((-1) ...\n .*logthetax).*(x+(-1).*xp).^2+(-1/2).*exp(1).^((-1).*logthetay).*(y+(-1) ...\n .*yp).^2).*((-1)+(1/2).*exp(1).^((-1).*logthetax).*(x+(-1).*xp).^2).*(x+ ...\n (-1).*xp).*(y+(-1).*yp);\n\n\ncase 3 % logthetay\n\nK=exp(1).^(logsigma+(-1).*logthetax+(-1).*logthetay+(-1/2).*exp(1).^((-1) ...\n .*logthetax).*(x+(-1).*xp).^2+(-1/2).*exp(1).^((-1).*logthetay).*(y+(-1) ...\n .*yp).^2).*(x+(-1).*xp).*((-1)+(1/2).*exp(1).^((-1).*logthetay).*(y+(-1) ...\n .*yp).^2).*(y+(-1).*yp);\n\n\notherwise\n \n K = zeros(n_x, n_xp);\nend\n\nend\n", "meta": {"author": "maziarraissi", "repo": "HPM", "sha": "21a7429cceb55d5ab688256db75ac360e2d8a925", "save_path": "github-repos/MATLAB/maziarraissi-HPM", "path": "github-repos/MATLAB/maziarraissi-HPM/HPM-21a7429cceb55d5ab688256db75ac360e2d8a925/Kernels/Navier_Stokes/+k11/kv1u1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110511888303, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5452372002813582}} {"text": "function [rVect, vVect] = getStateAtTime_alg(time, sma, ecc, inc, raan, arg, mean, epoch, gmu)\n%getStateAtTime Summary of this function goes here\n% Detailed explanation goes here\n numTimes = length(time);\n\n oneArray = (zeros(1, numTimes)+1);\n \n sma = sma * oneArray;\n ecc = ecc * oneArray;\n inc = AngleZero2Pi(deg2rad(inc)) * oneArray;\n raan = AngleZero2Pi(deg2rad(raan)) * oneArray;\n arg = AngleZero2Pi(deg2rad(arg)) * oneArray;\n M0 = deg2rad(mean) * oneArray; \n \n n = computeMeanMotion(sma, gmu);\n deltaT = time - epoch;\n M = (M0(:) + n(:).*deltaT(:))';\n tru = computeTrueAnomFromMean(M, ecc);\n\n if(length(tru) > 1)\n [rVect,vVect] = vect_getStatefromKepler(sma, ecc, inc, raan, arg, tru, gmu, false); \n else\n [rVect, vVect] = getStatefromKepler_Alg(sma, ecc, inc, raan, arg, tru, gmu);\n end\n \n rVect(isnan(rVect)) = 0;\n vVect(isnan(vVect)) = 0;\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/getStateAtTime_alg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232809, "lm_q2_score": 0.6261241842048092, "lm_q1q2_score": 0.545102008657494}} {"text": "function [R,eff] = randmio_und_connected(R, ITER)\n%RANDMIO_UND_CONNECTED Random graph with preserved degree distribution\n%\n% R = randmio_und_connected(W,ITER);\n% [R eff] = randmio_und_connected(W, ITER);\n%\n% This function randomizes an undirected network, while preserving the \n% degree distribution. The function does not preserve the strength \n% distribution in weighted networks. The function also ensures that the \n% randomized network maintains connectedness, the ability for every node \n% to reach every other node in the network. The input network for this \n% function must be connected.\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% References: Maslov and Sneppen (2002) Science 296:910\n%\n%\n% 2007-2012\n% Mika Rubinov, UNSW\n% Jonathan Power, WUSTL\n% Olaf Sporns, IU\n\n% Modification History:\n% Jun 2007: Original (Mika Rubinov)\n% Apr 2008: Edge c-d is flipped with 50% probability, allowing to explore\n% all potential rewirings (Jonathan Power)\n% Mar 2012: Limit number of rewiring attempts, count number of successful\n% rewirings (Olaf Sporns)\n\n\nn=size(R,1);\n[i,j]=find(tril(R));\nK=length(i);\nITER=K*ITER;\n\n% maximal number of rewiring attempts per 'iter'\nmaxAttempts= round(n*K/(n*(n-1)));\n% actual number of successful rewirings\neff = 0;\n\nfor iter=1:ITER\n att=0;\n while (att<=maxAttempts) %while not rewired\n rewire=1;\n while 1\n e1=ceil(K*rand);\n e2=ceil(K*rand);\n while (e2==e1),\n e2=ceil(K*rand);\n end\n a=i(e1); b=j(e1);\n c=i(e2); d=j(e2);\n\n if all(a~=[c d]) && all(b~=[c d]);\n break %all four vertices must be different\n end\n end\n\n if rand>0.5\n i(e2)=d; j(e2)=c; \t%flip edge c-d with 50% probability\n c=i(e2); d=j(e2); \t%to explore all potential rewirings\n end\n \n %rewiring condition\n if ~(R(a,d) || R(c,b))\n %connectedness condition\n if ~(R(a,c) || R(b,d))\n P=R([a d],:);\n P(1,b)=0; P(2,c)=0;\n PN=P;\n PN(:,d)=1; PN(:,a)=1; \n \n while 1\n P(1,:)=any(R(P(1,:)~=0,:),1);\n P(2,:)=any(R(P(2,:)~=0,:),1);\n P=P.*(~PN);\n if ~all(any(P,2))\n rewire=0;\n break\n elseif any(any(P(:,[b c])))\n break\n end\n PN=PN+P;\n end\n end %connectedness testing\n\n if rewire %reassign edges\n R(a,d)=R(a,b); R(a,b)=0;\n R(d,a)=R(b,a); R(b,a)=0;\n R(c,b)=R(c,d); R(c,d)=0;\n R(b,c)=R(d,c); R(d,c)=0;\n\n j(e1) = d; %reassign edge indices\n j(e2) = b;\n eff = eff+1;\n break;\n end %edge reassignment\n end %rewiring condition\n att=att+1;\n end %while not rewired\nend %iterations", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/bct/randmio_und_connected.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424217727027, "lm_q2_score": 0.6442251133170357, "lm_q1q2_score": 0.544977352526207}} {"text": "function [out] = idv2idv(n)\n% Outputs a transformation matrix for changing from forward to reverse order.\n%\n% order 1 (Jennie's)\n%\n% 000, 001, 010, 011, 100, 101, 110, 111\n%\n% order 2 (mine)\n%\n% 000, 100, 010, 110, 001, 101, 011, 111\n%\n% USAGE:\n%\n% [out] = idv2idv(n)\n%\n% INPUT:\n% n: matrix, size of matrix `(2^n x 2^n)`\n%\n% OUTPUT:\n% out: transforamtion matrix\n\nwarning('are you sure you want to call this function?');\n\nif n <= 0\n out = 1;\n return;\nend\n\nout = sparse(2^n,2^n);\nfor i = 0:(2^n-1)\n t = dec2bin(i,n);\n t2 = t(end:-1:1);\n i2 = bin2dec(t2);\n out(i+1,i2+1) = 1;\nend\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/src/dataIntegration/fluxomics/c13solver/idv2idv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085146, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.5449773451997163}} {"text": "%%***********************************************************************\n%% fapproblem:\n%%\n%% (primal prob.) min Tr C*X\n%% s.t. diag(X) = e \n%% -Eij * X = 2/(k-1) if (i,j) in U\n%% -Eij * X <= 2/(k-1) if (i,j) in GU\n%% where Eij = ei*ej' + ej*ei'\n%% b = e\n%% C = (1/2)*Diag(We) - (k-1)/(2k) *L(G)\n%% SignP(i,j) = 1 if (i,j) in GU, 2 if (i,j) in U; 0 otherwise\n%% M_ij = -1/(k-1) if (i,j) in U or GU; 0 otherwise \n%%-----------------------------------------------------------------------\n%% (primal prob.) min Tr C*X\n%% s.t. diag(X) = e \n%% LL <= X <= UU if (i,j) in U\n%% \n%% where L_ij = -1/(k-1) if (i,j) in U or GU; -inf otherwise, \n%% U_ij = -1/(k-1) if (i,j) in U; inf otherwise \n%% \n%% \n%% \n%% [blk,Avec,C,b,LL,UU,SignP,M,kparm] = fapread_lu(fname);\n%%***********************************************************************\n%% SDPNAL+ \n%% Copyright (c) 2014 by\n%% Liuqin Yang, Defeng Sun, and Kim-Chuan Toh\n%%***********************************************************************\n\n function [blk,Avec,C,b,LL,UU,SignP,M,kparm] = fapread_lu(fname)\n\n%%\n%% read fap data\n%%\n if exist(fname)\n fid = fopen(fname,'r');\n elseif exist([fname,'.dat']); \n fid = fopen([fname,'.dat'],'r');\n else \n fprintf('** Problem not found. \\n'); \n blk = []; Avec = []; C = []; b = [];\n LL =[]; UU =[];SignP = []; M =[]; kparm = [];\n return;\n end\n [tmpr,count] = fscanf(fid,'%c');\n datavec = sscanf(tmpr,'%f'); clear tmpr;\n n = datavec(1); \n numedges = datavec(2);\n kparm = datavec(3); \n datavec = datavec(4:length(datavec)); \n len = length(datavec);\n if (len ~= 3*numedges) \n error(' fapread: numedges and data do not match.'); \n end\n I = datavec(1:3:len); \n J = datavec(2:3:len); \n w = datavec(3:3:len); \n\n idxU = find(w==1000); \n IU = I(idxU); JU = J(idxU); wU = w(idxU);\n U = spconvert([IU JU wU; n n 0]);\n U = U + U'; \n \n idx2 = find(w~=1000); \n I2 = I(idx2); J2 = J(idx2); w2 = w(idx2); \n GU = spconvert([I2 J2 w2; n n 0]); \n GU = GU + GU'; \n \n fclose(fid);\n%%\n%% blk, Avec, C, b\n%% \n n = length(U); \n mU = nnz(triu(U,1)); \n mGU = nnz(triu(GU,1)); \n m = mGU + mU + n; \n\n %%b = [ones(n,1); (2/(kparm-1))*ones(mU+mGU,1)]; \n b = ones(n,1);\n %b = [];\n LG = diag(GU*ones(n,1))-GU;\n C{1,1} = 0.5*(diag(GU*ones(n,1))) - ((kparm-1)/(2*kparm))*LG; \n %%C{2,1} = zeros(mGU,1); \n\n blk{1,1} = 's'; blk{1,2} = n; \n %%blk{2,1} = 'l'; blk{2,2} = mGU; \n%%\n%%\n%%\n r2 = sqrt(2); \n I = zeros(m,1); J = zeros(m,1); w = zeros(m,1); \n cnt = 0; \n e = [1:n]'; \n I(1:n) = e.*(e+1)/2; \n J(1:n) = e; \n w = ones(n,1); \n cnt = cnt+n;\n for i = 1:n \n idx = find(U(i,i+1:n)); \n idx = idx+i; %% adjust index. \n len = length(idx); \n I(cnt+[1:len]) = i + idx.*(idx-1)/2; \n J(cnt+[1:len]) = cnt+[1:len]'; \n w(cnt+[1:len]) = -r2*ones(len,1); \n cnt = cnt + len; \n end \n for i = 1:n\n idx = find(GU(i,i+1:n)); \n idx = idx+i; %% adjust index. \n len = length(idx); \n I(cnt+[1:len]) = i + idx.*(idx-1)/2; \n J(cnt+[1:len]) = cnt+[1:len]'; \n w(cnt+[1:len]) = -r2*ones(len,1); \n cnt = cnt + len; \n end\n Av = spconvert([I,J,w; n*(n+1)/2, m, 0]); \n Avec{1,1} = Av(:,1:n); \n \n sign0 = zeros(n,n);\n sign0(GU ~= 0) = 1;\n sign0(U ~= 0) = 2;\n SignP{1,1} = sign0;\n \n M0 = zeros(n,n);\n M0(sign0 ~= 0) = -1/(kparm-1);\n M{1,1} = M0;\n LL0 = -inf*ones(n,n);\n LL0(sign0 ~= 0) = -1/(kparm-1);\n LL{1,1} = LL0;\n UU0 = inf*ones(n,n);\n UU0(sign0 == 2) = -1/(kparm-1);\n UU{1,1} = UU0;\n%%***********************************************************************\n\n", "meta": {"author": "intellhave", "repo": "SDRSAC", "sha": "b081721e9dfd7843d75aa12f30025b2bd7c8f024", "save_path": "github-repos/MATLAB/intellhave-SDRSAC", "path": "github-repos/MATLAB/intellhave-SDRSAC/SDRSAC-b081721e9dfd7843d75aa12f30025b2bd7c8f024/solvers/SDPNAL+v1.0/util/fapread_lu.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406087, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.5449773401954364}} {"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 [lower, upper] = ...\n UpperBound1(S, g, df, B, beta, lower, Nr, NSim, NSSim, ...\n getpaths, payoff)\n% method from Broadie see Chapter 8\n\nv = g(:, end); % option value at maturity\nc = zeros(NSim,Nr-1); % continuation value\n\nstoppingtime = Nr * ones(NSim,1);\n\n for i=Nr-1:-1:1\n index = find(g(:,i)>0); \n s = S(index, i+1);\n v = v * df(i+1);\n \n Acell = B(s);\n A = cell2mat(Acell{:,:}); \n c(index,i) = A*beta(:,i); % cont value itm paths\n \n earlyexercise = g(index,i) >= c(index,i);% exercise\n stoppingtime(index(earlyexercise)) = i;\n v(index(earlyexercise)) = g(index(earlyexercise),i);\n end\n\n% Computing the martingale pi\n\nL = zeros(NSim,1); \nexpectation = zeros(NSim,Nr); \nexpectation(:,1) = lower * ones(NSim,1);\n\npi = zeros(NSim,Nr+1); % martingale\npi(:,1) = lower * ones(NSim,1); % set pi(0)\n\n% perform the subsimulation for each value of the path set\nfor i=1:1:Nr-1\n for j=1:NSim\n expectation(j,i+1) = subsimulation(S(j,i+1), df, B, NSSim, Nr-i,...\n beta(:,i:end), getpaths, payoff) * prod(df(1:i));\n end\nend\n\nfor i=1:1:Nr\n i_exercise = stoppingtime == i; % check if early exercised\n \n if i < Nr\n L(i_exercise) = g(i_exercise, i) * prod(df(1:i));\n L(~i_exercise) = expectation(~i_exercise,i+1); \n else\n L(i_exercise) = g(i_exercise, i) * prod(df(1:i));\n end\n \n \n pi(:,i+1) = pi(:,i) + L - expectation(:,i);\nend\n\n\nmaximum = zeros(NSim,1);\n\nfor j=1:1:NSim\n maximum(j) = L(j) + max(g(j,:) - pi(j,2:end)); % compute the max\nend\nupper = mean(maximum);\n\nend \n\nfunction y = subsimulation(S0, df, B, NSim, Nr, beta, gp,payoff)\n S2 = gp(S0,NSim,Nr); S2 = S2(:,2:end); % paths\n g2 = payoff(S2); % payoff\n iVec = 1:NSim;\n \n exercise = Nr * ones(NSim,1); % exercise per path\n % determine exercise strategy for path set S2\n for i=1:1:Nr-1 \n i_nexercised = exercise == Nr;\n I_nexercise = iVec(i_nexercised);\n \n s = S2(i_nexercised,i);\n Acell = B(s);\n A = cell2mat(Acell{:,:});\n c = A * beta(:,i);\n \n i_exercise = g2(i_nexercised,i) >= c & g2(i_nexercised,i) > 0;\n exercise(I_nexercise(i_exercise)) = i; \n end\n summe=0;\n for j=1:1:NSim\n summe = summe + g2(j,exercise(j)) * prod(df(1:exercise(j)));\n end\n y = summe / NSim; % MC value from subsimulation\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/37620-american-monte-carlo/AmericanMC/UpperBound1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.5449106679707858}} {"text": "function linpack_c_test11 ( )\n\n%*****************************************************************************80\n%\n%% TEST11 tests CHICO.\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 = 3;\n lda = n;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST11\\n' );\n fprintf ( 1, ' For a single precision complex (C)\\n' );\n fprintf ( 1, ' Hermitian matrix (HI):\\n' );\n fprintf ( 1, ' CHICO factors the matrix and estimates\\n' );\n fprintf ( 1, ' the reciprocal condition number.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The matrix order is N = %d\\n', n );\n%\n% Set the values of the matrix A.\n%\n seed = 123456789;\n\n for i = 1 : n\n [ a(i,i), seed ] = r4_uniform_01 ( seed );\n for j = i+1 : n\n [ a(i,j), seed ] = c4_uniform_01 ( seed );\n a(j,i) = conj ( a(i,j) );\n end\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, ' (%8f %8f)', real ( a(i,j) ), imag ( a(i,j) ) );\n end\n fprintf ( 1, '\\n' );\n end\n%\n% Factor the matrix A.\n%\n [ a, ipvt, rcond ] = chico ( a, lda, n );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Estimated reciprocal condition RCOND = %f\\n', rcond );\n\n return\nend\n", "meta": {"author": "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/linpack_c_test11.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149978955811, "lm_q2_score": 0.7217432062975978, "lm_q1q2_score": 0.544854771063301}} {"text": "function [res,resL2,qualMeasOut]=SART(proj,geo,angles,niter,varargin)\n% SART solves Cone Beam CT image reconstruction using Oriented Subsets\n% Simultaneous Algebraic Reconstruction Technique algorithm\n%\n% SART(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(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% 'Verbose' 1 or 0. Default is 1. Gives information about the\n% progress of the algorithm.\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\nblocksize=1;\n[lambda,res,lambdared,verbose,QualMeasOpts,OrderStrategy,nonneg,gpuids,redundancy_weights,gt]=parse_inputs(proj,geo,angles,varargin);\n\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\n[alphablocks,orig_index]=order_subsets(angles,blocksize,OrderStrategy);\nindex_angles=cell2mat(orig_index);\nangles_reorder=cell2mat(alphablocks);\n\n% does detector rotation exists?\nif ~isfield(geo,'rotDetector')\n geo.rotDetector=[0;0;0];\nend\n%% Create weighting matrices\n\n% Projection weight, W\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\nclear A x y dx dz;\n%% hyperparameter stuff\nnesterov=false;\nif ischar(lambda)&&strcmp(lambda,'nesterov')\n nesterov=true;\n lambda=(1+sqrt(1+4))/2;\n gamma=0;\n ynesterov=zeros(size(res),'single');\n ynesterov_prev=ynesterov;\nend\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 % reorder angles\n \n for jj=index_angles\n if size(offOrigin,2)==size(angles,2)\n geo.offOrigin=offOrigin(:,jj);\n end\n if size(offDetector,2)==size(angles,2)\n geo.offDetector=offDetector(:,jj);\n end\n if size(rotDetector,2)==size(angles,2)\n geo.rotDetector=rotDetector(:,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 % --------- Memory expensive-----------\n \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 %------------------------------------\n %--------- Memory cheap(er)-----------\n if nesterov\n % The nesterov update is quite similar to the normal update, it\n % just uses this update, plus part of the last one.\n ynesterov=res+ bsxfun(@times,1./V(:,:,jj),Atb(W(:,:,index_angles(:,jj)).*(proj(:,:,index_angles(:,jj))-Ax(res,geo,angles_reorder(:,jj),'gpuids',gpuids)),geo,angles_reorder(:,jj),'gpuids',gpuids));\n res=(1-gamma)*ynesterov+gamma*ynesterov_prev;\n else\n res=res+lambda* bsxfun(@times,1./V(:,:,jj),Atb(W(:,:,index_angles(:,jj)).*(proj(:,:,index_angles(:,jj))-Ax(res,geo,angles_reorder(:,jj),'gpuids',gpuids)),geo,angles_reorder(:,jj),'gpuids',gpuids));\n end\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 if nesterov\n gamma=(1-lambda);\n lambda=(1+sqrt(1+4*lambda^2))/2;\n gamma=gamma/lambda;\n else\n lambda=lambda*lambdared;\n end\n if computeL2 || nesterov\n geo.offOrigin=offOrigin;\n geo.offDetector=offDetector;\n geo.DSD=DSD;\n geo.rotDetector=rotDetector;\n resL2(ii)=im3Dnorm(proj-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');\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)\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,lambdared,verbose,QualMeasOpts,OrderStrategy,nonneg,gpuids,redundancy_weights,gt]=parse_inputs(proj,geo,alpha,argin)\nopts={'lambda','init','initimg','verbose','lambda_red','qualmeas','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:InvalidInput','Invalid number of inputs')\nend\n\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: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: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 elseif ischar(val)&&strcmpi(val,'nesterov')\n lambda='nesterov'; % just for lowercase/uppercase\n elseif length(val)>1 || ~isnumeric(val)\n error('TIGRE:SART:InvalidInput','Invalid lambda')\n else\n lambda=val;\n end\n case 'lambda_red'\n if default\n lambdared=1;\n else\n if length(val)>1 || ~isnumeric(val)\n error('TIGRE:SART:InvalidInput','Invalid lambda')\n end\n lambdared=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 res=init_multigrid(proj,geo,alpha);\n continue\n end\n if strcmp(val,'image')\n initwithimage=1; % it is used (10 lines below)\n continue\n end\n if isempty(res)\n error('TIGRE:SART: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: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('TIGRE:SART:InvalidInput','Invalid quality measurement parameters');\n end\n end\n case 'orderstrategy'\n if default\n OrderStrategy='random';\n else\n OrderStrategy=val;\n end\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:InvalidInput',['Invalid input name:', num2str(opt),'\\n No such option']);\n end\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.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.5448547676222674}} {"text": "function varargout = roots( F, varargin )\n%ROOTS Find the common zeros of a CHEBFUN2V object.\n% r = ROOTS(F) finds the common zeros of the two bivariate functions F(1) and\n% F(2) in their domain of definition under the assumption that the solution\n% set is zero-dimensional. R is a matrix with two columns storing the x- and\n% y-values of the solutions. This script is also called by the syntax\n% ROOTS(f,g), where f and g are CHEBFUN2 objects.\n%\n% [x, y] = ROOTS(F) returns the x- and y-values as two separate columns.\n%\n% Currently, if the maximum degree of F(1) and F(2) is greater than 200 then\n% an algorithm based on Marching squares is employed, and an algorithm based\n% on a resultant method is used otherwise (see [1]).\n%\n% ROOTS(F, 'ms') or ROOTS(F, 'marchingsquares') always employs the marching\n% squares algorithm.\n%\n% ROOTS(F, 'resultant') always employs the algorithm based on the hidden\n% variable resultant method.\n%\n% [1] Y. Nakatsukasa, V. Noferini, and A. Townsend, Computing the common zeros\n% of two bivariate functions via Bezout resultants, (2013).\n%\n% See also CHEBFUN2/ROOTS, CHEBFUN/ROOTS.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\n% Maximum degree for resultant method:\nmax_degree = 200; \n\n% Empty check:\nif ( isempty(F) )\n varargout = {[]};\n return\nend\n\nf = F.components{1}; \ng = F.components{2};\n[nf, mf] = length(f);\n[ng, mg] = length(g);\n% Maximum degree:\ndd = max([mf, nf, mg, ng]); \n\nvalidArgs = {'ms', 'marchingsquares', 'resultant'};\nif ( (nargin > 1) && ~any(strcmpi(varargin{1}, validArgs)) )\n error('CHEBFUN:CHEBFUN2V:roots:badInput', ...\n 'Unrecognised optional argument.');\nend\n\n\nif ( isempty(varargin) )\n % If rootfinding method has not been defined, then use resultant if\n % degrees are small: \n if ( dd <= max_degree ) \n [xroots, yroots] = roots_resultant(F);\n else\n [xroots, yroots] = roots_marchingSquares(F);\n xroots = xroots.'; \n yroots = yroots.';\n end\nelseif ( strcmpi(varargin{1}, 'resultant') )\n % If the user wants the resultant method, then use it: \n [xroots, yroots] = roots_resultant(F);\nelseif ( any( strcmpi(varargin{1}, {'ms', 'marchingsquares'} ) ) )\n % If the user wants the marching squares method, then use it: \n [xroots, yroots] = roots_marchingSquares(F);\n xroots = xroots.'; \n yroots = yroots.';\nelse\n % Print error. Unknown method. \n error('CHEBFUN2V:ROOTS:METHOD', 'Unknown rootfinding method.') \nend\n\nif ( nargout <= 1 )\n varargout{1} = [xroots ; yroots].';\nelse\n varargout = {xroots, yroots};\nend\n\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%% RESULTANT METHOD %%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [xroots,yroots] = roots_resultant(F)\n\n% extract out the two CHEBFUN2 objects.\nf = F.components{1}; g = F.components{2};\n\n% Useful parameters\nrect = f.domain; % rectangular domain of CHEBFUN2.\n[nf,mf]=length(f);[ng,mg]=length(g);\ndd = max([mf nf mg ng]); % max degree\nmax_degree = min( 16 , dd ); % subdivision threshold degree\nreg_tol = 1e-15; % Regularization (for Bezoutian)\ndomain_overlook = 1e-10; % start by looking for zeros on larger domain.\ndonewton = 0; % Newton polishing?\nmultitol = sqrt(eps); % for multiple roots we do not go for more than sqrt(eps);\n\n% Consider a slightly large domain to make sure we get all the roots along\n% edges.\n% domain width (attempt to make scale invariant)\nxwid = diff(rect(1:2))/2; ywid = diff(rect(3:4))/2;\nxmax = rect(2) + xwid*domain_overlook;\nxmin = rect(1) - xwid*domain_overlook;\nymax = rect(4) + ywid*domain_overlook;\nymin = rect(3) - ywid*domain_overlook;\n\nsubdividestop = 2*(1/2)^((log(16)-log(dd))/log(.79)); % subdivision threshold\nsubdividestop = min(subdividestop,1/4);\n\n% initial scaling to O(1)\nf = f/abs(f.pivotValues(1));\ng = g/abs(g.pivotValues(1));\n\n[xroots,yroots] = subrootsreptwo(f,g,xmin,xmax,ymin,ymax,xwid,ywid,reg_tol,max_degree,subdividestop);\n% ballpark obtained, next do local bezoutian refinement\n\n\n[fx, fy] = gradient(chebfun2(f,rect)); \n[gx, gy] = gradient(chebfun2(g,rect));\n\n%%%%% subdivision for accuracy when dynamical range is an issue %%%%%%%%\n% find region in which roots might have been missed\nF = chebcoeffs2(f); \nG = chebcoeffs2(g);\nF = rot90(F, -2);\nG = rot90(G, -2);\n\nxpts = linspace(xmin,xmax,2*max(size(F,2),size(G,2)));\nypts = linspace(ymin,ymax,2*max(size(F,1),size(G,1)));\n\n[xx,yy] = meshgrid(xpts,ypts);\nFX = fx(xx,yy);FY = fy(xx,yy); GY = gy(xx,yy);GX = gx(xx,yy);\nFG = abs(FX.*GY-FY.*GX); % Bezout conditioning\nFpG = abs(f(xx,yy))+abs(g(xx,yy)); % function values\n\nFGG = (log10(FpG+eps)<-6 & log10(FG/max(max(FG))+eps)<-12); % dangerous region (Bezout might have missed)\nif sum(sum(FGG))>0, % Bezout could have missed these, do local search\n xx = zeros(1,size(FGG,1)*size(FGG,2)); yy = xx;\n ip = 1;\n for i=1:size(FGG,1)\n for j=1:size(FGG,2)\n if FGG(i,j)==1,\n s = svd([FX(i,j) FY(i,j);GX(i,j) GY(i,j)]);\n Jacobs = 1./s(end); % conditioning of original problem\n if ( Jacobs < 1e15 ), % give up if solution is too ill conditioned\n xx(ip) = xpts(j); yy(ip) = ypts(i);\n ip = ip+1;\n end\n end\n end\n end\n \n xdis = (xpts(2)-xpts(1)); ydis = (ypts(2)-ypts(1));\n xx = xx(1:ip-1); yy = yy(1:ip-1);\n m = blockingxy(xx,yy,max(xdis,ydis)*1.1);\n for i = 1:max(m)\n xnow = xx(m==i); ynow = yy(m==i);\n [xt,yt] = subrootsreptwo(f,g,min(xnow)-xdis,max(xnow)+xdis,min(ynow)-ydis,max(ynow)+ydis,xwid,ywid,reg_tol,max_degree); % local (second) bez\n xroots = [xroots xt]; yroots = [yroots yt];\n end\nend\n\n\n% xroots,yroots should contain solutions (condnum<1e14) and maybe more.\ntolblock = xwid*min(3e-3,1/(10*dd)); % clustering threshold\nm = blockingxy(xroots,yroots,tolblock);\nz = xroots+1i*yroots;\nxroots = [];yroots = [];\n\ntolbdefault = min(5*xwid*sqrt(multitol),tolblock); % local bezout width\nfor i = 1:max(m)\n znow = z(m==i); xnow = real(znow); ynow = imag(znow);\n J = [fx(mean(xnow),mean(ynow)) fy(mean(xnow),mean(ynow));gx(mean(xnow),mean(ynow)) gy(mean(xnow),mean(ynow))];\n s = svd(J);\n Jacobs = 1./s(end); % original conditioning\n Jacobsbez = 1/abs(det(J)); % Bezout conditioning\n tolb = max(tolbdefault,eps*100*Jacobsbez);\n tolb = min(tolb,xwid*1e-2); % give up if Jacobs too large\n [xrootsnow,yrootsnow] = subrootsreptwo(f,g,min(xnow)-tolb,max(xnow)+tolb,min(ynow)-tolb,max(ynow)+tolb,xwid,ywid,0,max_degree); % local (second) bez no subdivision\n \n xxx = []; yyy = [];\n if length(xrootsnow)>=1,\n \n if Jacobs<1e10, %only for well-conditioned roots\n tolbb = max(xwid*multitol,Jacobs*1000*eps);\n for j = 1:length(xrootsnow)\n [xx,yy] = subrootsreptwo(f,g,min(xrootsnow(j))-tolbb,max(xrootsnow(j))+tolbb,min(yrootsnow(j))-tolbb,max(yrootsnow(j))+tolbb,xwid,ywid,0,max_degree/2); % local (second) bez\n xxx = [xxx xx]; yyy = [yyy yy];\n end\n \n else\n xxx = xrootsnow;\n yyy = yrootsnow;\n end\n \n end\n xroots = [xroots xxx]; yroots = [yroots yyy];\nend\n\n% finally collapse close roots\nxrootsnow = []; yrootsnow = [];\nmm = blockingxy(xroots,yroots,min(xwid*sqrt(eps)*10));\nfor ii = 1:max(mm)\n xtmp = xroots(mm==ii); ytmp = yroots(mm==ii);\n res = zeros(1,length(xtmp));\n for ij = 1:length(xtmp)\n res(ij) = norm([feval(f,xtmp(ij),ytmp(ij)) feval(g,xtmp(ij),ytmp(ij))]);\n end\n [mres,IX] = min(res);\n if min(mres)<1e-10,\n xrootsnow = [xrootsnow xtmp(IX)]; yrootsnow = [yrootsnow ytmp(IX)];\n end\nend\nxroots = xrootsnow; yroots = yrootsnow;\n\nif donewton % optional Newton update (don't do by default)\n [xroots,yroots] = newtonupdate(f,g,xroots,yroots);\nend\n\n\n% discard roots safely outside initial domain\nxmax = xmax - xwid*domain_overlook; xmin = xmin + xwid*domain_overlook; % original domain\nymax = ymax - ywid*domain_overlook; ymin = ymin + ywid*domain_overlook;\n\nii = find(xrootsxmin-xwid*1e-15 & yrootsymin-ywid*1e-15);\nxroots = xroots(ii); yroots = yroots(ii);\nfor i=1:length(xroots)\n if xroots(i)>xmax, xroots(i) = xmax; end % push outliers to boundary\n if xroots(i)ymax, yroots(i) = ymax; end\n if yroots(i)xwid*subdividestop || (ymax-ymin)>ywid*subdividestop % subdivide only if domain is not too small\n if (size(fcoef,1)>maxd && size(fcoef,2)>maxd) ||...\n (size(gcoef,1)>maxd && size(gcoef,2)>maxd)\n % subdivide in both x,y\n xmed = (xmax+xmin)/2 - magicnum * (xmax-xmin)/2;\n ymed = (ymin+ymax)/2 - honournum * (ymax-ymin)/2;\n [xroots1,yroots1] = subrootsreptwo(f,g,xmin,xmed,ymin,ymed,xwid,ywid,tolreg,maxd,subdividestop);\n [xroots12,yroots12] = subrootsreptwo(f,g,xmed,xmax,ymin,ymed,xwid,ywid,tolreg,maxd,subdividestop);\n [xroots2,yroots2] = subrootsreptwo(f,g,xmin,xmed,ymed,ymax,xwid,ywid,tolreg,maxd,subdividestop);\n [xroots22,yroots22] = subrootsreptwo(f,g,xmed,xmax,ymed,ymax,xwid,ywid,tolreg,maxd,subdividestop);\n xroots = [xroots xroots1 xroots2 xroots12 xroots22];\n yroots = [yroots yroots1 yroots2 yroots12 yroots22];\n return\n elseif (size(fcoef,1)>maxd)||(size(gcoef,1)>maxd) % subdivide in y\n ymed = (ymin+ymax)/2 - magicnum * (ymax-ymin)/2;\n [xroots1,yroots1] = subrootsreptwo(f,g,xmin,xmax,ymin,ymed,xwid,ywid,tolreg,maxd,subdividestop);\n [xroots12,yroots12] = subrootsreptwo(f,g,xmin,xmax,ymed,ymax,xwid,ywid,tolreg,maxd,subdividestop);\n xroots = [xroots xroots1 xroots12];\n yroots = [yroots yroots1 yroots12];\n return\n elseif (size(fcoef,2)>maxd)||(size(gcoef,2)>maxd) % subdivide in x\n xmed = (xmax+xmin)/2 - honournum * (xmax-xmin)/2;\n [xroots1,yroots1] = subrootsreptwo(f,g,xmin,xmed,ymin,ymax,xwid,ywid,tolreg,maxd,subdividestop);\n [xroots12,yroots12] = subrootsreptwo(f,g,xmed,xmax,ymin,ymax,xwid,ywid,tolreg,maxd,subdividestop);\n xroots = [xroots xroots1 xroots12];\n yroots = [yroots yroots1 yroots12];\n return\n end\nelse\n ff = cheb2(f,[xmin xmax ymin ymax],approx_tol,round(1.5*maxd)); % didn't resolve, sample at more than maxd points but not too much\n gg = cheb2(g,[xmin xmax ymin ymax],approx_tol,round(1.5*maxd));\nend\n\nF = ff.coeffs; G = gg.coeffs;\nif isempty(F); F = 0; end\nif isempty(G); G = 0; end\nif (2-eps*10)*abs(F(end,end))>sum(sum(abs(F))) || (2-eps*10)*abs(G(end,end))>sum(sum(abs(G)))\n % 'no roots here!'\nelse\n if min(min(size(F)),min(size(G)))<=1,\n if length(F)<=1 && length(G)<=1, % constant\n if (abs(F)<=1e-15) && (abs(G)<=1e-15), % flat 0; just say middle point is 0\n xroots = (xmax+xmin)/2; yroots = (ymax+ymin)/2;\n else\n xroots = [];yroots=[];\n end\n else\n % 'no roots here!'\n [xroots,yroots] = onevar(F,G,xmin,xmax,ymin,ymax);\n end\n else\n \n [xroots,yroots] = runbezval(F,G,xmin,xmax,ymin,ymax,tolreg);\n end\nend\nend\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [xroots,yroots] = runbezval(F,G,xmin,xmax,ymin,ymax,tol)\n% run bezout (core code):\n% form Bezout matrix polynomial and solve eigenproblem, then find other variable\n% form Bezoutian at magic number and find null space and diagonal balancing\n% regularization tolerance\n\nmc = size(F,1)-1+size(G,1)-1+1; % # of sampling points (degree of B(y))\nmc = max(mc,2);\n\nmagicnum = 0.004849834917525; % 'magic number'\n\ndoswap = 0;\n\n% swap x and y if appropriate\nif max(size(F,1),size(G,1))*(size(F,2)+size(G,2)) > max(size(F,2),size(G,2))*(size(F,1)+size(G,1))\n F = F'; G = G'; doswap = 1;\n mc = size(F,1)-1+size(G,1)-1+1;\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%% form B and regularize %%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nB0 = formBez(F,G,magicnum); % sample Bezoutian at 'magic number'\n\n% now form Bezoutians at Chebyshev points\nx = chebpts(mc);\nB = zeros(size(B0,1),size(B0,1),mc);\nBsum = zeros(size(B0));\nfor i = 1:mc\n B(:,:,i) = formBez(F,G,x(i));\n Bsum = Bsum+abs(B(:,:,i));\n % B(:,:,i) = Btmp(k+1:end,k+1:end); % extract regular part\nend\n\nif tol == 0, % no regularization\n k = 0;\nelse\n %%%%%%%%%% REGULARIZATION parameter %%%%%%%%%%%%%%% extract lower-right part of Bezoutian %%%\n d = diag(B0);\n for i = 1:size(B0,1), d(i) = max(max(abs(Bsum(1:i,1:i)))); end\n m = find(abs(d)/max(abs(d))> tol);\n if isempty(m) \n k = 0;\n else\n offd = zeros(1,m(1)-1);\n for i = 1:m(1)-1\n offd(i) = max(max(abs(Bsum(i+1:end,1:i))));\n end\n mm = find(offd/max(abs(d)) 10*eps, break; end\n end\n B = B(:,:,ii:end);\n ns = size(B);\n \n %Bori = B;\n % diagonal balancing (optional)\n [Dori] = balancecong(B0(k+1:end,k+1:end));\n for i = 1:size(B,3)\n B(:,:,i) = Dori * B(:,:,i) * Dori;\n B(:,:,i) = rot90(B(:,:,i),2); % fliplr,ud\n end\n \n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n %%%%%%%%%%%%%%%% done forming B, now solve polyeig %%%%%%%%%%%\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n \n % colleague QZ (most stable but slow)\n nrm = norm(BB,'fro')/ns(1); % scale as suggested as Van Dooren\n ei = chebT1rtsmatgep(B/nrm);\n %[ei,AG,BG] = chebT1rtsmatgep(B/nrm); ei = stairqz(AG,BG); % semi-staircase\n \nend\nyreal = sort(real(ei(abs(real(ei))<=1+10*eps & abs(imag(ei))ep;\ny = y(ii);\n\n\nxreal = magicnum*ones(size(y));\nxtmp = [];ytmp = [];\nfor j = 1:length(y)\n if xreal(j)==magicnum\n \n % compute coefficients via vandermonde vector\n vy = vandercheb(y(j),size(G,1)); coef1 = vy'*G;\n vy = vandercheb(y(j),size(F,1)); coef2 = vy'*F;\n \n % find roots of two univariate polys via colleague\n if length(coef1)<=1 || norm(coef1)==0, rts1=[];\n else\n rts1 = chebT1rts(coef1(find(abs(coef1)>0,1,'first'):end)');\n rts1 = real(sort(rts1(abs(imag(rts1))<=10*1e-8 & abs(rts1)<=1+10*eps)));\n end\n if length(coef2)<=1 || norm(coef2)==0, rts2=[];\n else\n rts2 = chebT1rts(coef2(find(abs(coef2)>0,1,'first'):end)');\n rts2 = real(sort(rts2(abs(imag(rts2))<=10*1e-8 & abs(rts2)<=1+10*eps)));\n end\n % collapse nearby roots if any (deal with multiple roots)\n dist = abs(rts1(1:end)-[rts1(2:end);2]);\n ii = dist>10*ep; rts1 = rts1(ii);\n dist = abs(rts2(1:end)-[rts2(2:end);2]);\n ii = dist>10*ep; rts2 = rts2(ii);\n rts = sort([rts1;rts2]); res = ones(size(rts));\n \n % compute function values\n for i = 1:length(rts)\n res(i) = max([abs(coef1*vandercheb(rts(i),size(G,2))),abs(coef2*vandercheb(rts(i),size(F,2)))]);\n end\n \n % adopt depending on the interval size\n if xmax-xmin > 2e-3,\n %rtscan = rts(find(res<1000*sqrt(eps))); % candidates for x-values\n rtscan = rts((res<100*sqrt(eps))); % candidates for x-values\n elseif xmax-xmin > 1e-7, % local bez\n rtscan = rts((res<1e-10));\n else % very local (final) bez\n rtscan = rts((res<1e-12));\n end\n \n % collect/collapse candidate roots\n if ~isempty(rtscan)\n skipnext = 0;\n for i = 1:length(rtscan)-1\n if skipnext\n skipnext = 0;\n else\n if ( abs(rtscan(i)-rtscan(i+1))<10*ep ),\n skipnext = 1;\n vali = max([abs(coef1*vandercheb(rtscan(i),size(G,2))), abs(coef2*vandercheb(rtscan(i),size(F,2)))]);\n valip= max([abs(coef1*vandercheb(rtscan(i+1),size(G,2))),abs(coef2*vandercheb(rtscan(i+1),size(F,2)))]);\n if ( vali < valip )\n xtmp = [xtmp;rtscan(i)];\n else\n xtmp = [xtmp;rtscan(i+1)];\n end\n else\n xtmp = [xtmp;rtscan(i)];\n end\n ytmp = [ytmp;y(j)];\n end\n end\n % last i\n if skipnext % do nothing\n else\n xtmp = [xtmp;rtscan(end)]; ytmp = [ytmp;y(j)];\n end\n end\n end\nend\n\nif doswap ==0 % recover if swapped initially\n xval = (xmin+xmax)/2+(xmax-xmin)/2*xtmp';\n yval = (ymin+ymax)/2+(ymax-ymin)/2*ytmp';\nelse\n xval = (xmin+xmax)/2+(xmax-xmin)/2*ytmp';\n yval = (ymin+ymax)/2+(ymax-ymin)/2*xtmp';\nend\n\nreturn\nend\n\n%%%%%%%%%%%%%%%%%%%%%% KEEP IN CASE I NEED AT SOME STAGE %%%%%%%%%%%%%%%%% \n% function [xroots,yroots,sproots] = localrefine(f,g,xmin,xmax,ymin,ymax,xwid,ywid,tolreg,maxd)\n% % execute subdivision and if degrees small enough, run bezout\n%\n% approx_tol = 1e-13; % cheb2 cutoff tolerance\n% ff = cheb2(f,[xmin xmax ymin ymax],approx_tol,maxd+2); % sample at a bit more than maxd points\n% gg = cheb2(g,[xmin xmax ymin ymax],approx_tol,maxd+2);\n% F = ff.coeffs; G = gg.coeffs;\n%\n% if isempty(F),\n% v = vandercheb(0,size(G,2));\n% G = G*v;\n% rx = chebT1rts(G(find(abs(G)>0,1,'first'):end)')';\n% rx = real(sort(rx(abs(imag(rx))<=1e-8 & abs(rx)<=1+10*eps)));\n% yroots = (ymin+ymax)/2+(ymax-ymin)/2*rx;\n% xroots = (xmin+xmax)/2*ones(size(yroots));\n% return,\n% end\n% if isempty(G),\n% v = vandercheb(0,size(F,2));\n% F = F*v;\n% rx = chebT1rts(F(find(abs(F)>0,1,'first'):end)')';\n% rx = real(sort(rx(abs(imag(rx))<=1e-8 & abs(rx)<=1+10*eps)));\n% yroots = (ymin+ymax)/2+(ymax-ymin)/2*rx;\n% xroots = (xmin+xmax)/2*ones(size(yroots));\n% return,\n% end\n%\n%\n% if min(min(size(F)),min(size(G)))<=1,\n% if length(F)<=1 && length(G)<=1, % constant\n% if (abs(F)<=1e-15) && (abs(G)<=1e-15), % flat 0; just say middle point is 0\n% xroots = (xmax+xmin)/2; yroots = (ymax+ymin)/2;\n% else\n% xroots = [];yroots=[];\n% end\n% else\n% % 'no roots here!'\n% %[xmin xmax ymin ymax],keyboard\n% [xroots,yroots] = onevar(F,G,xmin,xmax,ymin,ymax);\n% end\n% else\n% [xroots,yroots] = runbezval(F,G,xmin,xmax,ymin,ymax,tolreg); % bez not syl\n% end\n% end\n\n\nfunction [xroots,yroots] = onevar(F,G,xmin,xmax,ymin,ymax)\n% when either F or G is constant\ndoswap = 0;\n\nif min(min(size(F)))==1,\n if size(F,2) ==1, FF = F'; GG = G'; doswap = 1;\n else FF = F; GG = G;\n end\nelse\n if size(G,2) ==1, FF = G'; GG = F'; doswap = 1;\n else FF = G; GG = F;\n end\nend\n\nif length(FF)==1\n if abs(FF)<1e-15,\n if min(size(GG))==1,\n rx = chebT1rts(GG(find(abs(GG)>0,1,'first'):end)')';\n rx = real(sort(rx(abs(imag(rx))<=1e-8 & abs(rx)<=1+10*eps)));\n rr = rx;\n else % GG is matrix. just take x=0 and find y.\n %gcheb = chebfun2(g,[xmin xmax ymin ymax]); roots(gcheb);\n v = vandercheb(0,size(GG,2));\n GG = GG*v;\n rx = chebT1rts(GG(find(abs(GG)>0,1,'first'):end)')';\n rx = real(sort(rx(abs(imag(rx))<=1e-8 & abs(rx)<=1+10*eps)));\n rr = rx;\n end\n if size(GG,1)>size(GG,2)\n yroots =rr; xroots = zeros(size(rr));\n else\n xroots =rr; yroots = zeros(size(rr));\n end\n else\n xroots = []; yroots = [];\n end\nelse\n rx = chebT1rts(FF(find(abs(FF)>0,1,'first'):end)');\n rx = real(sort(rx(abs(imag(rx))<=1e-8 & abs(rx)<=1+10*eps)));\n xroots = []; yroots = [];\n for j=1:length(rx)\n vy = vandercheb(rx(j),size(GG,2)); coef = GG*vy;\n % ry = roots(chebfun(coef,'coeffs'))';\n if length(coef)<=1,\n if norm(coef)<1e-15,\n ry = 0;\n else ry=[];\n end\n else\n rts2 = chebT1rts(coef(find(abs(coef)>0,1,'first'):end));\n rts2 = real(sort(rts2(abs(imag(rts2))<=1e-8 & abs(rts2)<=1+10*eps)));\n ry = rts2';\n end\n yroots = [yroots ry];\n xroots = [xroots rx(j)*ones(size(ry))];\n end\nend\nif doswap\n xt = xroots; xroots = yroots; yroots = xt;\nend\nxroots = (xmin+xmax)/2+(xmax-xmin)/2*xroots;\nyroots = (ymin+ymax)/2+(ymax-ymin)/2*yroots;\nend\n\n\nfunction [r,A,B] = chebT1rtsmatgep(c)\n% CHEBT1RTSMATGEP(c), finds via QZ the roots of a MATRIX polynomial\n% expressed in a ChebT basis\n% by using the colleague matrix *pencil* of the first kind. F can be a vector of\n% coefficients or a chebfun. Coefficients are ordered highest degree down.\n%\n% c is a nxnxk array. k-1 is the degree, n is the matrix size.\n\nk=length(c(1,1,:)); n=length(c(:,:,1));\n\nif size(c,3) ==2, % linear case\n r = eig(c(:,:,2),-c(:,:,1));\n return\nend\n\nfor ii=2:k\n c(:,:,ii)=c(:,:,ii)*(-.5); % coefficients\nend\nc(:,:,3) = c(:,:,3)+.5*c(:,:,1);\n\noh = .5*ones(n*(k-2),1);\n% form colleague matrix A,B:\nA = diag(oh,n)+diag(oh,-n);\nA(end-n+1:end,end-2*n+1:end-n) = eye(n);\n\nfor ii=1:k-1\n A(1:n,(ii-1)*n+1:ii*n) = c(:,:,ii+1);\nend\nB=eye(size(A)); B(1:n,1:n)=c(:,:,1);\n\nr = eig(A,B);% Compute roots\n\nend\n\nfunction r = chebT1rts(c)\n% CHEBT1RTS(F), finds the roots of a polynomial expressed in a Cheb T basis\n% by using the colleague matrix of the first kind. F can be a vector of\n% coefficients or a chebfun.\n\nif length(c)<=1 \n r=[]; \n return\nend\nif size(c,1) < size(c,2) % c is column vector\n c = c';\nend \n\nif length(c)==2, % linear case\n r = -c(2)/c(1); return\nend\n\nif c(1)==0\n c(1)=eps*max(c); % perturb a zero leading coefficient by eps. \nend\nc = -.5*c(end:-1:2)/c(1); \nc(end-1) = c(end-1)+.5;\noh = .5*ones(length(c)-1,1);\n% Modified colleague matrix:\nA = diag(oh,1)+diag(oh,-1);\nA(end,end-1) = 1; A(1,:) = flipud(c);\nr = eig(A);% Compute roots as eig(A)\n\nend\n\nfunction B = formBez(F,G,y)\n% forms Bezoutian using DLP for F,G (matrices) at a specific value of y.\n\nyv = vandercheb(y,max(size(F,1),size(G,1))); % Chebyshev-vandermonde form vector\n\nff = yv(end-size(F,1)+1:end)'*F;\ngg = yv(end-size(G,1)+1:end)'*G;\n\nif length(ff) 0 )\n error('CHEBFUN:CHEBFUN2V:roots:matrixChebfft:badDegree', ...\n 'Degree must be integer');\nend\n\nD = A;\nfor jj = 1:n % for each column of A\n B = A(:,jj:n:n*k);\n C = chebtech2.vals2coeffs(B.'); % convert first column of each coefficient to values.\n D(:,jj:n:n*k) = rot90(C, -1); % assign to output.\nend\n\nend\n\nfunction m = blockingxy(x,y,delta)\n% BLOCKINGXY Produce blocking pattern for data x,y within tolerance delta.\n% Elements will be assigned numbers for each class.\n\nif isempty(x), m=[]; return, end\n[xx,IX] = sort(x); m = ones(size(x));\n\nxxp = ones(size(x)); ppos = ones(size(x));\np = 1;\nfor i=1:length(x)-1\n if abs(xx(i)-xx(i+1))>delta,\n p = p+1; ppos(p) = i+1;\n end\nend\nppos = ppos(1:p); % done with x\nq = 0;\nfor i=1:p\n q = q+1;\n if idelta,\n q = q+1;\n m(IX(ppos(i)+IY(j+1:end)-1)) = q*ones(size(IX(ppos(i)+IY(j+1:end)-1)));\n end\n end\nend\nend\n\nfunction v = vandercheb(x,n)\n% v = vandercheb(x,n) forms unit vector in vandermonde form\nv = zeros(n,1);\nfor i = 1:n \n v(end-i+1) = real(cos((i-1)*acos(x)));\nend\nend\n\nfunction D = balancecong(B)\n% diagonal congruence balancing to make the diagonals of DBD equal.\nD = eye(length(B));\nfor i = length(B)-1:-1:1;\n if norm(B(i,:))>0,\n D(i,i) = max(1,sqrt(norm(B(end,:))/norm(B(i,:))));\n else\n D(i,i) = D(i+1,i+1);\n end\nend\nend\n\nfunction [xroots,yroots] = newtonupdate(f,g,xroots,yroots,itnum)\n%%%%%%%%%%%% newton update %%%%%%%%%%%%%%%%\n% Use one iteration of Newton to get 14-15 digits.\nif nargin < 5\n itnum = 1;\nend\nf = chebfun2(f); g = chebfun2(g) ;\n\ntol = 1e-15;\nfx = diff(f,1,2); fy=diff(f); gx = diff(g,1,2); gy=diff(g); % derivatives.\nJ = @(x,y) [feval(fx,x,y) feval(fy,x,y);feval(gx,x,y) feval(gy,x,y)]; % Jacobian\nfor jj=1:itnum\n r = [xroots' yroots'];\n for kk = 1:size(r,1)\n x0 = [r(kk,1),r(kk,2)].';dx=1; iter = 1;\n while ( norm(dx) > 10*tol && iter < 2 )\n dx = J(x0(1),x0(2)) \\ -[feval(f,x0(1),x0(2));feval(g,x0(1),x0(2))]; % update\n x0 = dx + x0; iter = iter + 1;\n end\n r(kk,:) = x0;\n end\n xroots = r(:,1)'; yroots = r(:,2)';\nend\n\nend\n\nfunction g = cheb2(f,varargin)\n% Basic bivariate tensor product, nonadaptive constructor.\n\ndefault_tol = 10*eps;\ndefault_n = 300;\n\n% Did we get any user defined domain?\nif nargin == 2\n % Assume this is a user defined domain [a b c d]\n if numel(varargin{1}) > 1\n ends = varargin{1};\n tol = default_tol;\n elseif numel(varargin{1}) == 1\n tol = varargin{1};\n end\nelseif nargin == 3\n ends = varargin{1};\n tol = varargin{2};\nelseif nargin == 4\n ends = varargin{1};\n tol = varargin{2};\n n = varargin{3};\nelse\n % default to the unit interval [-1 1 -1 1]\n ends = [-1 1 -1 1];\n tol = default_tol;\n n = default_n;\nend\n\nif isstruct(f)\n g = f;\n return;\nend\n\n% evaluate the function on a grid.\nif exist('n','var')==0,\n n = 300;\nend\n\nx = mypoints(n,ends(1:2)); y = mypoints(n,ends(3:4));\n[xx, yy]=meshgrid(x,y); F = f(xx,yy);\n\n% vertical scale for machine precision\nvscl = max(1,max(abs(F(:)))); % don't go for more than absolute accuracy.\n\n% Compute bivariate Chebyshev T coefficients.\nC = chebfun2.vals2coeffs(F);\nC = rot90(C, -2);\n\n% Very simple truncation of the coefficients.\n%m = find(max(abs(C))>100*eps*vscl,1,'first'); n = find(max(abs(C.'))>100*eps*vscl,1,'first');\nm = find(max(abs(C))>tol*vscl,1,'first'); n = find(max(abs(C.'))>tol*vscl,1,'first');\nC = C(n:end,m:end);\n\n% Form cheb2 object.\ng = struct('coeffs',C,'scl',vscl,'corners',ends);\n\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%% Marching Squares %%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [xroots, yroots] = roots_marchingSquares( f )\n\nfx = f.components{1}; \nfy = f.components{2};\npref = chebfunpref;\ntol = pref.cheb2Prefs.chebfun2eps;\nnum = 0; \nr = zeros(1,2); \ndom = fy.domain;\n\nnf = f.nComponents; \nif ( nf > 2 )\n error('CHEBFUN:CHEBFUN2V:roots:zeroSurface', ...\n 'CHEBFUN2 is unable to find zero surfaces.');\nend\n\nif ( length(fx) == 1 || length(fy) == 1 ) % one of them is of the form u(x)v(y)\n \n if ( length(fx) == 1 )\n % Find roots of fx. \n rowz = roots(fx.rows); \n colz = roots(fy.cols); \n for jj = 1:length(rowz)\n rr = roots(fy(rowz(jj),:));\n for kk = 1:length(rr)\n r(num+1,:) = [rowz(jj) rr(kk)]; num=num+1;\n end\n end\n for jj = 1:length(colz)\n rr = roots(fy(:,colz(jj)));\n for kk = 1:length(rr)\n r(num+1,:) = [rr(kk) colz(jj)]; num=num+1;\n end\n end\n elseif ( length(fy) == 1 )\n % roots lie along these lines\n rowz = roots(fy.rows); \n colz = roots(fy.cols); \n for jj = 1:length(rowz)\n ff = fx(rowz(jj),:);\n rr = roots(ff);\n for kk = 1:length(rr)\n r(num+1,:) = [rowz(jj) rr(kk)]; num=num+1;\n end\n end\n for jj = 1:length(colz)\n rr = roots(fx(:,colz(jj)));\n for kk = 1:length(rr)\n r(num+1,:) = [rr(kk) colz(jj)]; num=num+1;\n end\n end\n end\n \nelse\n % Use contourc to get roots to 3-4 digits.\n N = 400; \n NewtonFail = 0;\n rfx = roots(fx); \n rfy = roots(fy);\n x = linspace(-1, 1, N); % this is on [-1,1] because all zero contours are represented by chebfuns on the default interval.\n r = zeros(0,2); \n num = 0;\n \n Rx = rfx(x(:), :); \n Ry = rfy(x(:), :);\n if ( any(size(Rx)==[1 1]) )\n Rx = Rx( : ); \n end\n if ( any(size(Ry)==[1 1]) )\n Ry = Ry( : ); \n end\n \n for jj = 1:size(rfx, 2)\n rx = Rx(:, jj); \n rlx = real( rx ); \n imx = imag( rx );\n for kk = 1:size(rfy,2)\n ry = Ry(:,kk);\n [x0, y0]=intersections(rlx, imx, real(ry), imag(ry));\n if ( ~isempty(x0) )\n r(num+1:num+length(x0),1)=x0;\n r(num+1:num+length(x0),2)=y0;\n num=num+length(x0);\n end\n end\n end\n % Use a few iterations of Newton to get 14-15 digits.\n f = fx; \n g = fy;\n fx = diff(f,1,2); \n fy = diff(f); \n gx = diff(g,1,2); \n gy = diff(g); % derivatives.\n J = @(x,y) [feval(fx,x,y) feval(fy,x,y);...\n feval(gx,x,y) feval(gy,x,y)]; % Jacobian\n \n warnstate = warning('off','CHEBFUN:CHEBFUN2:NEWTON'); % turn warnings off, and capture Newton failure instead.\n for kk = 1:size(r,1)\n x0 = [r(kk,1), r(kk,2)].';\n dx = 1; \n iter = 1;\n while ( norm(dx) > 10*tol && iter < 15 )\n dx = J(x0(1),x0(2)) \\ -[feval(f,x0(1),x0(2));feval(g,x0(1),x0(2))]; % update\n x0 = dx + x0; iter = iter + 1;\n end\n if ( norm(dx) < 10*sqrt(tol) ) % we may have diverged so don't always update.\n r(kk,:) = x0;\n else\n NewtonFail = 1;\n end\n end\n warning(warnstate); % turn them back on.\n \n \n % If all the Newton iterations failed then some roots may be\n % inaccurate.\n if ( NewtonFail )\n warning('CHEBFUN:CHEBFUN2V:roots:newtonFail', ...\n 'Iterates may have diverged some of the computed roots may be not be accurate.')\n end\nend\n\n%%\n% Remove the roots which lie outside of the domain.\nif ( ~isempty(r) )\n r = r( (r(:,1) <= dom(2)+tol &...\n r(:,1) >= dom(1)-tol & ...\n r(:,2) <= dom(4)+tol & ...\n r(:,2) >= dom(3)-tol ), :);\nend\n\nif num==0\n xroots=[]; yroots=[];\n return\nend\n\nxroots = r(:,1); yroots = r(:,2);\n\n\nend\n\n\nfunction [x0,y0,iout,jout] = intersections(x1,y1,x2,y2,robust)\n%INTERSECTIONS Intersections of curves.\n% Computes the (x,y) locations where two curves intersect. The curves\n% can be broken with NaNs or have vertical segments.\n%\n% Example:\n% [X0,Y0] = intersections(X1,Y1,X2,Y2,ROBUST);\n%\n% where X1 and Y1 are equal-length vectors of at least two points and\n% represent curve 1. Similarly, X2 and Y2 represent curve 2.\n% X0 and Y0 are column vectors containing the points at which the two\n% curves intersect.\n%\n% ROBUST (optional) set to 1 or true means to use a slight variation of the\n% algorithm that might return duplicates of some intersection points, and\n% then remove those duplicates. The default is true, but since the\n% algorithm is slightly slower you can set it to false if you know that\n% your curves don't intersect at any segment boundaries. Also, the robust\n% version properly handles parallel and overlapping segments.\n%\n% The algorithm can return two additional vectors that indicate which\n% segment pairs contain intersections and where they are:\n%\n% [X0,Y0,I,J] = intersections(X1,Y1,X2,Y2,ROBUST);\n%\n% For each element of the vector I, I(k) = (segment number of (X1,Y1)) +\n% (how far along this segment the intersection is). For example, if I(k) =\n% 45.25 then the intersection lies a quarter of the way between the line\n% segment connecting (X1(45),Y1(45)) and (X1(46),Y1(46)). Similarly for\n% the vector J and the segments in (X2,Y2).\n%\n% You can also get intersections of a curve with itself. Simply pass in\n% only one curve, i.e.,\n%\n% [X0,Y0] = intersections(X1,Y1,ROBUST);\n%\n% where, as before, ROBUST is optional.\n\n% Version: 1.12, 27 January 2010\n% Author: Douglas M. Schwarz\n% Email: dmschwarz=ieee*org, dmschwarz=urgrad*rochester*edu\n% Real_email = regexprep(Email,{'=','*'},{'@','.'})\n\n% License:\n%\n% Copyright (c) 2008, Douglas M. Schwarz\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% Theory of operation:\n%\n% Given two line segments, L1 and L2,\n%\n% L1 endpoints: (x1(1),y1(1)) and (x1(2),y1(2))\n% L2 endpoints: (x2(1),y2(1)) and (x2(2),y2(2))\n%\n% we can write four equations with four unknowns and then solve them. The\n% four unknowns are t1, t2, x0 and y0, where (x0,y0) is the intersection of\n% L1 and L2, t1 is the distance from the starting point of L1 to the\n% intersection relative to the length of L1 and t2 is the distance from the\n% starting point of L2 to the intersection relative to the length of L2.\n%\n% So, the four equations are\n%\n% (x1(2) - x1(1))*t1 = x0 - x1(1)\n% (x2(2) - x2(1))*t2 = x0 - x2(1)\n% (y1(2) - y1(1))*t1 = y0 - y1(1)\n% (y2(2) - y2(1))*t2 = y0 - y2(1)\n%\n% Rearranging and writing in matrix form,\n%\n% [x1(2)-x1(1) 0 -1 0; [t1; [-x1(1);\n% 0 x2(2)-x2(1) -1 0; * t2; = -x2(1);\n% y1(2)-y1(1) 0 0 -1; x0; -y1(1);\n% 0 y2(2)-y2(1) 0 -1] y0] -y2(1)]\n%\n% Let's call that A*T = B. We can solve for T with T = A\\B.\n%\n% Once we have our solution we just have to look at t1 and t2 to determine\n% whether L1 and L2 intersect. If 0 <= t1 < 1 and 0 <= t2 < 1 then the two\n% line segments cross and we can include (x0,y0) in the output.\n%\n% In principle, we have to perform this computation on every pair of line\n% segments in the input data. This can be quite a large number of pairs so\n% we will reduce it by doing a simple preliminary check to eliminate line\n% segment pairs that could not possibly cross. The check is to look at the\n% smallest enclosing rectangles (with sides parallel to the axes) for each\n% line segment pair and see if they overlap. If they do then we have to\n% compute t1 and t2 (via the A\\B computation) to see if the line segments\n% cross, but if they don't then the line segments cannot cross. In a\n% typical application, this technique will eliminate most of the potential\n% line segment pairs.\n\n\n% Input checks.\nnarginchk(2,5)\n\n% Adjustments when fewer than five arguments are supplied.\nswitch nargin\n case 2\n robust = true;\n x2 = x1;\n y2 = y1;\n self_intersect = true;\n case 3\n robust = x2;\n x2 = x1;\n y2 = y1;\n self_intersect = true;\n case 4\n robust = true;\n self_intersect = false;\n case 5\n self_intersect = false;\nend\n\n% x1 and y1 must be vectors with same number of points (at least 2).\nif sum(size(x1) > 1) ~= 1 || sum(size(y1) > 1) ~= 1 || ...\n length(x1) ~= length(y1)\n error('CHEBFUN:CHEBFUN2:roots:intersections:badInputs1', ...\n 'X1 and Y1 must be equal-length vectors of at least 2 points.')\nend\n% x2 and y2 must be vectors with same number of points (at least 2).\nif sum(size(x2) > 1) ~= 1 || sum(size(y2) > 1) ~= 1 || ...\n length(x2) ~= length(y2)\n error('CHEBFUN:CHEBFUN2:roots:intersections:badInputs2', ...\n 'X2 and Y2 must be equal-length vectors of at least 2 points.')\nend\n\n\n% Force all inputs to be column vectors.\nx1 = x1(:);\ny1 = y1(:);\nx2 = x2(:);\ny2 = y2(:);\n\n% Compute number of line segments in each curve and some differences we'll\n% need later.\nn1 = length(x1) - 1;\nn2 = length(x2) - 1;\nxy1 = [x1 y1];\nxy2 = [x2 y2];\ndxy1 = diff(xy1);\ndxy2 = diff(xy2);\n\n% Determine the combinations of i and j where the rectangle enclosing the\n% i'th line segment of curve 1 overlaps with the rectangle enclosing the\n% j'th line segment of curve 2.\n[i,j] = find(repmat(min(x1(1:end-1),x1(2:end)),1,n2) <= ...\n repmat(max(x2(1:end-1),x2(2:end)).',n1,1) & ...\n repmat(max(x1(1:end-1),x1(2:end)),1,n2) >= ...\n repmat(min(x2(1:end-1),x2(2:end)).',n1,1) & ...\n repmat(min(y1(1:end-1),y1(2:end)),1,n2) <= ...\n repmat(max(y2(1:end-1),y2(2:end)).',n1,1) & ...\n repmat(max(y1(1:end-1),y1(2:end)),1,n2) >= ...\n repmat(min(y2(1:end-1),y2(2:end)).',n1,1));\n\n% Force i and j to be column vectors, even when their length is zero, i.e.,\n% we want them to be 0-by-1 instead of 0-by-0.\ni = reshape(i,[],1);\nj = reshape(j,[],1);\n\n% Find segments pairs which have at least one vertex = NaN and remove them.\n% This line is a fast way of finding such segment pairs. We take\n% advantage of the fact that NaNs propagate through calculations, in\n% particular subtraction (in the calculation of dxy1 and dxy2, which we\n% need anyway) and addition.\n% At the same time we can remove redundant combinations of i and j in the\n% case of finding intersections of a line with itself.\nif self_intersect\n remove = isnan(sum(dxy1(i,:) + dxy2(j,:),2)) | j <= i + 1;\nelse\n remove = isnan(sum(dxy1(i,:) + dxy2(j,:),2));\nend\ni(remove) = [];\nj(remove) = [];\n\n% Initialize matrices. We'll put the T's and B's in matrices and use them\n% one column at a time. AA is a 3-D extension of A where we'll use one\n% plane at a time.\nn = length(i);\nT = zeros(4,n);\nAA = zeros(4,4,n);\nAA([1 2],3,:) = -1;\nAA([3 4],4,:) = -1;\nAA([1 3],1,:) = dxy1(i,:).';\nAA([2 4],2,:) = dxy2(j,:).';\nB = -[x1(i) x2(j) y1(i) y2(j)].';\n\n% Loop through possibilities. Trap singularity warning and then use\n% lastwarn to see if that plane of AA is near singular. Process any such\n% segment pairs to determine if they are colinear (overlap) or merely\n% parallel. That test consists of checking to see if one of the endpoints\n% of the curve 2 segment lies on the curve 1 segment. This is done by\n% checking the cross product\n%\n% (x1(2),y1(2)) - (x1(1),y1(1)) x (x2(2),y2(2)) - (x1(1),y1(1)).\n%\n% If this is close to zero then the segments overlap.\n\n% If the robust option is false then we assume no two segment pairs are\n% parallel and just go ahead and do the computation. If A is ever singular\n% a warning will appear. This is faster and obviously you should use it\n% only when you know you will never have overlapping or parallel segment\n% pairs.\n\nif robust\n overlap = false(n,1);\n warning_state = warning('off','MATLAB:singularMatrix');\n % Use try-catch to guarantee original warning state is restored.\n try\n lastwarn('')\n for k = 1:n\n T(:,k) = AA(:,:,k)\\B(:,k);\n [unused,last_warn] = lastwarn;\n lastwarn('')\n if strcmp(last_warn,'MATLAB:singularMatrix')\n % Force in_range(k) to be false.\n T(1,k) = NaN;\n % Determine if these segments overlap or are just parallel.\n overlap(k) = rcond([dxy1(i(k),:);xy2(j(k),:) - xy1(i(k),:)]) < eps;\n end\n end\n warning(warning_state)\n catch err\n warning(warning_state)\n rethrow(err)\n end\n % Find where t1 and t2 are between 0 and 1 and return the corresponding\n % x0 and y0 values.\n in_range = (T(1,:) >= 0 & T(2,:) >= 0 & T(1,:) <= 1 & T(2,:) <= 1).';\n % For overlapping segment pairs the algorithm will return an\n % intersection point that is at the center of the overlapping region.\n if any(overlap)\n ia = i(overlap);\n ja = j(overlap);\n % set x0 and y0 to middle of overlapping region.\n T(3,overlap) = (max(min(x1(ia),x1(ia+1)),min(x2(ja),x2(ja+1))) + ...\n min(max(x1(ia),x1(ia+1)),max(x2(ja),x2(ja+1)))).'/2;\n T(4,overlap) = (max(min(y1(ia),y1(ia+1)),min(y2(ja),y2(ja+1))) + ...\n min(max(y1(ia),y1(ia+1)),max(y2(ja),y2(ja+1)))).'/2;\n selected = in_range | overlap;\n else\n selected = in_range;\n end\n xy0 = T(3:4,selected).';\n \n % Remove duplicate intersection points.\n [xy0,index] = unique(xy0,'rows');\n x0 = xy0(:,1);\n y0 = xy0(:,2);\n \n % Compute how far along each line segment the intersections are.\n if nargout > 2\n sel_index = find(selected);\n sel = sel_index(index);\n iout = i(sel) + T(1,sel).';\n jout = j(sel) + T(2,sel).';\n end\nelse % non-robust option\n for k = 1:n\n [L,U] = lu(AA(:,:,k));\n T(:,k) = U\\(L\\B(:,k));\n end\n \n % Find where t1 and t2 are between 0 and 1 and return the corresponding\n % x0 and y0 values.\n in_range = (T(1,:) >= 0 & T(2,:) >= 0 & T(1,:) < 1 & T(2,:) < 1).';\n x0 = T(3,in_range).';\n y0 = T(4,in_range).';\n \n % Compute how far along each line segment the intersections are.\n if nargout > 2\n iout = i(in_range) + T(1,in_range).';\n jout = j(in_range) + T(2,in_range).';\n end\nend\n\n% Plot the results (useful for debugging).\n% plot(x1,y1,x2,y2,x0,y0,'ok');\nend\n\n\nfunction x = mypoints(n, dom)\n% Get the sample points that correspond to the right grid for a particular\n% technology.\n\n% What tech am I based on?:\ntech = chebfunpref().tech();\nif ( ischar(tech) )\n tech = eval(tech);\nend\n\nif ( isa(tech, 'chebtech2') )\n x = chebpts( n, dom, 2 ); % x grid.\nelseif ( isa(tech, 'chebtech1') )\n x = chebpts( n, dom, 1 ); % x grid.\nelseif ( isa(tech, 'trigtech') )\n x = trigpts( n, dom ); % x grid.\nelse\n error('CHEBFUN:CHEBFUN2V:roots:techType', 'Unrecognized technology');\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/@chebfun2v/roots.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.5448547676222674}} {"text": "function value = r4_mach ( i )\n\n%*****************************************************************************80\n%\n%% R4_MACH returns single precision real machine constants.\n%\n% Discussion:\n%\n% Assume that single precision real numbers are stored with a mantissa\n% of T digits in base B, with an exponent whose value must lie\n% between EMIN and EMAX. Then for values of I between 1 and 5,\n% R1MACH will return the following values:\n%\n% R1MACH(1) = B^(EMIN-1), the smallest positive magnitude.\n% R1MACH(2) = B^EMAX*(1-B^(-T)), the largest magnitude.\n% R1MACH(3) = B^(-T), the smallest relative spacing.\n% R1MACH(4) = B^(1-T), the largest relative spacing.\n% R1MACH(5) = log10(B)\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 24 April 2007\n%\n% Author:\n%\n% Original FORTRAN77 version by Phyllis Fox, Andrew Hall, Norman Schryer\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Phyllis Fox, Andrew Hall, Norman Schryer,\n% Algorithm 528,\n% Framework for a Portable Library,\n% ACM Transactions on Mathematical Software,\n% Volume 4, Number 2, June 1978, page 176-188.\n%\n% Parameters:\n%\n% Input, integer I, chooses the parameter to be returned.\n% 1 <= I <= 5.\n%\n% Output, real VALUE, the value of the chosen parameter.\n%\n if ( i < 1 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R4_MACH - Fatal error!\\n' );\n fprintf ( 1, ' The input argument I is out of bounds.\\n' );\n fprintf ( 1, ' Legal values satisfy 1 <= I <= 5.\\n' );\n fprintf ( 1, ' I = %d\\n', i );\n value = 0.0;\n error ( 'R4_MACH - Fatal error!' );\n elseif ( i == 1 )\n value = 1.1754944E-38;\n elseif ( i == 2 )\n value = 3.4028235E+38;\n elseif ( i == 3 )\n value = 5.9604645E-08;\n elseif ( i == 4 )\n value = 1.1920929E-07;\n elseif ( i == 5 )\n value = 0.3010300;\n elseif ( 5 < i )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R4_MACH - Fatal error!\\n' );\n fprintf ( 1, ' The input argument I is out of bounds.\\n' );\n fprintf ( 1, ' Legal values satisfy 1 <= I <= 5.\\n' );\n fprintf ( 1, ' I = %d\\n', i );\n value = 0.0;\n error ( 'R4_MACH - 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/fn/r4_mach.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.721743206297598, "lm_q2_score": 0.7549149923816049, "lm_q1q2_score": 0.5448547670836262}} {"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 : nrtFfmMaxwellCFIEpec.m |\n%| # | VERSION : 0.61 |\n%| _#_ | AUTHOR(S) : Matthieu Aussal & Francois Alouges |\n%| ( # ) | CREATION : 14.03.2017 |\n%| / 0 \\ | LAST MODIF : 05.09.2019 |\n%| ( === ) | SYNOPSIS : Solve PEC scatering problem with CFIE |\n%| `---' | |\n%+========================================================================+\n\n% Cleaning\nclear all\nclose all\nclc\n\n% Gypsilab path\nrun('../../addpathGypsilab.m')\n\n% Parameters\nN = 1e3\ntol = 1e-3\ntyp = 'RWG'\ngss = 3\nbeta = 0.5;\n\n% Spherical mesh\nsphere = mshSphere(N,1);\nsigma = dom(sphere,gss);\nfigure\nplot(sphere)\naxis equal\n\n% Frequency adjusted to maximum esge size\nstp = sphere.stp;\nk = 1/stp(2);\nc = 299792458;\nf = (k*c)/(2*pi);\ndisp(['Frequency : ',num2str(f/1e6),' MHz']);\n\n% Incident direction and field\nX0 = [0 0 -1]; \nE = [0 1 0]; % Polarization (+x for Theta-Theta and +y for Phi-Phi)\nH = cross(X0,E);\n\n% Incident Plane wave (electromagnetic field)\nPWE{1} = @(X) exp(1i*k*X*X0') * E(1);\nPWE{2} = @(X) exp(1i*k*X*X0') * E(2);\nPWE{3} = @(X) exp(1i*k*X*X0') * E(3);\n\nPWH{1} = @(X) exp(1i*k*X*X0') * H(1);\nPWH{2} = @(X) exp(1i*k*X*X0') * H(2);\nPWH{3} = @(X) exp(1i*k*X*X0') * H(3);\n\n% Incident wave representation\nplot(sphere,real(PWH{1}(sphere.vtx)))\ntitle('Incident wave')\nxlabel('X'); ylabel('Y'); zlabel('Z');\nhold off\nview(0,10)\n\n\n%%% PREPARE OPERATOR\ndisp('~~~~~~~~~~~~~ PREPARE OPERATOR ~~~~~~~~~~~~~')\n\n% Green kernel function --> G(x,y) = exp(ik|x-y|)/|x-y| \nGxy = '[exp(ikr)/r]';\nHxy = {'grady[exp(ikr)/r]1','grady[exp(ikr)/r]2','grady[exp(ikr)/r]3'};\n\n% Finite elements\nu = fem(sphere,'RWG');\nv = fem(sphere,'RWG');\n\n% Finite element mass matrix --> \\int_Sx psi(x)' psi(x) dx\nId = integral(sigma,u,v);\n\n% Finite element boundary operator\ntic\nT = 1i*k/(4*pi)*integral(sigma, sigma, v, Gxy, k, u, tol) ...\n - 1i/(4*pi*k)*integral(sigma, sigma, div(v), Gxy, k, div(u), tol) ;\ntoc\n\n% Regularization\ntic\nTr = 1i*k/(4*pi)*regularize(sigma, sigma, v, '[1/r]', u) ...\n - 1i/(4*pi*k)*regularize(sigma, sigma, div(v), '[1/r]', div(u));\nT = T + Tr; \ntoc\n\n% Finite element boundary operator\ntic\nnxK = 1/(4*pi) * integral(sigma, sigma, nx(v), Hxy, k, u, tol); \ntoc\n\n% Regularization\ntic\nnxKr = 1/(4*pi) * regularize(sigma, sigma, nx(v), 'grady[1/r]', u);\nnxK = nxK + nxKr;\ntoc\n\n% Left hand side\nLHS = - beta * T + (1-beta) * (0.5*Id - nxK);\nLHSr = - beta * Tr + (1-beta) * (0.5*Id - nxKr);\n\n% Right hand side\nRHS = beta*integral(sigma,v,PWE) - (1-beta)*integral(sigma,nx(v),PWH);\n\n\n%%% SOLVE LINEAR PROBLEM\ndisp('~~~~~~~~~~~~~ SOLVE LINEAR PROBLEM ~~~~~~~~~~~~~')\n\n% ILU preconditionner\ntic\n[L,U] = ilu(LHSr);\ntoc\n\n% Iterative solver\ntic\nJ = mgcr(@(V) LHS*V,RHS,[],tol,1000,L,U);\ntoc\n\n\n%%% INFINITE SOLUTION\ndisp('~~~~~~~~~~~~~ INFINITE RADIATION ~~~~~~~~~~~~~')\n\n% Plane waves direction\nNinf = 1e3;\ntheta = 2*pi/1e3 .* (1:Ninf)';\nnu = [sin(theta),zeros(size(theta)),cos(theta)];\n\n% Green kernel function\nGinf = '[exp(-ikxy)]';\n\n% Finite element infinite operator --> \\int_Sy exp(ik*nu.y) * psi(y) dx\nTinf = integral(nu,sigma,Ginf,k,v,tol);\nsol = 1i*k/(4*pi)*cross(nu, cross([Tinf{1}*J, Tinf{2}*J, Tinf{3}*J], nu));\n\n% Radiation infinie de reference, convention e^(+ikr)/r\nnMax = 100; refInf = zeros(Ninf,1);\nif E(1) == 1\n for jj = 1:Ninf\n refInf(jj,:) = sphereMaxwell(1, -f, theta(jj), 0.0, nMax);\n end\nelse\n for jj = 1:Ninf\n [~,refInf(jj)] = sphereMaxwell(1, -f, theta(jj), pi/2, nMax);\n end\nend\nrefInf = refInf ./ sqrt(4*pi);\n\n% Radiations infinies en X\nif E(1) == 1\n sol = sin(theta)'.*sol(:,3) - cos(theta)'.*sol(:,1);\nelse\n sol = sol(:,2);\nend\n\n% Erreur\neL2 = norm(refInf-sol,2)/norm(refInf,2)\neLINF = norm(refInf-sol,'inf')/norm(refInf,'inf')\n \n% Representation graphique\nfigure\nsubplot(1,2,1)\nplot(theta,20*log10(abs(sol)),'b',theta,20*log10(abs(refInf)),'r--')\n\nsubplot(1,2,2)\nplot(theta,real(sol),'--b', theta,imag(sol),'--r', theta, real(refInf),':b', theta,imag(refInf),':r');\ndrawnow\n\n\n%%% SURFACIC RADIATION\ndisp('~~~~~~~~~~~~~ SURFACIC RADIATION ~~~~~~~~~~~~~')\n\n% Mesh Interpolation\nJmsh = feval(u,J,sphere);\nV = sqrt(sum(real(cell2mat(Jmsh)).^2,2));\n\n% Graphical representation\nfigure\nplot(sphere)\nhold on\nplot(sphere,V)\naxis equal\ntitle('|J| surfacic')\nxlabel('X'); ylabel('Y'); zlabel('Z');\ncolorbar\n\n\n\ndisp('~~> Michto gypsilab !')\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/fastFreeMemory/nrtFfmMaxwellCFIEpec.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314677809303, "lm_q2_score": 0.6150878696277513, "lm_q1q2_score": 0.5447411727926709}} {"text": "function [ fea, out ] = ex_linearelasticity6( varargin )\n%EX_LINEARELASTICITY6 NAFEMS LE6 skew plate benchmark\n%\n% [ FEA, OUT ] = EX_LINEARELASTICITY6( VARARGIN ) Skew plate under\n% normal pressure (NAFEMS LE6 Benchmark).\n%\n% Reference:\n%\n% [1] National Agency for Finite Element Methods and Standards. The\n% Standard NAFEMS Benchmarks. Rev. 3. United Kingdom: NAFEMS,\n% October 1990.\n%\n% Accepts the following property/value pairs.\n%\n% Input Value/{Default} Description\n% -----------------------------------------------------------------------------------\n% hmax string {0.05} Grid size\n% sfun string {sflag2} Shape function\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 = { 'hmax', 0.05;\n 'sfun', 'sflag2';\n 'iplot', 1;\n 'tol', 0.1;\n 'fid', 1 };\n[got,opt] = parseopt(cOptDef,varargin{:});\nfid = opt.fid;\n\n\nE = 210e9;\nnu = 0.3;\nrho = 7800;\nt = 0.01;\nload = -0.7e3;\n\n\n% Grid definition.\nfea.sdim = {'x', 'y', 'z'};\na = cos(pi*30/180);\np = [0 1 1+a a;0 0 0.5 0.5]';\ngeom_2d.objects{1} = gobj_polygon(p);\ngrid_2d = gridgen( geom_2d, 'hmax', opt.hmax, 'fid', fid );\nfea.grid = gridextrude( grid_2d, max(3,ceil(t/opt.hmax)), t );\n\n\n% Equations and problem definition.\nfea = addphys( fea, @linearelasticity );\nfea.phys.el.eqn.coef{1,end} = { nu };\nfea.phys.el.eqn.coef{2,end} = { E };\nfea.phys.el.eqn.coef{3,end} = { rho };\nfea.phys.el.sfun = { opt.sfun, opt.sfun, opt.sfun };\n\n\n% Set/constrain w = 0 on sides (boundaries 1-4).\nn_bdr = 6;\nbctype = mat2cell( zeros(3,n_bdr), [1 1 1], ones(1,n_bdr) );\n[bctype{3,[1:4]}] = deal(1);\nfea.phys.el.bdr.coef{1,5} = bctype;\n\n% Set/constrain u, v = 0 on edge 2, x = y = 0.\nedg(1).index = 2;\nedg(1).type = 'constraint';\nedg(1).dvar = 1;\nedg(1).expr = 0;\n\nedg(2).index = 2;\nedg(2).type = 'constraint';\nedg(2).dvar = 2;\nedg(2).expr = 0;\n\n% Set/constrain v = 0 on edge 1, x = 0, y = 1.\nedg(3).index = 1;\nedg(3).type = 'constraint';\nedg(3).dvar = 2;\nedg(3).expr = 0;\nfea.edg = edg;\n\n% Apply vertical load to top boundary.\nbccoef = mat2cell( zeros(3,n_bdr), [1 1 1], ones(1,n_bdr) );\nbccoef{3,6} = load;\nfea.phys.el.bdr.coef{1,end} = bccoef;\n\n\n% Solve problem.\nfea = parsephys( fea );\nfea = parseprob( fea );\n\nfea.sol.u = solvestat( fea, 'fid', fid );\n\n\n% Postprocessing.\nif( opt.iplot>0 )\n postplot( fea, 'surfexpr', 'sqrt(u^2+v^2+w^2)', ...\n 'deformexpr', {'u', 'v', 'w'} )\nend\n\n\n% Error checking.\nout = [];\np_E = [0.933012701892219; 0.25; 0];\nps1_E = evalexpr( fea.phys.el.eqn.vars{12,2}, p_E, fea );\nps2_E = evalexpr( fea.phys.el.eqn.vars{13,2}, p_E, fea );\nps3_E = evalexpr( fea.phys.el.eqn.vars{14,2}, p_E, fea );\nps_E_max = max([ps1_E,ps2_E,ps3_E]);\nps_E_ref = 0.802e6;\nout.w_E = evalexpr( 'w', p_E, fea );\nout.ps_E = [ps1_E, ps2_E, ps3_E];\nout.err = abs(ps_E_max-ps_E_ref)/ps_E_ref;\nout.pass = 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_linearelasticity6.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529376, "lm_q2_score": 0.6959583187272712, "lm_q1q2_score": 0.5447004629830048}} {"text": "function [rank,description,usedcards,unusedcards] = rankp(hands,handsize)\n% A function that evaluates poker hands and returns a numerical rank and\n% text description for each. The list of cards used to make the best\n% possible hand is returned in 'usedcards'. If handsize is smaller than\n% the length of hands given, then the cards not used in the best possible\n% hand are returned in 'unusedcards'. Rank of 1 is best (Royal Flush),\n% higher numbers are worse. Rank values are not contiguous across all\n% hands, but are correctly ordered.\n% \n% The hand matrix expected is an mxn list of m hands with n cards. The\n% cards are numbered from 1 to 52. Suit doesn't matter for ranking. Order\n% of the cards in the input vector does not matter. Numbering starts with\n% the Ace at position 1. Here is a suggested card assignment:\n% \n% A | K | Q | J | 10| 9 | 8 | 7 | 6 | 5 | 4 | 3 | 2 | Suit\n% -------------------------------------------------------------\n% 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10| 11| 12| 13| Spades\n% 14| 15| 16| 17| 18| 19| 20| 21| 22| 23| 24| 25| 26| Hearts\n% 27| 28| 29| 30| 31| 32| 33| 34| 35| 36| 37| 38| 39| Clubs\n% 40| 41| 42| 43| 44| 45| 46| 47| 48| 49| 50| 51| 52| Diamonds\n% \n% Example call to the function:\n% trick = [33,3,43,1,25,4,19;\n% 6,36,20,10,35,21,38;\n% 45,31,51,40,37,22,26;\n% 28,49,46,32,17,16,39]; \n% [ranks,descriptions,usedcards,unusedcards] = rankp(trick,2); \n% \n% revision 5\n% - fixed a conditional error in the numerical ranking section,\n% thanks to Tim C. for testing it\n% revision 4\n% - fixed a hole in the condition to wipe low aces if not used\n% revision 3\n% - made rankp \"toolbox neutral\" by using nchoosek instead of combnk,\n% thanks to James for pointing that out\n% - fixed a hole in the conditional statements for unusedcards\n% revision 2\n% - added handsize input, usedcards and unusedcards outputs\n% - improved speed of classification with help from Doug\n% revision 1\n% - written for Doug's LazyWeb by Rob\n\n%% Setup variables\n\nhandlen = size(hands,2);\nnumhands = size(hands,1);\n\n% quality check on handsize argument\nif nargin > 1\n handsize = min([handsize handlen 5]);\nelse\n handsize = min([handlen 5]);\nend\n\nrank = zeros(numhands,1);\ndescription = cell(numhands,1);\nusedcards = zeros(numhands,handsize);\nif handlen > handsize\n unusedcards = zeros(numhands,(handlen-handsize));\nelse\n unusedcards = [];\nend\n\n%% Main process loop\n\n% test each hand, keep max rank\nfor i = 1:numhands\n handcombs = nchoosek(hands(i,:),handsize);\n a = zeros(size(handcombs,1),1);\n b = cell(size(a));\n for j = 1:size(handcombs,1)\n [a(j),b{j}] = rankhand(handcombs(j,:));\n end\n [a,ix] = sort(a);\n rank(i) = a(1);\n description{i} = b(ix(1));\n usedcards(i,:) = handcombs(ix(1),:);\n if handlen > handsize\n unusedcards(i,:) = setxor(usedcards(i,:),hands(i,:));\n end\nend\n\n%% Sub function\n\nfunction [r,handclass] = rankhand(hand)\n\n% Setup variables\nif nargin < 1 || length(hand) > 5\n r = 0;\n handclass = 'Hand must have 1 to 5 cards!';\n return;\nend\n\nlen = length(hand);\ncards = zeros(13,4);\ncards(hand) = 1;\ncards(14,:) = cards(1,:);\n\ncolsum = sum(cards);\nrowsum = sum(cards,2);\nrownames = {'Ace';'King';'Queen';'Jack';'10';'9';'8';'7';'6';'5';'4'; ...\n '3';'2';'Ace'};\n\nhandclass = 'High';\ndone = false;\n\n%% Classify the hand\n\n% test for Straight and Straight-flush, wipe low Ace if not used\nif len==5\n if any(sum(logical([rowsum(1:5) rowsum(2:6) rowsum(3:7) rowsum(4:8)...\n rowsum(5:9) rowsum(6:10) rowsum(7:11) rowsum(8:12)...\n rowsum(9:13) rowsum(10:14)]))==5)\n if sum(logical(colsum))==1\n handclass = 'Straigh Flush';\n else\n handclass = 'Straight';\n end\n if sum(logical(rowsum(10:14))) == 5\n cards(1,:) = 0;\n else\n cards(14,:) = 0;\n end\n colsum = sum(cards);\n rowsum = sum(cards,2);\n done = true;\n end\nend\nif ~done\n cards(14,:) = 0;\n colsum = sum(cards);\n rowsum = sum(cards,2);\nend\n\n% test for Four of a Kind\nif len >= 4\n if ~done && sum(rowsum==4)==1\n handclass = 'Four';\n done = true;\n end\nend\n\n% test for full house\nif len == 5\n if ~done && sum(rowsum==3)==1 && sum(rowsum==2)==1\n handclass = 'Full House';\n done = true;\n end\n% test for Flush\n if ~done && sum(colsum==5)==1\n handclass = 'Flush';\n done = true;\n end\nend\n\n% test for 3 of a kind\nif len >= 3\n if ~done && sum(rowsum==3)==1\n handclass = 'Three';\n done = true;\n end\nend\n\n% test for 2 pairs\nif len >= 4\n if ~done && sum(rowsum==2)==2\n handclass = 'Two Pairs';\n done = true;\n end\nend\n\n% test for 1 pair\nif len >= 2\n if ~done && sum(rowsum==2)==1\n handclass = 'Pair';\n end\nend\n\n% if nothing else, handclass stays 'High'\n\n%% Numerically rank the hand within its class\n\nswitch handclass\n case 'Straigh Flush'\n r = find(rowsum,1,'first');\n case 'Four'\n r = 1e1*find(rowsum==4);\n if len == 5\n r = r + find(rowsum==1);\n end\n case 'Full House'\n r = 2e2*find(rowsum==3) + find(rowsum==2);\n case 'Flush'\n a = find(rowsum);\n r = 3e3*a(1)+1e2*a(2)+1e2/2*a(3)+1e1*a(4)+a(5);\n case 'Straight'\n r = 4e4*find(rowsum,1,'first');\n case 'Three'\n r = 5e5*find(rowsum==3);\n if len > 3\n a = find(rowsum==1);\n r = r+1e4*a(1);\n if len==5\n r = r+1e3*a(2);\n end\n end\n case 'Two Pairs'\n a = find(rowsum==2);\n r = 7e6*a(1)+1e5*a(2);\n if len == 5\n b = find(rowsum==1);\n r = r+1e4*b(1);\n end\n case 'Pair'\n a = find(rowsum==2);\n r = 2e8*a(1);\n if len > 2\n b = find(rowsum==1);\n r = r+1e6*b(1);\n if len > 3\n r = r+1e5*b(2);\n if len == 5\n r = r+1e4*b(3);\n end\n end\n end\n case 'High'\n a = find(rowsum);\n r = 5e9*a(1);\n if len > 1\n r = r+1e7*a(2);\n if len > 2\n r = r+1e6*a(3);\n if len > 3\n r = r+1e5*a(4);\n if len == 5\n r = r+a(5);\n end\n end\n end\n end\n otherwise\n disp('There was an error classifying this hand!');\n return;\nend\n\n%% Generate text output to describe the hand\n\nswitch handclass\n case 'Straigh Flush'\n if r == 1\n handclass = 'Royal Flush!';\n else\n handclass = [handclass,' to the ',rownames{find(rowsum,1,'first')}];\n end\n case 'Four'\n handclass = [handclass,' ',rownames{find(rowsum==4)},'''s'];\n if len == 5\n handclass = [handclass,' and a ',rownames{find(rowsum==1)}];\n end\n case 'Full House'\n handclass = [handclass,', ',rownames{find(rowsum==3)},'''s and ',...\n rownames{find(rowsum==2)},'''s'];\n case 'Flush'\n handclass = [handclass,' with ',rownames{a(1)},', ',rownames{a(2)},...\n ', ',rownames{a(3)},', ',rownames{a(4)},', and ',rownames{a(5)}];\n case 'Straight'\n handclass = [handclass,' to the ',rownames{find(rowsum,1,'first')}];\n case 'Three'\n handclass = [handclass,' ',rownames{find(rowsum==3)},'s'];\n if len > 3\n handclass = [handclass,' with ',rownames{a(1)}];\n if len == 5\n handclass = [handclass,', and ',rownames{a(2)}];\n end\n end\n case 'Two Pairs'\n handclass = [handclass,', ',rownames{a(1)},'''s and ',rownames{a(2)},'''s'];\n if len == 5\n handclass = [handclass,' with a(n) ',rownames{b(1)}];\n end\n case 'Pair'\n handclass = [handclass,' of ',rownames{a(1)},'''s'];\n if len > 2\n handclass = [handclass,' with ',rownames{b(1)}];\n if len > 3\n handclass = [handclass,', ',rownames{b(2)}];\n if len == 5\n handclass = [handclass,', and ',rownames{b(3)}];\n end\n end\n end\n case 'High'\n handclass = [rownames{a(1)},' ',handclass,' with ',rownames{a(2)}];\n if len > 2\n handclass = [handclass,', ',rownames{a(3)}];\n if len > 3\n handclass = [handclass,', ',rownames{a(4)}];\n if len == 5\n handclass = [handclass,', and ',rownames{a(5)}];\n end\n end\n end\n otherwise\n disp('There was an error generating text for this hand.');\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/17579-poker-hand-ranker/rankp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84997116805678, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5445220058373219}} {"text": "classdef tt_function\n %TT_FUNCTION Summary of this class goes here\n % Detailed explanation goes here\n \n properties\n fun;\n coeff;\n end\n \n methods\n %-----------------------------------------------------------------%\n function obj = tt_function(fun, coeff)\n obj.fun = fun;\n obj.coeff = coeff;\n end\n \n %-----------------------------------------------------------------%\n function tt = to_tt_tensor(obj, x)\n %TO_TT_TENSOR Converts tt_function to tt_tensor\n % x - d x 1 cell array of coordinates for evaluation\n \n d = obj.coeff.d;\n r = obj.coeff.r;\n n = obj.coeff.n;\n ps = obj.coeff.ps;\n cr = obj.coeff.core;\n n_tt = cellfun(@numel, x);\n ps_tt = cumsum([1 ; n_tt.*r(1:d).*r(2:d+1)]);\n cr_tt = zeros(ps_tt(d+1)-1, 1);\n \n % compute basis functions\n basis = tt_function.get_basis(x, obj.fun, n);\n \n % evaluate cores\n for i = 1: d\n c = reshape(cr(ps(i):ps(i+1)-1), [r(i) n(i) r(i+1)]);\n t = ten_conv(c, 2, basis{i});\n cr_tt(ps_tt(i):ps_tt(i+1)-1) = reshape(t, [r(i)*n_tt(i)*r(i+1) 1]);\n end\n \n tt = tt_tensor;\n tt.d = d;\n tt.r = r;\n tt.n = n_tt;\n tt.ps = ps_tt;\n tt.core = cr_tt;\n \n end\n \n %-----------------------------------------------------------------%\n function val = eval(obj, x)\n %EVAL Evaluates tt_function at a given d-dimensional point\n % Inefficient code, simple solution\n \n d = numel(x);\n t = cell(d,1);\n for i = 1: d\n t{i} = x(i);\n end\n tt = obj.to_tt_tensor(t);\n val = tt(ones(1, d));\n \n end\n \n end\n \n methods (Static)\n %-----------------------------------------------------------------%\n function basis = get_basis(x, fun, n)\n %GET_BASIS Constructs a cell array of values of basis functions.\n\n d = numel(n);\n basis = cell(d, 1);\n \n for i = 1: d\n basis{i} = zeros(n(i), numel(x{i}));\n for j = 1: n(i)\n for k = 1: numel(x{i})\n basis{i}(j,k) = fun(i, j, x{i}(k));\n end\n end\n end\n\n end\n \n end\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/tt_function.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5444177147550199}} {"text": "% TTeMPS Toolbox. \n% Michael Steinlechner, 2013-2016\n% Questions and contact: michael.steinlechner@epfl.ch\n% BSD 2-clause license, see LICENSE.txt\n\nfunction [X, residual, cost] = amen( L, F, X, opts )\n\n% set default opts\nif ~exist( 'opts', 'var'); opts = struct(); end\nif ~isfield( opts, 'nSweeps'); opts.nSweeps = 4; end\nif ~isfield( opts, 'maxrank'); opts.maxrank = 20; end\nif ~isfield( opts, 'maxrankRes'); opts.maxrankRes = 4; end\nif ~isfield( opts, 'tolRes'); opts.tolRes = 1e-13; end\nif ~isfield( opts, 'tol'); opts.tol = 1e-13; end\n\nd = X.order;\nn = X.size;\n\n\nnormF = norm(F);\ncost = cost_function( L, X, F );\nresidual = norm( apply(L, X) - F ) / normF;\n\nfor sweep = 1:opts.nSweeps\n X = orthogonalize(X, 1);\n for mu = 1:d-1\n disp( ['Current core: ', num2str(mu)] )\n\n % STEP 1: Solve mu-th core opimization \n L_mu = contract( L, X, mu );\n F_mu = contract( X, F, mu );\n \n U_mu = L_mu \\ F_mu(:);\n X.U{mu} = reshape( U_mu, size(X.U{mu}) );\n \n % STEP 2: Calculate current residual and cost function \n res = F - apply(L, X);\n residual = [residual; norm( res ) / normF];\n cost = [cost; cost_function( L, X, F )];\n disp(['Rel. residual: ' num2str(residual(end)) ', Current rank: ' num2str(X.rank) ]);\n\n % STEP 3: Augment mu-th and (mu+1)-th core with (truncated) residual\n R = contract( X, res, [mu, mu+1] );\n R_combined = unfold(R{1},'left') * unfold(R{2},'right'); \n\n [uu,ss,~] = svd( R_combined, 'econ'); \n s = find( diag(ss) > opts.tolRes*norm(diag(ss)), 1, 'last' );\n\t\tif opts.maxrankRes ~= 0 \n\t\t\ts = min( s, opts.maxrankRes );\n\t\tend\n R{1} = reshape( uu(:,1:s)*ss(1:s,1:s), [X.rank(mu), n(mu), s]);\n %R{2} = reshape( vv(:,1:s)', [s, n(mu+1), X.rank(mu+2)]);\n\n left = cat(3, X.U{mu}, R{1});\n %right = cat(1, X.U{mu+1}, R{2});\n\n % STEP 4: Move orthogonality to (mu+1)-th core while performing rank truncation \n [U,S,~] = svd( unfold(left,'left'), 'econ' );\n t = find( diag(S) > opts.tol*norm(diag(S)), 1, 'last' );\n t = min( t, opts.maxrank );\n X.U{mu} = reshape( U(:,1:t), [X.rank(mu), n(mu), t] );\n %X.U{mu+1} = tensorprod_ttemps( right, S(1:t,1:t)*V(:,1:t)', 1);\n X.U{mu+1} = rand( t, n(mu+1), X.rank(mu+2));\n\n end\n for mu = d:-1:2\n disp( ['Current core: ', num2str(mu)] )\n\n % STEP 1: Solve mu-th core opimization \n L_mu = contract( L, X, mu );\n F_mu = contract( X, F, mu );\n \n U_mu = L_mu \\ F_mu(:);\n X.U{mu} = reshape( U_mu, size(X.U{mu}) );\n \n % STEP 2: Calculate current residual and cost function \n res = F - apply(L, X);\n residual = [residual; norm( res ) / normF];\n disp(['Rel. residual: ' num2str(residual(end)) ', Current rank: ' num2str(X.rank) ]);\n cost = [cost; cost_function( L, X, F )];\n\n % STEP 3: Augment mu-th and (mu+1)-th core with (truncated) residual\n R = contract( X, res, [mu-1, mu] );\n R_combined = unfold(R{1},'left') * unfold(R{2},'right'); \n\n [~,ss,vv] = svd( R_combined, 'econ'); \n s = find( diag(ss) > opts.tolRes*norm(diag(ss)), 1, 'last' );\n\t\tif opts.maxrankRes ~= 0 \n\t\t\ts = min( s, opts.maxrankRes );\n\t\tend\n R{2} = reshape( ss(1:s,1:s)*vv(:,1:s)', [s, n(mu), X.rank(mu+1)]);\n\n right = cat(1, X.U{mu}, R{2});\n\n % STEP 4: Move orthogonality to (mu+1)-th core while performing rank truncation \n [~,S,V] = svd( unfold(right,'right'), 'econ' );\n t = find( diag(S) > opts.tol*norm(diag(S)), 1, 'last' );\n t = min( t, opts.maxrank );\n X.U{mu} = reshape( V(:,1:t)', [t, n(mu), X.rank(mu+1)] );\n %X.U{mu+1} = tensorprod_ttemps( right, S(1:t,1:t)*V(:,1:t)', 1);\n X.U{mu-1} = rand( X.rank(mu-1), n(mu-1), t);\n\n %residuum = [residuum; norm( apply(L, X) - F ) / normF];\n\n %L_mu = contract( L, X, mu );\n %F_mu = contract( X, F, mu );\n\n %U_mu = L_mu \\ F_mu(:);\n %X.U{mu} = reshape( U_mu, size(X.U{mu}) );\n %X = orth_at( X, mu, 'right', true );\n %residuum = [residuum; norm( apply(L, X) - F ) / normF];\n %cost = [cost; cost_function( L, X, F )];\n %disp(['Rel. residual: ' num2str(residuum(end)) ', Current rank: ' num2str(X.rank) ]);\n end\n\nend\n\n\nend\n\nfunction res = cost_function( L, X, F )\nres = 0.5*innerprod( X, apply(L, X) ) - innerprod( X, F );\nend\n\nfunction res = euclid_grad( L, X, F )\nres = apply(L, X) - F;\nend\n\n", "meta": {"author": "NicolasBoumal", "repo": "manopt", "sha": "b8b54a6af8b965f7ae572972ba0d15787427744b", "save_path": "github-repos/MATLAB/NicolasBoumal-manopt", "path": "github-repos/MATLAB/NicolasBoumal-manopt/manopt-b8b54a6af8b965f7ae572972ba0d15787427744b/manopt/manifolds/ttfixedrank/TTeMPS_1.1/algorithms/linearsystem/amen.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117898012104, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.5443215158669551}} {"text": "% op_ppmref.m\n% Jamie Near, McGill University 2015.\n% \n% USAGE:\n% [out,frqshift]=op_ppmref(in,ppmmin,ppmmax,ppmrefval,dimNum);\n% \n% DESCRIPTION:\n% Search for the peak located between ppmmin and ppmmax, and then give that\n% peak a new ppm reference value.\n% \n% INPUTS:\n% in = input data in matlab structure format.\n% ppmmin = minimum of ppm search range.\n% ppmmax = maximum of ppm search range.\n% ppmrefval = new reference ppm value.\n% dimNum = which subspectrum to used for referencing (optional).\n%\n% OUTPUTS:\n% out = Output dataset following frequency shift.\n% frqshift = Frequency shift applied (in Hz).\n\nfunction [out,frqshift]=op_ppmref(in,ppmmin,ppmmax,ppmrefval,dimNum);\n\n\nif in.dims.coils>0\n error('ERROR: Can not operate on data with multilple coils! ABORTING!!')\nend\nif in.dims.averages>0\n error('ERROR: Can not operate on data with multiple averages! ABORTING!!');\nend\nif in.dims.extras>0\n error('ERROR: Can not operate on data with extras dimension! ABORTING!!');\nend\nif in.dims.subSpecs>0\n if nargin<5\n plot(in.ppm,in.specs);\n legend('subspec 1','subspec 2');\n dimNum=input('Input which subspectrum to use for referencing: ');\n end\nelse\n dimNum=1;\nend\n\n%Zeropad the data if it hasn't already been done\nif ~in.flags.zeropadded\n in_zp=op_zeropad(in,10);\nelse\n in_zp=in;\nend\n\n%Find the ppm of the maximum peak magnitude within the given range:\nppmindex=find(abs(in_zp.specs(in_zp.ppm>ppmmin & in_zp.ppmppmmin & in_zp.ppmppmmin & in_zp.ppm 1st scale coefficients \n% | | `-----------> 2nd scale coefficients\n% | `--------------------> 3rd scale coefficients\n% `----------------> Low pass residue at 3rd scale \n%\n% \n% If X is a matrix, the result will be another matrix with \n% the same number of rows, holding each one its respective \n% transformation.\n%\n% WT (X,H,G,K,DEL1,DEL2) calculates the wavelet transform of \n% vector X, but also allows the users to change the alignment\n% of the outputs with respect to the input signal. This effect\n% is achieved by setting to DEL1 and DEL2 the delays of H and\n% G respectively. The default values of DEL1 and DEL2 are \n% calculated using the function WTCENTER. \n\n% -----------------------------------\n% CHECK PARAMETERS AND OPTIONS\n% -----------------------------------\n\nh=h(:)'; % Arrange the filters so that they are row vectors.\ng=g(:)';\n\nif length(x)<2^k \n disp('The scale is too high. The maximum for the signal is:')\n floor(log2(length(x)))\n return\nend\n\n[liy,lix]=size(x);\n\nif lix==1 % And arrange the input vector to a row if \n x=x'; % it's not a matrix. \n trasp=1; % (and take note of it)\n [liy,lix]=size(x);\nelse\n trasp=0;\nend\n\n\n%--------------------------\n% DELAY CALCULATION \n%--------------------------\n\n% Calculate delays as the C.O.E. of the filters\ndlp=wtcenter(h);\ndhp=wtcenter(g);\n\nif rem(dhp-dlp,2)~=0 % difference between them.\n dhp=dhp+1; % must be even\nend;\n\nif nargin==6, % Other experimental filter delays\n dlp=del1; % can be forced from the arguments\n dhp=del2;\nend;\n\n%------------------------------\n% WRAPPAROUND CALCULATION \n%------------------------------\nllp=length(h); % Length of the lowpass filter\nlhp=length(g); % Length of the highpass filter.\n\nL=max([lhp,llp,dlp,dhp]); % The number of samples for the\n % wrapparound. Thus, we should need to \n % move along any L samples to get the\n % output wavelet vector phase equal to\n % original input phase.\n\n\n%------------------------------\n% START THE ALGORITHM \n%------------------------------\n\nfor it=1:liy, % For every row of the input matrix...\n % (this makes one wavelet transform\n % for each of the rows of the input matrix)\n tm=[];\n t=x(it,:); % Copy the vector to transform.\n\n for i=1:k % For every scale (iteration)...\n lx=length(t);\n if rem(lx,2)~=0 % Check that the number of samples\n t=[t,0]; % will be even (because of decimation).\n lx=lx+1;\n end\n tp=t; % Build wrapparound. The input signal\n pl=length(tp); % can be smaller than L, so it can\n while L>pl % be necessary to repeat it several\n tp=[tp,t]; % times\n pl=length(tp);\n end\n\n t=[tp(pl-L+1:pl),t,tp(1:L)]; % Add the wrapparound.\n\n yl=conv(t,h); % Then do lowpass filtering ...\n yh=conv(t,g); % ... and highpass filtering.\n\n yl=yl((dlp+1+L):2:(dlp+L+lx)); % Decimate the outputs\n yh=yh((dhp+1+L):2:(dhp+L+lx)); % and leave out wrapparound\n\n tm=[yh,tm]; % Put the resulting wavelet step\n % on its place into the wavelet \n % vector...\n t=yl; % ... and set the next iteration.\n end\n\n y(it,:)=[t,tm]; % Wavelet vector (1 row vector)\n\n\nend % End of the \"rows\" loop.\n\n%------------------------------\n% END OF THE ALGORITHM \n%------------------------------\n\nif trasp==1 % If the input data was a column vector\n y=y'; % then transpose it.\nend\n\n\n\nfunction d=wtcenter(x,op);\n\n% WTCENTER Calculates the delay of filters for alignment.\n%\n% WTCENTER (X) calculates the integer aproximation\n% of delay for filter X using the method set with\n% the WTMETHOD function, for alignment operations\n% in Wavelet transforms.\n%\n% For a non integer value, use the CENTER function.\n%\n% See also: WTMETHOD, CENTER, WT\n%\n\nglobal WTCENTERMETHOD\n\nif size(WTCENTERMETHOD)==[0,0]\n WTCENTERMETHOD=0;\nend\n\nif WTCENTERMETHOD>3 | WTCENTERMETHOD<0\n WTCENTERMETHOD=0\nend\n \nd=floor(center(x,WTCENTERMETHOD));\n\n% (Another long function !!!)\n\n\nfunction d=center(x,op);\n\n% CENTER Delay calculation for Wavelet transform alignment.\n%\n% CENTER (X, OP) calculates the delay for filter in X \n% according to the alignment method indicated in OP. \n% This delay is used by Wavelet transform functions.\n% The value of OP can be:\n% 0 : First Absolute Maxima Location\n% 1 : Zero delay in analysis (Full for synthesis).\n% 2 : Mass center (sum(m*d)/sum(m))\n% 3 : Energy center (sum(m^2 *d)/sum(m^2))\n%\n% If no output argument is given, then the vector X will\n% be plotted in the current figure, and a color line will be \n% marking the result.(red: OP=0; green: OP=1; cyan: OP=2; \n% blue: OP=4)\n\nlx=length(x);\nl=1:lx;\n\nif op==1\n d=0;\nelse\n if op==2\n xx=abs(x(:)');\n L=l;\n end\n if op==3\n xx=x(:)'.^2;\n L=l;\n end\n if op==0\n [mx,d]=max(abs(x));\n else \n \n d=sum(xx.*L)/sum(xx);\n end\nend\n\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/@core/filterbank.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430562234878, "lm_q2_score": 0.6548947290421276, "lm_q1q2_score": 0.544311206600727}} {"text": "function [out_profile,out_IMU_bias_est,out_KF_SD,out_R_matrix,out_Q_matrix,corrections] =...\n Loosely_coupled_INS_GNSS(init_cond, filter_time, epoch, lla, gps, imu, LC_KF_config, est_IMU_bias)\n%Loosely_coupled_INS_GNSS - Simulates inertial navigation using ECEF\n% navigation equations and kinematic model, GNSS using a least-squares\n% positioning algorithm, and loosely-coupled INS/GNSS integration. \n%\n% Software for use with \"Principles of GNSS, Inertial, and Multisensor\n% Integrated Navigation Systems,\" Second Edition.\n%\n% This function created 12/4/2012 by Paul Groves\n%\n% Significant changes made to data-formatting and time-handling by Adam\n% Werries, 2015/2016.\n%\n% Inputs:\n% LC_KF_config\n% .init_att_unc Initial attitude uncertainty per axis (rad)\n% .init_vel_unc Initial velocity uncertainty per axis (m/s)\n% .init_pos_unc Initial position uncertainty per axis (m)\n% .init_b_a_unc Initial accel. bias uncertainty (m/s^2)\n% .init_b_g_unc Initial gyro. bias uncertainty (rad/s)\n% .gyro_noise_PSD Gyro noise PSD (rad^2/s)\n% .accel_noise_PSD Accelerometer noise PSD (m^2 s^-3)\n% .accel_bias_PSD Accelerometer bias random walk PSD (m^2 s^-5)\n% .gyro_bias_PSD Gyro bias random walk PSD (rad^2 s^-3)\n% .pos_meas_SD Position measurement noise SD per axis (m)\n% .vel_meas_SD Velocity measurement noise SD per axis (m/s)\n% .init_biases IMU bias initialization\n%\n% Outputs:\n% out_profile Navigation solution as a motion profile array\n% out_IMU_bias_est Kalman filter IMU bias estimate array\n% out_clock GNSS Receiver clock estimate array\n% out_KF_SD Output Kalman filter state uncertainties\n%\n% Format of motion profiles:\n% Column 1: time (sec)\n% Column 2: latitude (rad)\n% Column 3: longitude (rad)\n% Column 4: height (m)\n% Column 5: north velocity (m/s)\n% Column 6: east velocity (m/s)\n% Column 7: down velocity (m/s)\n% Column 8: roll angle of body w.r.t NED (rad)\n% Column 9: pitch angle of body w.r.t NED (rad)\n% Column 10: yaw angle of body w.r.t NED (rad)\n%\n% Format of output IMU biases array:\n% Column 1: time (sec)\n% Column 2: estimated X accelerometer bias (m/s^2)\n% Column 3: estimated Y accelerometer bias (m/s^2)\n% Column 4: estimated Z accelerometer bias (m/s^2)\n% Column 5: estimated X gyro bias (rad/s)\n% Column 6: estimated Y gyro bias (rad/s)\n% Column 7: estimated Z gyro bias (rad/s)\n%\n% Format of KF state uncertainties array:\n% Column 1: time (sec)\n% Column 2: X attitude error uncertainty (rad)\n% Column 3: Y attitude error uncertainty (rad)\n% Column 4: Z attitude error uncertainty (rad)\n% Column 5: X velocity error uncertainty (m/s)\n% Column 6: Y velocity error uncertainty (m/s)\n% Column 7: Z velocity error uncertainty (m/s)\n% Column 8: X position error uncertainty (m)\n% Column 9: Y position error uncertainty (m)\n% Column 10: Z position error uncertainty (m)\n% Column 11: X accelerometer bias uncertainty (m/s^2)\n% Column 12: Y accelerometer bias uncertainty (m/s^2)\n% Column 13: Z accelerometer bias uncertainty (m/s^2)\n% Column 14: X gyro bias uncertainty (rad/s)\n% Column 15: Y gyro bias uncertainty (rad/s)\n% Column 16: Z gyro bias uncertainty (rad/s)\n\nold_time = filter_time(1);\n\n% Initialize INS from GPS\nold_est_r_eb_e = init_cond(1:3)';\nold_est_v_eb_e = init_cond(4:6)';\n[old_est_L_b,old_est_lambda_b,old_est_h_b,old_est_v_eb_n] = pv_ECEF_to_NED(old_est_r_eb_e,old_est_v_eb_e);\nest_L_b = old_est_L_b;\n\n% Initialize estimated attitude solution\n% old_est_C_b_n = Initialize_NED_attitude(true_C_b_n,initialization_errors);\nold_est_C_b_n = Euler_to_CTM(init_cond(7:9));\n[~,~,old_est_C_b_e] = NED_to_ECEF(old_est_L_b,old_est_lambda_b,old_est_h_b,old_est_v_eb_n,old_est_C_b_n);\nold_est_r_eb_e = old_est_r_eb_e + old_est_C_b_e*LC_KF_config.lever_arm + old_est_C_b_e*LC_KF_config.gps_correction;\n\n% Initialize output profile record and errors record\nout_profile = zeros(length(filter_time),10);\n\n% Generate output profile record\nout_profile(1,1) = old_time;\nout_profile(1,2:4) = old_est_r_eb_e;\nout_profile(1,5:7) = old_est_v_eb_e';\nout_profile(1,8:10) = CTM_to_Euler(old_est_C_b_n')';\n\n% Initialize Kalman filter P matrix and IMU bias states\nP_matrix = Initialize_LC_P_matrix(LC_KF_config);\n\n% Generate IMU bias and clock output records\nout_IMU_bias_est(1,1) = old_time;\nout_IMU_bias_est(1,2:7) = est_IMU_bias';\n\n% Generate KF uncertainty record\nout_KF_SD(1,1) = old_time;\nfor n = 1:15\n out_KF_SD(1,n+1) = sqrt(P_matrix(n,n));\nend % for i\n\n% Initialize R (not really used but it makes me feel better\npos_variance = LC_KF_config.gps_pos_stddev.^2*gps(1,16).^2.*ones(1,3);\nvel_variance = LC_KF_config.gps_vel_stddev.^2*gps(1,16).^2.*ones(1,3);\nR_matrix(1:3,1:3) = diag(max(LC_KF_config.pos_sd_min, ...\n min(LC_KF_config.pos_sd_max,...\n pos_variance)));\nR_matrix(1:3,4:6) = zeros(3);\nR_matrix(4:6,1:3) = zeros(3);\nR_matrix(4:6,4:6) = diag(max(LC_KF_config.vel_sd_min,...\n min(LC_KF_config.vel_sd_max,...\n vel_variance)));\n\nout_R_matrix = zeros(size(gps,1), 6);\nfor n = 1:6\n out_R_matrix(1,n) = R_matrix(n,n);\nend % for i\nout_Q_matrix = zeros(size(gps,1), 15);\nQ_matrix = zeros(15,15);\nfor n = 1:15\n out_Q_matrix(1,n) = Q_matrix(n,n);\nend % for i\n% Main loop\nGNSS_epoch = 2;\nlast_GNSS_epoch = GNSS_epoch;\ncorrections = zeros(15,size(gps,1)-1);\nlast_imu_index = 1;\nnumIMU = size(imu, 1);\nimu_index_windowsize = floor(20*epoch/mean(diff(imu(:,1))));\nfor i = 2:length(filter_time)\n time = filter_time(i);\n % find range of imu measurements to use\n endcap = min(numIMU, last_imu_index+1 + imu_index_windowsize);\n indices = find(imu(last_imu_index+1:endcap,1) < time);\n imu_range_end = last_imu_index + indices(end) - 1;\n % Apply IMU bias estimates\n meas_f_ib_b = mean(imu(last_imu_index+1:imu_range_end,2:4))' - est_IMU_bias(1:3);\n meas_omega_ib_b = mean(imu(last_imu_index+1:imu_range_end,5:7))' - est_IMU_bias(4:6);\n \n % Update estimated navigation solution\n [est_r_eb_e,est_v_eb_e,est_C_b_e] = Nav_equations_ECEF(epoch,...\n old_est_r_eb_e,old_est_v_eb_e,old_est_C_b_e,meas_f_ib_b,...\n meas_omega_ib_b);\n% while GNSS_epoch < size(gps,1)+1 && ~gps(GNSS_epoch,3)\n% GNSS_epoch = GNSS_epoch + 1;\n% end\n % Determine whether to update GNSS simulation and run Kalman filter\n if GNSS_epoch <= size(gps,1) && time > gps(GNSS_epoch,1)\n tor_s = gps(GNSS_epoch,1) - gps(last_GNSS_epoch,1); % KF time interval\n GNSS_r_eb_e = gps(GNSS_epoch,9:11)';\n GNSS_v_eb_e = gps(GNSS_epoch,12:14)';\n est_L_b = lla(GNSS_epoch,1);\n % Use the GPS-reported standard deviation values, but clamping\n % min/max values according to configuration\n pos_variance = LC_KF_config.gps_pos_stddev.^2*gps(GNSS_epoch,16).^2;\n vel_variance = LC_KF_config.gps_vel_stddev.^2*gps(GNSS_epoch,16).^2;\n R_matrix(1:3,1:3) = diag(max(LC_KF_config.pos_sd_min, ...\n min(LC_KF_config.pos_sd_max,...\n pos_variance.*ones(1,3)*tor_s)));\n R_matrix(4:6,4:6) = diag(max(LC_KF_config.vel_sd_min,...\n min(LC_KF_config.vel_sd_max,...\n vel_variance.*ones(1,3)*tor_s)));\n% disp(size(R_matrix));\n% disp(diag(R_matrix));\n \n % Run Integration Kalman filter\n [est_C_b_e,est_v_eb_e,est_r_eb_e,est_IMU_bias,P_matrix_new,corrections(:,GNSS_epoch-1), Phi_matrix, Q_matrix] =...\n LC_KF_Epoch(GNSS_epoch, GNSS_r_eb_e,GNSS_v_eb_e,tor_s,est_C_b_e,...\n est_v_eb_e,est_r_eb_e,est_IMU_bias,P_matrix,meas_f_ib_b,...\n est_L_b,LC_KF_config,Q_matrix,R_matrix,meas_omega_ib_b);\n if any(any(isnan(P_matrix))) || any(any(isinf(P_matrix)))\n disp('Filter instability detected. Time to kick the bucket.');\n fprintf('Died on iteration %d/%d\\n',i,length(filter_time));\n fprintf('and GNSS epoch %d/%d\\n',GNSS_epoch,size(gps,1));\n return\n end\n\n % Run adaptive algorithm\n [Q_matrix] = adapt_noise_covariance(Phi_matrix, P_matrix_new, P_matrix, Q_matrix, ...\n LC_KF_config.n, GNSS_epoch, corrections);\n P_matrix = P_matrix_new;\n \n % Generate IMU bias and clock output records\n out_IMU_bias_est(GNSS_epoch,1) = time;\n out_IMU_bias_est(GNSS_epoch,2:7) = est_IMU_bias';\n\n % Generate KF uncertainty output record\n out_KF_SD(GNSS_epoch,1) = time;\n for n = 1:15\n out_KF_SD(GNSS_epoch,n+1) = sqrt(P_matrix(n,n));\n end % for i\n for n = 1:6\n out_R_matrix(GNSS_epoch,n) = sqrt(abs(R_matrix(n,n)));\n end % for i\n for n = 1:15\n out_Q_matrix(GNSS_epoch,n) = sqrt(abs(Q_matrix(n,n)));\n end % for i\n last_GNSS_epoch = GNSS_epoch;\n GNSS_epoch = GNSS_epoch + 1;\n end % if time \n \n % Convert navigation solution to NED\n [~,~,~,~,est_C_b_n] =...\n ECEF_to_NED(est_r_eb_e,est_v_eb_e,est_C_b_e);\n\n % Generate output profile record\n out_profile(i,1) = time;\n out_profile(i,2:4) = est_r_eb_e;\n out_profile(i,5:7) = est_v_eb_e';\n out_profile(i,8:10) = CTM_to_Euler(est_C_b_n')';\n \n % Reset old values\n old_est_r_eb_e = est_r_eb_e;\n old_est_v_eb_e = est_v_eb_e;\n old_est_C_b_e = est_C_b_e;\n last_imu_index = imu_range_end;\nend %epoch\n\n% Ends", "meta": {"author": "awerries", "repo": "kalman-localization", "sha": "558ca7fae1779aa71da61ec4829299bbbdbf62ff", "save_path": "github-repos/MATLAB/awerries-kalman-localization", "path": "github-repos/MATLAB/awerries-kalman-localization/kalman-localization-558ca7fae1779aa71da61ec4829299bbbdbf62ff/MATLAB/Loosely_coupled_INS_GNSS.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.6548947155710233, "lm_q1q2_score": 0.5443111899260058}} {"text": "function result = make_epochs_per_sample(weights)\n%MAKE_EPOCHS_PER_SAMPLE Given a set of weights generate the number of\n% epochs per sample for each weight.\n%\n% result = MAKE_EPOCHS_PER_SAMPLE(weights)\n%\n% Parameters\n% ----------\n% weights: array of size (n_1_simplices, 1)\n% The weights of how much we wish to sample each 1-simplex.\n%\n% Note that the total number of epochs does not impact this result.\n% \n% Returns\n% -------\n% result: array of size (n_1_simplices, 1)\n% The number of epochs per sample, one for each 1-simplex.\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\nresult = -1*ones(size(weights, 1), 1);\nL = weights > 0;\nresult(L) = max(weights)*ones(sum(L), 1)./weights(L);", "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/make_epochs_per_sample.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891130942472, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.5442257877152381}} {"text": "function [ySqrtPred,PInvSqrtPred,RwPred,RwxPred]=ESRIFDiscPred(ySqrtPrev,PInvSqrtPrev,f,FJacob,SQ,u,Gamma)\n%%ESRIFDISCPRED Perform the discrete-time prediction step that comes with\n% the extended square root information filter with additive\n% process noise.\n%\n%INPUTS: ySqrtPrev The xDimX1 square root information state that is to be\n% propagated. The previous information state is always\n% PInvSqrtPrev times the previous target state estimate.\n% PInvSqrtPrev The previous inverse square root information matrix.\n% If P is the covariance matrix of a Gaussian state x,\n% then P=PSqrt*PSqrt' and PInvSqrtPrev=inv(PSqrt). This\n% can be either upper triangular or lower triangular.\n% f A function handle for the state transition function\n% that takes the state as its parameter.\n% FJacob A function handle for calculating the xDim X xDim state\n% transition matrix. If an empty matrix is passed, then\n% FJacob will be found using numerical differentiation \n% via the numDiff function with default parameters.\n% SQ The lower-triangular square root of the process noise\n% covariance matrix. In the standard linear dynamic\n% model, one has\n% x(k)=F(k-1)*x(k-1)+u(k-1)+noise where x is the state\n% and Q is the covariance matrix of the noise. However,\n% if the covariance matrix of the noise in such equation\n% is singular, then one should rewrite it as\n% x(k)=F(k-1)*x(k-1)+u(k-1)+Gamma*noise\n% where gamma is some matrix and the covariance matrix of\n% the untransformed noise is not singular. This SQ is the\n% lower triangular square root of the noise in the linear\n% dynamic equation.\n% u An optional xDim X1 vector that is the control input.\n% If omitted, a zero control input (no control input) is\n% used.\n% Gamma An optional matrix that transforms the process noise\n% to the state domain if the process noise covariance\n% matrix is singular, as disccused for the input SQ. If\n% this is omitted an identity matrix is used (i.e. there\n% is no Gamma).\n%\n%OUTPUTS:ySqrtPred The xDim X 1 predicted square root information state\n% vector.\n% PInvSqrtPred The predicted xDim X xDim inverse square root state\n% covariance matrix, which is upper-triangular.\n% RwPred,RwxPred Noise matrices which can be saved for use in smoothing\n%\n%The time prediction step is taken from the algorithmic implementation\n%of [1] described in chapters V and VI.\n%\n%Given a Gaussian predicted state with mean x and covariance matrix P, the\n%square root information state is\n%ySqrt=PInvSqrt*x\n%where\n%PSqrt=inv(PInvSqrt)\n%and\n%P=PSqrt*PSqrt';\n%The matrix PInvSqrtPred can be upper or lower triangular, when supplied to\n%this function. For example, a lower-triangular matrix can be obtained\n%using PInvSqrt=inv(chol(P,'lower')). However, the output of this function,\n%PInvSqrtUpdate is always upper triangular.\n%\n%REFERENCES:\n%[1] G. J. Bierman, \"Factorization Methods for Discrete Sequential\n% Estimation. Academic Press, New York, 1977.\n%\n%February 2015 David Karnick, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nxDim=size(ySqrtPrev,1);\nif(nargin<6||isempty(u))\n u=zeros(xDim,1); \nend\nif(nargin<7||isempty(Gamma))\n Gamma=eye(xDim);\nend\nif(isempty(FJacob))\n FJacob=@(x)numDiff(x,f,xDim);\nend\n\nxPrev=PInvSqrtPrev\\ySqrtPrev;\n\nF=FJacob(xPrev);\nPInvSqrtTilde=PInvSqrtPrev/F;\n\n%The mapping matrix found on p.121 of Bierman\nA=[inv(SQ), zeros(xDim,xDim), SQ\\u;\n -PInvSqrtTilde*Gamma, PInvSqrtTilde, ySqrtPrev];\n[~,T] = qr(A);\n\nPInvSqrtPred=T((xDim+1):end,(end-xDim):(end-1));\n\n%Since f may be nonlinear, the information state output described in\n%Bierman is not valid, and the predicted state should be calculated\n%independently.\nySqrtPred=PInvSqrtPred*f(xPrev);\n\nif(nargout>2)\n RwPred=T(1:xDim,1:xDim);\n RwxPred=T(1:xDim,xDim+1:end-1);\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_Estimation/State_Propagation/Discrete_Time/ESRIFDiscPred.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034369, "lm_q2_score": 0.6513548511303338, "lm_q1q2_score": 0.5441962549318539}} {"text": "function S = xval_SVM(varargin)\n% SVM for repeated-measures (within-person) classification, with repeated cross-val and nested cross-val options\n%\n% :Usage:\n% ::\n%\n% S = xval_SVM(X, Y, id, varargin)\n%\n% Steps and features:\n% -------------------------------------------------------------------------\n% - Select holdout sets, keeping images from the same id together and stratifying on the outcome to be predicted\n% - Fit overall model and get \"sanity check\" accuracy\n% - Cross-validation with standard a priori hyperparameter choices\n% - Plot scores and ROC curves\n% - Nested cross-val with hyperparameter optimization [optional]\n% * Estimate model performance accounting for search across hyperparams\n% * Updates S.yfit, S.dist_from_hyperplane_xval, S.class_probability_xval\n% * Updates crossval_accuracy, Y_within_id, scores_within_id, scorediff, crossval_accuracy_within, classification_d\n% * Retrain to obtain estimate of best hyperparameters for future testing (update S.modeloptions)\n% - Repeat cross-validation of optimized model with different random splits [optional]\n% - Fit model on full dataset with final hyperparameters to get predictor weights (betas, b)\n% - Bootstrap model parameter estimates (w) and get P-values, FDR-corrected significant features\n% - Print output and text compatible with report-generation\n%\n% Notes:\n% -------------------------------------------------------------------------\n% - Uses Matlab's Stats/ML Toolbox SVM object, fitcsvm, and hyperparameter\n% optimization. Other options, e.g., fitclinear, may be better for some\n% situations (large num. variables)\n%\n% - Single-interval accuracy from cross-val and ROC_plot may differ because\n% ROC_plot chooses a new score threshold that maximizes overall balanced\n% accuracy. Forced-choice accuracy should be identical.\n%\n% Optimizing hyperparameters: \n% HyperparameterOptimizationOptions include defaults of:\n% - 5-fold CV (not grouped by id) without repartitioning \n% - Bayesian optimization, using best estimates from smooth function\n% - maximizes accuracy, so may need large(ish) samples to be effective.\n%\n% - works on linear classifiers only, but can explore nonlinear models\n% with a small change in the code (now commented out). This could be added\n% as an optional flag as well.\n%\n% - If optimizing hyperparameters AND repeating cross-validation, accuracy\n% estimates will use nested cross-validation, and can take a long time to run\n%\n%\n% Class probability estimates: \n% - crossval returns cross-validated yfit (class predictions), scores (dist_from_hyperplane_xval),\n% class_probability_xval. Scores and class probabilties will diverge (may\n% not be perfectly correlated) because the sigmoid scaling (Platt scaling) varies across folds.\n% They will diverge more if there is no true signal.\n%\n% ..\n% Author and copyright information:\n%\n% Copyright (C) 2020 Tor Wager\n%\n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n% ..\n%\n% :Inputs:\n%\n% **X:**\n% obs x variables numeric matrix of predictors\n%\n% **Y:**\n% obs x 1 numeric vector of outcomes, effects-coded (1, -1)\n%\n% **id:**\n% obs x 1 numeric vector of grouping codes, e.g., for participants\n% all obs from each group will be included together in a training or test set\n% if no grouping, use integers 1...n images or leave empty\n%\n% :Optional Inputs:\n% **'doplot', [logical flag]:**\n% Create plots; default = true. 'noplot' to turn off.\n%\n% **'doverbose', [logical flag]:**\n% Verbose output; default = true. 'noverbose' to turn off.\n%\n% **'dooptimize', [logical flag]:**\n% Optimize hyperparameters; default = true. 'nooptimize' to turn off.\n%\n% **'doprepeats', [num repeats]:**\n% Repeat cross-val with different partitions; default = 10.\n% Enter number of repeats, 'norepeats' to turn off.\n%\n% **'modeloptions', [modeloptions cell]:**\n% Options for model structure and hyperparameters\n% Cell array of keyword-value pairs, as specified in fitcsvm (Matlab Stats/ML toolbox)\n% Default: {'KernelFunction', 'linear'}\n% \n% **'nfolds', [num folds]:**\n% Set number of cross-validation folds; default = 10.\n% Enter number of folds.\n%\n% :Outputs:\n%\n% **S:**\n% Structure with model output\n% of them (partially consistent with this function).\n% Y: Actual (obs) outcome - should be 1, -1 for SVM analysis\n% yfit: Predicted outcome - should be 1, -1 for SVM analysis\n% Cross-validated, so can be used as series\n% of predicted values based on brain\n% measures (very useful!)\n% id: Grouping variable for within-participant observations\n% accfun: Function handle to get accuracy (single-interval)\n% w: Model weights/betas, weights on input variables\n% nfolds: Number of folds in holdout set\n% cvpartition: Object with information about training/test sets\n% teIdx: Testing IDs for each fold (holdout set)\n% trIdx: Training IDs for each fold (holdout set)\n% dist_from_hyperplane_xval: Cross-validated distance perpendicular to class boundary\n% higher = stronger prediction in favor of Class 1, lower = in favor of class -1.\n% Useful! use as continuous measure of\n% observation scores. Can calculate\n% effect sizes from this, for example.\n% class_probability_xval: Cross-validated distance expressed as probabilities of Class 1, using Platt scaling\n% crossval_accuracy: Cross-validated accuracy (input options; no hyperparam opt)\n% classification_d_singleinterval: Classification effect size (input options; no hyperparam opt)\n%crossval_accuracy_opt_hyperparams: Cross-validated accuracy with optimized hyper-parameters\n% Y_within_id: Outcomes arranged by id, for within-person comparisons\n% scores_within_id: SVM scores arranged by id, for within-person comparisons\n% scorediff: Within-person SVM scores arranged by id, for within-person comparisons\n% crossval_accuracy_within: Within-person cross-validated accuracy (input options; no hyperparam opt)\n% classification_d_within: Within-person classification effect size (input options; no hyperparam opt)\n% S.boot_w_ste: Bootstrapped standard errors of model weights (feature-level)\n% S.boot_w_mean: Bootstrapped mean model weights (feature-level)\n% S.wZ: Bootstrapped Z-scores of model weights (feature-level)\n% S.wP: Bootstrapped P-values for individual model weights (feature-level)\n% S.wP_fdr_thr: P-value threshold for FDR q < 0.05\n% S.boot_w_fdrsig: Logical vector for which weights are significant with FDR\n% S.w_thresh_fdr: Thresholded weights at FDR q < 0.05 based on bootstrapping (feature-level)\n% S.SVMModel: ClasssificationSVM model object trained on full dataset, final chosen parameter set; for predicting in subsequent validation samples.\n% Y-hat = (X/s)'* w + b\n% ClassificationSVM objects store w, b, and s in the properties Beta, Bias, and KernelParameters.Scale, respectively.\n%\n% :Examples:\n% ::\n%\n% Simulate some data with true signal, with two observations per person\n% -------------------------------------------------------------------------\n% n = 50; % participants\n% k = 120; % features\n% true_sig = [repmat(randn(1, k), n, 1); repmat(randn(1, k), n, 1)]; % First n are Class 1, second n are Class 2\n% noise = 10 * randn(2 * n, k); % Noise var >> true signal var\n% X = true_sig + noise; % Predictors\n% Y = [ones(n, 1); -ones(n, 1)]; % Outcome to classify, coded [1 -1]\n% id = [(1:n)'; (1:n)']; % Grouping ID codes for participants\n%\n% S = xval_SVM(X, Y, id, 'nooptimize', 'norepeats', 'nobootstrap'); % Fastest for quick cross-validated performance\n% S = xval_SVM(X, Y, id, 'nooptimize', 'norepeats', 'nboot', 100); % Very quick test of bootstrapping with few samples (not for final models)\n% S = xval_SVM(X, Y, id, 'nooptimize', 'dorepeats', 5, 'nobootstrap'); % Quick test of repeated cross-val, 5x\n% S = xval_SVM(X, Y, id, 'nooptimize', 'nobootstrap'); % Repeat cross-val only\n% S = xval_SVM(X, Y, id, 'norepeats', 'nobootstrap'); % Optimize with nested cross-val only\n% S = xval_SVM(X, Y, id); % Optimize, repeat with optimal model, bootstrap\n%\n% S = xval_SVM(X, Y, id, 'nooptimize', 'norepeats', 'nobootstrap', 'noverbose', 'noplot'); % Returns only the output S\n%\n% Train the same model without within-person observations (i.e., 1 observation per id):\n% This does single-interval classification only\n% \n% S = xval_SVM(X, Y, (1:length(Y))', 'norepeats', 'nobootstrap');\n%\n% :References:\n% See Mathworks functions\n%\n% :See also:\n% - fmri_data.predict, canlab_run_paired_SVM, other xval_ functions\n%\n\n% ..\n% Programmers' notes:\n% Created by Tor Wager, May 2020\n% ver 1.0 (no version number listed) - some bugs in optimization\n% Enforce [1 -1] inputs\n% ver 1.1 (Tor): fixed bugs, optimization changes and documentation, multiple small tweaks and some new plots\n% Updated to handle within-person or between-person obs only\n% ROC_plot should be at threshold 0 for single-interval\n% Get rid of plots for all folds in opt output\n% OptimizeHypParams returns point est. No need to rerun. Builds in 5-fold eval by default\n% Add ?Summary of nested cross-val accuracy with hyperparameter optimization?\n% Optim.: Allow control of verbosity and plots. No plots/verbose in nested eval.\n% Optim: use best estim, not best observed\n% Have a look at the data and add data plots. Sorted by cases\n% ver 1.2 Cosmetic documentation and look updates\n%\n% Future:\n% \n% Troubleshoot prediction vs. class probability reversals\n% % either scores or pscores appear to be inconsistent in terms of which column is class -1 and which is class 1. Check for instability in scores, and select pscores to be consistent with this on each fold.\n% Add permutation test\n% v1.3\n% Linear/nonlinear - pass in hyparams to optimize.\n% Return model weights from folds for further analysis/application\n%\n% v1.4\n% Add nfolds argument - Michael Sun, 07/07/2022\n% \n% ..\n\n%% ----------------------------------------------------------------------\n% Version\n% ----------------------------------------------------------------------\n\nver = 1.2;\n\n%% ----------------------------------------------------------------------\n% Parse inputs\n% ----------------------------------------------------------------------\n% Uses the inputParser object. Older schemes are below.\n\n% Logical flags - parse specially because they are not name-value pairs\n% Parser accepts only name/value pairs, so this code allows a workaround\n% We must remove these inputs because they will cause inputparser to error\n% ----------------------------------------------------------------------\nwh = strcmp(varargin, 'noverbose'); if any(wh), doverbose1 = false; varargin(wh) = []; end\nwh = strcmp(varargin, 'noplot'); if any(wh), doplot1 = false; varargin(wh) = []; end\nwh = strcmp(varargin, 'noplots'); if any(wh), doplot1 = false; varargin(wh) = []; end\nwh = strcmp(varargin, 'nooptimize'); if any(wh), dooptimize1 = false; varargin(wh) = []; end\nwh = strcmp(varargin, 'norepeats'); if any(wh), dorepeats1 = 0; varargin(wh) = []; end\nwh = strcmp(varargin, 'nobootstrap'); if any(wh), dobootstrap1 = 0; varargin(wh) = []; end\n\n% The handling of parsing keyword-value pairs, checking attributes, and\n% specifying default values is handled here, using Matlab's inputparser object:\nARGS = parse_inputs(varargin{:});\n\nfn = fieldnames(ARGS);\n\nfor i = 1:length(fn)\n str = sprintf('%s = ARGS.(''%s'');', fn{i}, fn{i});\n eval(str)\nend\n\n% Replace logical flags because they will be overwritten by the parser\nif exist('doverbose1', 'var'), doverbose = doverbose1; end\nif exist('doplot1', 'var'), doplot = doplot1; end\nif exist('dooptimize1', 'var'), dooptimize = dooptimize1; end\nif exist('dorepeats1', 'var'), dorepeats = dorepeats1; end\nif exist('dobootstrap1', 'var'), dobootstrap = dobootstrap1; end\nif ~exist('nfolds', 'var'), nfolds=10; end\n\nif isempty(id), id = [1:length(Y)]'; end\nif ~iscolumn(id), id = id'; end\n\n%% Select holdout sets for outer loop\n% - Keep images from the same id together\n% - Stratify on the outcome to be predicted\n% -------------------------------------------------------------------------\n\nS = struct(); % Define structure for models and output; use variable names in fmri_data.predict when possible\n\nS.Y = Y;\nS.id = id; % Subject grouping - not in fmri_data.predict\n\nS.modeloptions = modeloptions;\n\nS.accfun = @(Y, yfit) 100 .* nansum(Y == yfit) ./ sum(~isnan(Y));\n\nif doverbose\n \n dashes = '---------------------------------------------------------------------------------';\n printhdr = @(str) fprintf('%s\\n%s\\n%s\\n', dashes, str, dashes);\n \n printhdr(' ') %#ok<*UNRCH>\n printhdr(sprintf('xval_SVM ver %3.2f: Cross-validated Support Vector Machine classification', ver));\n printhdr(' ')\n \n disp(' ')\n disp(' ')\n printhdr('Selecting and analyzing cross-validation folds');\n \nend\n\n\n% Preliminary data plots\n% -------------------------------------------------------------------------\nif doplot\n prelim_data_plot(X, Y, id);\nend\n\n% Select train/test sets\n% -------------------------------------------------------------------------\n\n% [S.trIdx, S.teIdx] = xval_stratified_holdout_leave_whole_subject_out(S.Y, S.id, 'doverbose', doverbose, 'doplot', doplot);\n[S.trIdx, S.teIdx] = xval_stratified_holdout_leave_whole_subject_out(S.Y, S.id, 'doverbose', doverbose, 'doplot', doplot, 'nfolds', nfolds); % MS 6/16/2022: Crashes if you can't do 10-fold.\ndrawnow, snapnow\n\n% Fit the overall a priori model: SVM with linear kernel\n% -------------------------------------------------------------------------\nif doverbose\n \n printhdr('Model training and cross-validation without optimization')\n fprintf('Training overall model. ')\n \n SVMModel = fitcsvm(X, S.Y, S.modeloptions{:}); %#ok<*NODEF>\n \n % non-cross-val accuracy: sanity check. should usually be 100% if training is overfit and n >> p\n label = predict(SVMModel, X);\n \n acc = S.accfun(S.Y, label);\n fprintf('Accuracy without cross-val: %3.0f%%\\n', acc);\n \nend\n\n%% Cross-validation with standard a priori hyperparameter choices\n% -------------------------------------------------------------------------\nS.nfolds = length(S.trIdx);\n\n% crossval returns cross-validated yfit (class predictions), scores (dist_from_hyperplane_xval),\n% class_probability_xval. Scores and class probabilties will diverge (may\n% not be perfectly correlated) because the sigmoid scaling (Platt scaling) varies across folds.\n% They will diverge more if there is no true signal.\n\nS = crossval(S, X, doverbose);\n\n% Summarize accuracy\n% -------------------------------------------------------------------------\n% Given Y, yfit, cross-val scores (dist_from_hyperplane_xval), id\n% Update crossval_accuracy,classification_d_singleinterval\n% Y_within_id, scores_within_id, scorediff,\n% crossval_accuracy_within, classification_d_within\nS = update_accuracy_stats(S);\n\nif doverbose\n \n fprintf('Accuracy (cross-validated): Single-interval: %3.0f%%, d = %3.2f\\n', S.crossval_accuracy, S.classification_d_singleinterval);\n \n if S.mult_obs_within_person\n \n fprintf(' Forced-choice within-person: %3.0f%% d = %3.2f\\n', S.crossval_accuracy_within, S.classification_d_within);\n \n end\n \nend\n\n% Plot scores and ROC curves\n% -------------------------------------------------------------------------\nif doplot\n \n plot_scores_and_ROC(S);\n \n xval_plot_scores_vs_class_probability(S);\n \nend\n\n%% Nested cross-val with hyperparameter optimization\n% -------------------------------------------------------------------------\n\nif dooptimize\n \n if doverbose\n printhdr('Optimizing hyperparameters using nested cross-validation');\n end\n \n % Nested cross-validation (updates S.yfit, S.dist_from_hyperplane_xval,\n % S.class_probability_xval)\n % Estimate model performance accounting for search across hyperparams\n % ---------------------------------------------------------------------\n % Updates S.yfit, S.dist_from_hyperplane_xval, S.class_probability_xval\n S = crossval_nested(S, X, doverbose);\n \n % Given Y, yfit, cross-val scores (dist_from_hyperplane_xval), id\n % Update crossval_accuracy, Y_within_id, scores_within_id, scorediff, crossval_accuracy_within, classification_d\n S = update_accuracy_stats(S);\n \n % Retrain to obtain estimate of best hyperparameters for future testing (update S.modeloptions)\n % ---------------------------------------------------------------------\n % Modal parameters across folds is not\n % the best way to get the final hyperparameters. Instead, the model should\n % be re-fit using single cross-validation with all hparam options pick the\n % best relative model. Nested cross-val will estimate the accuracy of the\n % whole procedure, including the hparam search, but not return the final best\n % parameters.\n hparams_to_optimize = 'all'; % {'BoxConstraint' 'Standardize'}\n Mdl = fitcsvm(X, S.Y,...\n 'OptimizeHyperparameters', hparams_to_optimize, 'HyperparameterOptimizationOptions',...\n struct('AcquisitionFunctionName','expected-improvement-plus', 'Verbose', double(doverbose), 'ShowPlots', double(doplot))); %#ok<*IDISVAR>\n \n % Notes:\n % - Extract hyperparameter choices in a format that we can pass back in\n % to train or test a new model.\n % - We could use the best observed point, but it's preferred to use the\n % best estimated values from a smooth model fit to observed samples.\n \n best_modeloptions = convert_hyperparameter_choices_to_cell(Mdl, []); % optimizing \"all\"\n % best_modeloptions = convert_hyperparameter_choices_to_cell(Mdl, S.modeloptions); % optimizing \"linear\" : ms 06242022 Changed default settings to not optimize\n\n S.modeloptions = best_modeloptions;\n\n \n % Summarize accuracy\n % -------------------------------------------------------------------------\n \n if doverbose\n \n disp('Summary of nested cross-val accuracy with hyperparameter optimization')\n disp(' ')\n \n disp('Optimized hyperparameters for each fold')\n disp(S.hyperparams_by_fold)\n \n disp(' ')\n disp('Best options, stored in S.modeloptions:');\n \n disp(best_modeloptions)\n \n fprintf('Accuracy (nested cross-validation): Single-interval: %3.0f%%, d = %3.2f\\n', S.crossval_accuracy, S.classification_d_singleinterval);\n \n if S.mult_obs_within_person\n \n fprintf(' Forced-choice within-person: %3.0f%% d = %3.2f\\n', S.crossval_accuracy_within, S.classification_d_within);\n \n end\n \n end\n \n % Plot scores and ROC curves\n % -------------------------------------------------------------------------\n if doplot\n \n plot_scores_and_ROC(S, 'Cross-validated SVM scores with hyperparameter optimization');\n \n end\n \n \nend % do optimize\n\n%% Repeat cross-validation of optimized model, if specified\n% - if hyperparams optimized, then use \"consensus params\" for repeats\n% - these are stored in S.modeloptions now, so will be used\n% - If optimizing, re-do the first accuracy with the optimized\n% hyperparameters\n% -------------------------------------------------------------------------\nif dorepeats > 1\n \n if doverbose\n disp(' ')\n fprintf('Repeating cross-val %d times. ', dorepeats)\n end\n \n % if dooptimize, startat = 1; else, startat = 2; end\n startat = 2;\n \n for i = startat:dorepeats % do remainder of repeats without verbose.\n \n if doverbose, fprintf('%d ', i), end\n \n\n Sr = S;\n \n % Get new cvpartition (or outer loop if optimizing) \n% [Sr.trIdx, Sr.teIdx] = xval_stratified_holdout_leave_whole_subject_out(Sr.Y, Sr.id, 'doverbose', false, 'doplot', false);\n [Sr.trIdx, Sr.teIdx] = xval_stratified_holdout_leave_whole_subject_out(Sr.Y, Sr.id, 'doverbose', false, 'doplot', false, 'nfolds', nfolds); % MS 6/16/2022 add nfold option, otherwise default nfold=10 will cause this to crash if there are fewer than 10 possible folds.\n \n if dooptimize\n % If optimizing, repeat nested xval procedure\n % This can take a long time!\n \n Sr = crossval_nested(Sr, X, doverbose);\n \n else\n \n % Cross-validate\n Sr = crossval(Sr, X, false);\n \n end\n \n % Save accuracy\n % -------------------------------------------------------------------------\n % Given Y, yfit, cross-val scores (dist_from_hyperplane_xval), id\n % Update crossval_accuracy,classification_d_singleinterval\n % Y_within_id, scores_within_id, scorediff,\n % crossval_accuracy_within, classification_d_within\n \n Sr = update_accuracy_stats(Sr);\n\n S.crossval_accuracy(i) = Sr.crossval_accuracy; % Sr.accfun(Sr.Y, Sr.yfit);\n S.classification_d_singleinterval(i) = Sr.classification_d_singleinterval;\n \n if S.mult_obs_within_person\n \n S.crossval_accuracy_within(i) = Sr.crossval_accuracy_within; % Sr.accfun(Sr.Y, Sr.yfit);\n S.classification_d_within(i) = Sr.classification_d_within;\n\n end\n \n end\n \n if doverbose\n \n fprintf('Done!\\n')\n \n fprintf('CV single-interval accuracy across %d reps, mean = %3.0f%%, std = %3.0f%%, min = %3.0f%%, max = %3.0f%%\\n', dorepeats, ...\n mean(S.crossval_accuracy), std(S.crossval_accuracy), min(S.crossval_accuracy), max(S.crossval_accuracy));\n \n disp('Performance metrics saved in S.crossval_accuracy, classification_d_singleinterval')\n \n if S.mult_obs_within_person\n \n fprintf('\\nCV forced_choice accuracy across %d reps, mean = %3.0f%%, std = %3.0f%%, min = %3.0f%%, max = %3.0f%%\\n', dorepeats, ...\n mean(S.crossval_accuracy_within), std(S.crossval_accuracy_within), min(S.crossval_accuracy_within), max(S.crossval_accuracy_within));\n \n disp('Performance metrics saved in S.crossval_accuracy_within, classification_d_within')\n \n end\n \n \n disp(' ')\n \n end\n \nend\n\n%% Fit model on full dataset with selected options (final model if optimizing hyperparams) to get betas\n\nS.SVMModel = fitcsvm(X, S.Y, S.modeloptions{:});\nS.w = S.SVMModel.Beta; % Model weights/betas\n\n% Bootstrap betas\nif dobootstrap\n \n if doverbose\n disp(' ')\n printhdr(sprintf('Bootstrapping model param estimates (b): %d samples', nboot));\n end\n \n rng('shuffle');\n \n S.boot_w = NaN .* zeros(length(S.w), nboot);\n \n for i = 1:nboot\n \n [Xb, Yb] = get_bootstrap_sample_grouped_by_id(S, X);\n \n SVMModel = fitcsvm(Xb, Yb, S.modeloptions{:});\n \n S.boot_w(:, i) = SVMModel.Beta; % Model weights/betas\n \n \n end\n \n % Inference\n % (from fmri_data.predict)\n \n S.boot_w_ste = squeeze(nanstd(S.boot_w, 0, 2)); %1/20/16 add squeeze for multiclass case\n S.boot_w_mean = squeeze(nanmean(S.boot_w, 2)); %1/20/16 add squeeze for multiclass case\n S.boot_w_ste(S.boot_w_ste == 0) = Inf; % in case unstable regression returns all zeros\n \n S.wZ = S.boot_w_mean ./ S.boot_w_ste; % tor changed from wmean; otherwise bootstrap variance in mean inc in error; Luke renamed to avoid confusion\n S.wP = 2 * (1 - normcdf(abs(S.wZ)));\n S.wP_fdr_thr = FDR(S.wP, .05);\n if isempty(S.wP_fdr_thr), S.wP_fdr_thr = -Inf; end\n \n S.boot_w_fdrsig = S.wP <= S.wP_fdr_thr; % equals because can get exact vals in some cases...\n S.w_thresh_fdr = S.w;\n S.w_thresh_fdr(~S.boot_w_fdrsig) = 0;\n \n if doverbose\n \n disp('Summary of significant individual features (two-tailed)');\n \n Threshold = [.05 .01 .001 S.wP_fdr_thr]';\n \n for i = 1:length(Threshold)\n \n Num_Sig_Features(i, 1) = sum(S.wP <= Threshold(i));\n \n end\n \n t = table(Threshold, Num_Sig_Features);\n disp(t)\n \n end\nend\n\n%%\n% permutations would go here...future project.\n% consider exchangeability issue given within-person design...winkler and\n% nichols...\n% indx = randperm(size(X, 1));\n% X = X(indx, :); Y = Y(indx); id = id(indx);\n% S = xval_SVM(X, Y, id, 'nooptimize', 'norepeats');\n\n\nend % main function\n\n\n%%\n\n\n% -------------------------------------------------------------------------\n% -------------------------------------------------------------------------\n\n% Subfunctions\n\n% -------------------------------------------------------------------------\n% -------------------------------------------------------------------------\n\nfunction S = crossval(S, X, doverbose)\n\nif doverbose, fprintf('..X-val, %d folds...', S.nfolds), end\n\nfor i = 1:S.nfolds\n \n if doverbose, fprintf('%d ', i), end\n \n % Fit to training data for this fold\n SVM_fold = fitcsvm(X(S.trIdx{i}, :), S.Y(S.trIdx{i}), S.modeloptions{:});\n \n % Apply holdout test set for this fold\n [label, score] = predict(SVM_fold, X(S.teIdx{i}, :)); % Get raw scores\n score = score(:, 2); % Decision boundary is symmetrical\n \n S.dist_from_hyperplane_xval(S.teIdx{i}, 1) = score; % Unscaled SVM scores\n \n S.yfit(S.teIdx{i}, 1) = label; % Predicted class, cross-val\n \n SVM_fold = fitPosterior(SVM_fold); % Works for fitcsvm, not fitclinear\n \n % Note:\n % either scores or pscores appear to be inconsistent in terms of which\n % column is class -1 and which is class 1. Check for instability in\n % scores, and select pscores to be consistent with this on each fold.\n if mean(label(score > 0)) < mean(label(score < 0))\n disp('WARNING!!! Scores for label 1 are < scores for label -1, scores are reversed!!! This should not happen. Check code/implementation.');\n end\n \n [~, pscore] = predict(SVM_fold, X(S.teIdx{i}, :));\n \n % which pscores correlate more positively with score? use this one.\n r = corr([score pscore]);\n [~, wh] = max(r(1, 2:3));\n \n pscore = pscore(:, wh); % Platt scaling scores (class probability)\n \n S.class_probability_xval(S.teIdx{i}, 1) = pscore;\n \n \nend\n\nif doverbose, fprintf('Done!\\n'), end\n\nend % crossval\n\n\n% -------------------------------------------------------------------------\n% Nested cross-validation to optimize hyperparameters\n% -------------------------------------------------------------------------\n\n\nfunction S = crossval_nested(S, X, doverbose)\n\nif doverbose, fprintf('..X-val, %d folds...', S.nfolds), end\n\nfor i = 1:S.nfolds\n \n if doverbose, fprintf('%d ', i), end\n \n % Optimize hyperparameters within this fold\n % -------------------------------------------\n \n % Option 1: Optimize all, including kernel (linear/nonlinear)\n % Option 2: Optimize specific hyperparameters, Slack param C\n % (BoxConstraint) and Standardize inputs, linear model only\n \n hparams_to_optimize = 'all'; % {'BoxConstraint' 'Standardize'}\n \n Mdl = fitcsvm(X(S.trIdx{i}, :), S.Y(S.trIdx{i}),...\n 'OptimizeHyperparameters', hparams_to_optimize, 'HyperparameterOptimizationOptions',...\n struct('AcquisitionFunctionName','expected-improvement-plus', 'Verbose', 0, 'ShowPlots', 0));\n \n % Notes: HyperparameterOptimizationOptions include defaults of:\n % - 5-fold CV (not grouped by id) without repartitioning \n % - Bayesian optimization, using best estimates from smooth function\n \n % Add hyperparameter results to table\n % -------------------------------------\n % Use estimated rather than observed. This uses the smooth function estimated across observations\n\n opt_hyperparam_table = Mdl.HyperparameterOptimizationResults.XAtMinEstimatedObjective; \n \n if i == 1\n S.hyperparams_by_fold = opt_hyperparam_table; % best parameters - table\n \n else\n S.hyperparams_by_fold(i, :) = opt_hyperparam_table;\n end\n \n fold_modeloptions = convert_hyperparameter_choices_to_cell(Mdl, []); % Optimizing \"all\" \n %fold_modeloptions = convert_hyperparameter_choices_to_cell(Mdl, S.modeloptions); % Optimizing \"linear\"\n \n S.fold_modeloptions{i} = fold_modeloptions;\n \n % Fit to training data for this fold\n SVM_fold = fitcsvm(X(S.trIdx{i}, :), S.Y(S.trIdx{i}), fold_modeloptions{:});\n \n % Updates S.yfit, S. S.dist_from_hyperplane_xval, S.class_probability_xval\n \n % Apply holdout test set for this fold\n [label, score] = predict(SVM_fold, X(S.teIdx{i}, :)); % Get raw scores\n score = score(:, 2); % Decision boundary is symmetrical\n \n S.dist_from_hyperplane_xval(S.teIdx{i}, 1) = score; % Unscaled SVM scores\n \n S.yfit(S.teIdx{i}, 1) = label; % Predicted class, cross-val\n \n SVM_fold = fitPosterior(SVM_fold); % Works for fitcsvm, not fitclinear\n \n [~, pscore] = predict(SVM_fold, X(S.teIdx{i}, :));\n pscore = pscore(:, 2); % Platt scaling scores (class probability)\n \n S.class_probability_xval(S.teIdx{i}, 1) = pscore;\n \nend\n\nif doverbose, fprintf('Done!\\n'), end\n\nend % crossval\n\n\n\n% -------------------------------------------------------------------------\n% Get scores\n% -------------------------------------------------------------------------\n\n\nfunction [scores_within_id, scorediff, d] = get_scores_within_id(S, varname)\n\nmyvar = S.(varname);\nu = unique(S.id);\n\nfor i = 1:length(u)\n \n wh_id = S.id == u(i) & S.Y == -1;\n scores_within_id(i, 1) = nanmean(myvar(wh_id));\n \n wh_id = S.id == u(i) & S.Y == 1;\n scores_within_id(i, 2) = nanmean(myvar(wh_id));\n \nend\n\nscorediff = diff(scores_within_id')';\nd = nanmean(scorediff) ./ nanstd(scorediff);\n\nend %get scores\n\n\n% -------------------------------------------------------------------------\n% bootstrapping\n% -------------------------------------------------------------------------\n\n\nfunction [Xb, Yb] = get_bootstrap_sample_grouped_by_id(S, X)\n% Given X, S.Y, S.id, return a bootstrap sample, keeping all obs from an id together\n\nu = unique(S.id);\nn = length(u);\n\nwh = ceil(rand(n, 1) * n); % Bootstrap sample of p ids, with replacement\n\n[Xboot, Yboot] = deal(cell(n, 1));\n\nfor j = 1:n % add obs, allowing repeats\n \n wh_obs = ismember(S.id, u(wh(j)));\n \n Xboot{j} = X(wh_obs, :);\n Yboot{j} = S.Y(wh_obs);\n \nend\n\nXb = cat(1, Xboot{:});\nYb = cat(1, Yboot{:});\n\nend % function\n\n\n% -------------------------------------------------------------------------\n% optimized hyperparameter aggregation\n% -------------------------------------------------------------------------\n\nfunction best_modeloptions = convert_hyperparameter_choices_to_cell(Mdl, other_modeloptions)\n% Notes:\n% - Extract hyperparameter choices in a format that we can pass back in\n% to train or test a new model.\n% - We could use the best observed point, but it's preferred to use the\n% best estimated values from a smooth model fit to observed samples.\n\n% opt_hyperparam_table = Mdl.HyperparameterOptimizationResults.XAtMinObjective;\nopt_hyperparam_table = Mdl.HyperparameterOptimizationResults.XAtMinEstimatedObjective;\n\nbest_modeloptions = other_modeloptions;\n\n% Add optimal choices to the option set\nfor j = 1:size(opt_hyperparam_table, 2)\n vname = opt_hyperparam_table.Properties.VariableNames{j};\n \n paramval = opt_hyperparam_table.(vname)(1);\n \n % fix: categorical Standardize to text.\n % Leave KernelFunction as string\n if iscategorical(paramval) && strcmp(vname, 'Standardize')\n paramval = char(string(paramval));\n paramval = strcmp(paramval, 'true');\n elseif iscategorical(paramval)\n % For KernelFunction\n paramval = char(paramval);\n end\n \n % Get rid of NaN options passed back out from optimize 'all'\n if ~isnan(paramval)\n best_modeloptions{end + 1} = vname;\n best_modeloptions{end + 1} = paramval; %#ok<*AGROW>\n end\n \nend\n\nend\n \n% function best_modeloptions = get_modal_params_across_folds(S)\n% \n% % This function is deprecated because modal parameters across folds is not\n% % the best way to get the final hyperparameters. Instead, the model should\n% % be re-fit using single cross-validation with all hparam options pick the \n% % best relative model. Nested cross-val will estimate the accuracy of the\n% % whole procedure, including the hparam search, but not return the final best\n% % parameters.\n% \n% hbyfold = cat(1, S.fold_modeloptions{:});\n% best_modeloptions = {};\n% \n% for i = 1:size(hbyfold, 2)\n% \n% mydat = cat(1, hbyfold{:, i});\n% \n% if ischar(mydat) || iscategorical(mydat) || islogical(mydat)\n% \n% best_modeloptions{1, i} = mode(mydat);\n% \n% elseif isnumeric(mydat)\n% \n% best_modeloptions{1, i} = trimmean(mydat, 80);\n% \n% else\n% error('Unknown model option class! Extend this code.')\n% \n% end\n% \n% end\n% \n% end\n\n\n% -------------------------------------------------------------------------\n% accuracy\n% -------------------------------------------------------------------------\n\n\n\nfunction S = update_accuracy_stats(S)\n\nS.crossval_accuracy = S.accfun(S.Y, S.yfit);\n\ns1 = S.dist_from_hyperplane_xval(S.Y == 1);\ns2 = S.dist_from_hyperplane_xval(S.Y == -1);\n\n% d = difference / std pooled within, weighted by sample size\nS.classification_d_singleinterval = (mean(s1) - mean(s2)) ./ sqrt( ( var(s1) .* length(s1) + var(s2) .* length(s2) ) ./ (length(s1) + length(s2)) );\n\n% Do we have multiple obs within-person? If so return within-person stats\nS.mult_obs_within_person = length(S.id) > length(unique(S.id));\n\nif S.mult_obs_within_person\n \n varname = 'dist_from_hyperplane_xval';\n [scores_within_id, scorediff, d] = get_scores_within_id(S, varname);\n \n S.Y_within_id = get_scores_within_id(S, 'Y');\n \n S.scores_within_id = scores_within_id;\n S.scorediff = scorediff;\n S.crossval_accuracy_within = 100 * sum(scorediff > 0) ./ sum(~isnan(scorediff));\n S.classification_d_within = d;\n \nend\n\nend\n\n\n% -------------------------------------------------------------------------\n% plots\n% -------------------------------------------------------------------------\n\n\n\nfunction prelim_data_plot(X, Y, id)\n\ncreate_figure('Data view', 1, 3);\nimagesc(X); colorbar;\nxlabel('Input features'); ylabel('Observation'); title('Predictor matrix (X)');\naxis tight; set(gca, 'YDir', 'reverse');\n\nsubplot(1, 3, 2);\nimagesc([Y scale(id)]);\naxis tight; set(gca, 'YDir', 'reverse');\nset(gca, 'XTick', [1 2], 'XTickLabel', {'Y' 'id'});\ntitle('Outcome (Y) and id');\n\nsubplot(1, 3, 3);\nr = corr(X');\n[~, wh] = sort(Y);\nimagesc(r(wh, wh));\nn1 = sum(Y == -1);\nn2 = sum(Y == 1);\n\nh1 = drawbox(0, n1, 0, n1, 'k');\nset(h1, 'FaceColor', 'none', 'EdgeColor', 'r', 'LineWidth', 2);\n\nh1 = drawbox(n1, n2, n1, n2, 'k');\nset(h1, 'FaceColor', 'none', 'EdgeColor', 'r', 'LineWidth', 2);\n\naxis tight; set(gca, 'YDir', 'reverse');\n% set(gca, 'XTick', [1 2], 'XTickLabel', {'Y' 'id'});\ntitle('Inter-obs correlations sorted by Y [-1, 1]');\n\ncolorbar\n\ncm = colormap_tor([0 0 1], [1 0 0], [1 1 1]);\ncolormap(cm)\nset(gca, 'CLim', [-1 1])\n\ndrawnow, snapnow\nend\n\n\n\nfunction plot_scores_and_ROC(S, varargin)\n% plot_scores_and_ROC(S, varargin) -> varargin = new title\n\ncreate_figure('cross-val accuracy', 2, 2);\nsubplot(2, 2, 1); delete(gca); subplot(2, 2, 2); delete(gca);\naxes('Position', [.13 .58 .77 .35]);\nset(gca, 'FontSize', 16)\nhold on\n\nif S.mult_obs_within_person\n % Within-person scores\n \n n = size(S.scores_within_id, 1);\n x = [1:n; 1:n];\n plot(x(:, S.scorediff > 0), S.scores_within_id(S.scorediff > 0, :)', 'Color', [.3 .3 .3], 'LineWidth', 1);\n plot(x(:, S.scorediff < 0), S.scores_within_id(S.scorediff < 0, :)', 'r', 'LineWidth', 1);\n \n plot(x(1, :), S.scores_within_id(:, 1)', '^', 'Color', [.3 .5 1] / 2, 'MarkerFaceColor', [.3 .5 1], 'LineWidth', 1);\n plot(x(2, :), S.scores_within_id(:, 2)', 'v', 'Color', [1 .5 0] / 2, 'MarkerFaceColor', [1 .5 0], 'LineWidth', 1);\n \n xlabel(sprintf('ID, %3.0f%% single-interval acc, %3.0f%% forced-choice', S.crossval_accuracy, S.crossval_accuracy_within));\n \n disp('Black lines: Correct, Red lines: Errors. Red triangles: Scores for Class 1, Blue triangles: Scores for Class -1');\n \nelse\n \n % Scores, all between-person\n \n n = size(S.dist_from_hyperplane_xval, 1);\n x = 1:n;\n iscorrect = sign(S.dist_from_hyperplane_xval) == sign(S.Y);\n \n %plot(x(:, iscorrect), S.dist_from_hyperplane_xval(iscorrect, :)', 'o', 'MarkerSize', 10, 'Color', [.3 .3 .3], 'LineWidth', 1);\n plot(x(:, ~iscorrect), S.dist_from_hyperplane_xval(~iscorrect, :)', 'o', 'MarkerSize', 10, 'Color', [1 0 0], 'LineWidth', 1);\n \n h = plot_horizontal_line(0); set(h, 'LineStyle', '--');\n \n color1 = [.2 .8 .2];\n color2 = [.3 .3 1];\n \n plot(x(:, S.Y == 1), S.dist_from_hyperplane_xval(S.Y == 1, :)', 'v', 'MarkerSize', 6, 'Color', color1, 'MarkerFaceColor', color1, 'LineWidth', 1);\n plot(x(:, S.Y == -1), S.dist_from_hyperplane_xval(S.Y == -1, :)', '^', 'MarkerSize', 6, 'Color', color2, 'MarkerFaceColor', color2, 'LineWidth', 1);\n \n xlabel(sprintf('ID, %3.0f%% single-interval acc', S.crossval_accuracy));\n \n disp('Red cicles: Errors. Green triangles: Scores for Class 1, Blue triangles: Scores for Class -1');\n \n axis tight\n \nend\n\nylabel('SVM Score');\n\ntitle('Cross-validated SVM scores (no hyperparameter optimization)');\nif ~isempty(varargin), title(varargin{1}); end\n\n\n% ROC plot\nsubplot(2, 2, 3);\nS.ROC_single_interval = roc_plot(S.dist_from_hyperplane_xval, logical(S.Y > 0), 'color', [.4 .4 .7], 'threshold', 0);\ntitle('Single-interval ROC')\nset(gca, 'FontSize', 16)\n\nsubplot(2, 2, 4);\n\nif S.mult_obs_within_person\n \n % Paired forced-choice. Get complete cases - Remove NaNs id-wise\n outcomes = S.Y_within_id;\n scores = S.scores_within_id;\n [~, outcomes, scores] = nanremove(outcomes, scores);\n \n S.ROC_forced_choice = roc_plot(scores(:), logical(outcomes(:) > 0), 'color', [.4 .4 .7], 'twochoice');\n title('Forced-choice ROC')\n set(gca, 'FontSize', 16)\n \nelse\n % Scores, all between-person\n \n plot(S.Y(~iscorrect), S.dist_from_hyperplane_xval(~iscorrect, :)', 'o', 'MarkerSize', 10, 'Color', [1 0 0], 'LineWidth', 1);\n \n h = plot_horizontal_line(0); set(h, 'LineStyle', '--');\n \n color1 = [.2 .8 .2];\n color2 = [.3 .3 1];\n \n plot(ones(1, sum(S.Y == 1)), S.dist_from_hyperplane_xval(S.Y == 1, :)', 'v', 'MarkerSize', 6, 'Color', color1, 'MarkerFaceColor', color1, 'LineWidth', 1);\n plot(-ones(1, sum(S.Y == -1)), S.dist_from_hyperplane_xval(S.Y == -1, :)', '^', 'MarkerSize', 6, 'Color', color2, 'MarkerFaceColor', color2, 'LineWidth', 1);\n \n set(gca, 'XTick', [-1 1], 'XLim', [-1.5 1.5]);\n xlabel('True class');\n ylabel('Predicted class')\n \nend\n\ndrawnow, snapnow\n\nend\n\n\n\nfunction xval_plot_scores_vs_class_probability(S)\n\n% crossval returns cross-validated yfit (class predictions), scores (dist_from_hyperplane_xval),\n% class_probability_xval. Scores and class probabilties will diverge (may\n% not be perfectly correlated) because the sigmoid scaling (Platt scaling) varies across folds.\n% They will diverge more if there is no true signal.\n\ncreate_figure('xval scores vs. class probability estimates', 1, 2); \n\nplot(S.dist_from_hyperplane_xval, S.class_probability_xval, 'o');\n\nfor j = 1:length(S.teIdx)\n \n plot(S.dist_from_hyperplane_xval(S.teIdx{j}), S.class_probability_xval(S.teIdx{j}), 'o', 'MarkerFaceColor', rand(1, 3));\n\nend\n\nxlabel('Cross-validated SVM scores (colors are folds)');\nylabel('Cross-validated class prob estimates');\n\nhh = plot_vertical_line(0); set(hh, 'LineStyle', '--');\nhh = plot_horizontal_line(.5); set(hh, 'LineStyle', '--');\n\nsubplot(1, 2, 2)\n\nlineh = plot(S.dist_from_hyperplane_xval(S.Y == 1), S.class_probability_xval(S.Y == 1), 'v', 'MarkerFaceColor', [.2 .8 .2]);\nlineh = [lineh plot(S.dist_from_hyperplane_xval(S.Y == -1), S.class_probability_xval(S.Y == -1), '^', 'MarkerFaceColor', [.2 .2 1])];\n\nxlabel('Cross-validated SVM scores (colors are folds)');\nylabel('Cross-validated class prob estimates');\n\nhh = plot_vertical_line(0); set(hh, 'LineStyle', '--');\nhh = plot_horizontal_line(.5); set(hh, 'LineStyle', '--');\n\nlegend(lineh, {'True Class = 1' 'True Class = -1'});\n\ndrawnow, snapnow\n\nend\n\n\n\n\n% -------------------------------------------------------------------------\n% Inputs\n% -------------------------------------------------------------------------\n\n\n\nfunction ARGS = parse_inputs(varargin)\n\np = inputParser;\n\n\n% Validation functions - customized for each type of input\n% ----------------------------------------------------------------------\n\n% valfcn_scalar = @(x) validateattributes(x, {'numeric'}, {'nonempty', 'scalar'});\n\nvalfcn_number = @(x) validateattributes(x, {'numeric'}, {'nonempty'}); % scalar or vector\n\nvalfcn_cell = @(x) validateattributes(x, {'cell'}, {'nonempty'}); % scalar or vector\n\n% Validation: Region object, structure, or [x1 x2 x3] triplet\n% valfcn_custom = @(x) isstruct(x) || isa(x, 'region') || (~isempty(x) && all(size(x) - [1 3] == 0) && all(isnumeric(x)));\n\nvalfcn_logical = @(x) validateattributes(x, {}, {'nonempty', 'scalar', '>=', 0, '<=', 1}); % could enter numeric 0,1 or logical\n\nvalfcn_effectscode = @(x) validateattributes(x, {'numeric'}, {'nonempty', '<=', 1, '>=', -1});\n\n% Required inputs\n% ----------------------------------------------------------------------\np.addRequired('X', valfcn_number);\np.addRequired('Y', valfcn_effectscode); \np.addRequired('id', valfcn_number);\n\n% Optional inputs\n% ----------------------------------------------------------------------\n% Pattern: keyword, value, validation function handle\n\np.addParameter('doplot', true, valfcn_logical);\np.addParameter('doverbose', true, valfcn_logical);\np.addParameter('dooptimize', true, valfcn_logical);\np.addParameter('dorepeats', 10, valfcn_number);\np.addParameter('dobootstrap', true, valfcn_logical);\np.addParameter('nboot', 1000, valfcn_number);\np.addParameter('nfolds',10, valfcn_number); % Added by Michael Sun 08/2/2022\n\np.addParameter('modeloptions', {'KernelFunction', 'linear'}, valfcn_cell);\n\n\n% Parse inputs and distribute out to variable names in workspace\n% ----------------------------------------------------------------------\n% e.g., p.parse([30 1 0], [-40 0 10], 'bendpercent', .1);\np.parse(varargin{:});\n\nARGS = p.Results;\n\nend % parse_inputs);\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/Cross_validated_Regression/xval_SVM.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835207180245, "lm_q2_score": 0.651354857898194, "lm_q1q2_score": 0.5441962499135716}} {"text": "function mpc = case16am\n%CASE16AM Power flow data for 15 bus distribution system from Das, et al\n% Please see CASEFORMAT for details on the case file format.\n%\n% Data from ...\n% Das D, Kothari DP, Kalam A (1995) Simple and efficient method for load\n% flow solution of radial distribution networks. Int J Electr Power\n% Energy Syst 17:335-346. doi: 10.1016/0142-0615(95)00050-0\n% URL: https://doi.org/10.1016/0142-0615(95)00050-0\n\n%% MATPOWER Case Format : Version 2\nmpc.version = '2';\n\n%%----- Power Flow Data -----%%\n%% system MVA base\nmpc.baseMVA = 10;\n\n%% bus data\n%\tbus_i\ttype\tPd\tQd\tGs\tBs\tarea\tVm\tVa\tbaseKV\tzone\tVmax\tVmin\nmpc.bus = [ %% (Pd and Qd are specified in kW & kVAr here, converted to MW & MVAr below)\n\t1\t3\t0\t0\t0\t0\t1\t1\t0\t12.66\t1\t1\t1;\n\t2\t1\t0\t0\t0\t0\t1\t1\t0\t12.66\t1\t1.1\t0.9;\n\t3\t1\t2000\t1600\t0\t0\t1\t1\t0\t12.66\t1\t1.1\t0.9;\n\t4\t1\t3000\t400\t0\t0\t1\t1\t0\t12.66\t1\t1.1\t0.9;\n\t5\t1\t2000\t-400\t0\t0\t1\t1\t0\t12.66\t1\t1.1\t0.9;\n\t6\t1\t1500\t1200\t0\t0\t1\t1\t0\t12.66\t1\t1.1\t0.9;\n\t7\t1\t4000\t2700\t0\t0\t1\t1\t0\t12.66\t1\t1.1\t0.9;\n\t8\t1\t5000\t1800\t0\t0\t1\t1\t0\t12.66\t1\t1.1\t0.9;\n\t9\t1\t1000\t900\t0\t0\t1\t1\t0\t12.66\t1\t1.1\t0.9;\n\t10\t1\t600\t-500\t0\t0\t1\t1\t0\t12.66\t1\t1.1\t0.9;\n\t11\t1\t4500\t-1700\t0\t0\t1\t1\t0\t12.66\t1\t1.1\t0.9;\n\t12\t1\t1000\t900\t0\t0\t1\t1\t0\t12.66\t1\t1.1\t0.9;\n\t13\t1\t1000\t-1100\t0\t0\t1\t1\t0\t12.66\t1\t1.1\t0.9;\n\t14\t1\t1000\t900\t0\t0\t1\t1\t0\t12.66\t1\t1.1\t0.9;\n\t15\t1\t2100\t-800\t0\t0\t1\t1\t0\t12.66\t1\t1.1\t0.9;\n];\n\n%% generator data\n%\tbus\tPg\tQg\tQmax\tQmin\tVg\tmBase\tstatus\tPmax\tPmin\tPc1\tPc2\tQc1min\tQc1max\tQc2min\tQc2max\tramp_agc\tramp_10\tramp_30\tramp_q\tapf\nmpc.gen = [\n\t1\t0\t0\t10\t-10\t1\t100\t1\t10\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n];\n\n%% branch data\n%\tfbus\ttbus\tr\tx\tb\trateA\trateB\trateC\tratio\tangle\tstatus\tangmin\tangmax\nmpc.branch = [ %% (r and x specified in ohms here, converted to p.u. below)\n\t1\t2\t0\t1e-8\t0\t0\t0\t0\t0\t0\t1\t-360\t360; %% original reactance of 0 set to 1e-8\n\t2\t3\t0.1202\t0.1603\t0\t0\t0\t0\t0\t0\t1\t-360\t360;\n\t3\t4\t0.1282\t0.1763\t0\t0\t0\t0\t0\t0\t1\t-360\t360;\n\t3\t5\t0.1442\t0.2885\t0\t0\t0\t0\t0\t0\t1\t-360\t360;\n\t5\t6\t0.0641\t0.0641\t0\t0\t0\t0\t0\t0\t1\t-360\t360;\n\t2\t7\t0.1763\t0.1763\t0\t0\t0\t0\t0\t0\t1\t-360\t360;\n\t7\t8\t0.1282\t0.1763\t0\t0\t0\t0\t0\t0\t1\t-360\t360;\n\t7\t9\t0.1763\t0.1763\t0\t0\t0\t0\t0\t0\t1\t-360\t360;\n\t8\t10\t0.1763\t0.1763\t0\t0\t0\t0\t0\t0\t1\t-360\t360;\n\t8\t11\t0.1282\t0.1763\t0\t0\t0\t0\t0\t0\t1\t-360\t360;\n\t2\t12\t0.1763\t0.1763\t0\t0\t0\t0\t0\t0\t1\t-360\t360;\n\t12\t13\t0.1442\t0.1923\t0\t0\t0\t0\t0\t0\t1\t-360\t360;\n\t12\t14\t0.1282\t0.1763\t0\t0\t0\t0\t0\t0\t1\t-360\t360;\n\t14\t15\t0.0641\t0.0641\t0\t0\t0\t0\t0\t0\t1\t-360\t360;\n];\n\n%%----- OPF Data -----%%\n%% generator cost data\n%\t1\tstartup\tshutdown\tn\tx1\ty1\t...\txn\tyn\n%\t2\tstartup\tshutdown\tn\tc(n-1)\t...\tc0\nmpc.gencost = [\n\t2\t0\t0\t3\t0\t20\t0;\n];\n\n\n%% convert branch impedances from Ohms to p.u.\n[PQ, PV, REF, NONE, BUS_I, BUS_TYPE, PD, QD, GS, BS, BUS_AREA, VM, ...\n VA, BASE_KV, ZONE, VMAX, VMIN, LAM_P, LAM_Q, MU_VMAX, MU_VMIN] = idx_bus;\n[F_BUS, T_BUS, BR_R, BR_X, BR_B, RATE_A, RATE_B, RATE_C, ...\n TAP, SHIFT, BR_STATUS, PF, QF, PT, QT, MU_SF, MU_ST, ...\n ANGMIN, ANGMAX, MU_ANGMIN, MU_ANGMAX] = idx_brch;\nVbase = mpc.bus(1, BASE_KV) * 1e3; %% in Volts\nSbase = mpc.baseMVA * 1e6; %% in VA\nmpc.branch(:, [BR_R BR_X]) = mpc.branch(:, [BR_R BR_X]) / (Vbase^2 / Sbase);\n\n%% convert loads from kW to MW\nmpc.bus(:, [PD, QD]) = mpc.bus(:, [PD, QD]) / 1e3;\n", "meta": {"author": "MATPOWER", "repo": "matpower", "sha": "7da926d978824bf675a71e0a5cb91f8967f97007", "save_path": "github-repos/MATLAB/MATPOWER-matpower", "path": "github-repos/MATLAB/MATPOWER-matpower/matpower-7da926d978824bf675a71e0a5cb91f8967f97007/data/case16am.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.7154239897159439, "lm_q1q2_score": 0.5441877247184222}} {"text": "function sparse_grid_mixed_size_tabulate ( rule_1d, alpha_1d, beta_1d, ...\n dim_min, dim_max, level_max_min, level_max_max )\n\n%****************************************************************************80\n%\n%% SPARSE_GRID_MIXED_SIZE_TABULATE tests SPARSE_GRID_MIXED_SIZE.\n%\n% Discussion:\n%\n% We do NOT consider mixed rules. Instead, we are looking at sparse grid\n% rules for which all dimensions use the same 1D rule family.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 21 February 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer RULE_1D, the 1D rule.\n%\n% Input, real ALPHA_1D, BETA_1D, the optional parameters.\n%\n% Input, integer DIM_MIN, the minimum spatial dimension.\n%\n% Input, integer DIM_MAX, the maximum spatial dimension.\n%\n% Input, integer LEVEL_MAX_MIN, the minimum value of LEVEL_MAX.\n%\n% Input, integer LEVEL_MAX_MAX, the maximum value of LEVEL_MAX.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SPARSE_GRID_MIXED_SIZE_TABULATE\\n' );\n fprintf ( 1, ' SPARSE_GRID_MIXED_SIZE returns the number of distinct\\n' );\n fprintf ( 1, ' points in a sparse grid.\\n' );\n\n if ( rule_1d == 0 )\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Here we report the total number of polynomials of\\n' )\n fprintf ( 1, ' degree DEGREE or less in the given DIM dimensional space.\\n' );\n fprintf ( 1, ' (This is essentially Pascal''s triangle.)\\n' );\n fprintf ( 1, '\\n' );\n\n fprintf ( 1, ' DIM: ' );\n for dim_num = dim_min : dim_max\n fprintf ( 1, ' %8d', dim_num );\n end\n fprintf ( 1, '\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' DEGREE\\n' );\n fprintf ( 1, '\\n' );\n\n degree_max = 2 * level_max_max + 1;\n\n for degree = 0 : degree_max\n\n fprintf ( 1, ' %4d', degree );\n\n for dim_num = dim_min : dim_max\n\n point_num = i4_choose ( dim_num + degree, dim_num );\n\n fprintf ( 1, ' %8d', point_num );\n\n end\n\n fprintf ( 1, '\\n' );\n\n end\n\n else\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' We use the same rule in all dimensions, and count the points\\n' );\n fprintf ( 1, ' for a range of dimensions and levels.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' 1D rule index is %d\\n', rule_1d );\n fprintf ( 1, ' ALPHA parameter is %f\\n', alpha_1d );\n fprintf ( 1, ' BETA parameter is %f\\n', beta_1d );\n fprintf ( 1, '\\n' );\n\n tol = sqrt ( eps );\n\n fprintf ( 1, ' DIM: ' );\n for dim_num = dim_min : dim_max\n fprintf ( 1, ' %8d', dim_num );\n end\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\n fprintf ( 1, ' %4d', level_max );\n\n for dim_num = dim_min : dim_max\n\n rule(1:dim_num) = rule_1d;\n alpha(1:dim_num) = alpha_1d;\n beta(1:dim_num) = beta_1d;\n\n point_num = sparse_grid_mixed_size ( dim_num, level_max, rule, alpha, ...\n beta, tol );\n\n fprintf ( 1, ' %8d', point_num );\n\n end\n\n fprintf ( 1, '\\n' );\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_size_tabulate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239836484143, "lm_q2_score": 0.7606506526772884, "lm_q1q2_score": 0.5441877201031521}} {"text": "function x=subint(x1,x2,x3,x4,na,nb,nc)\n%subint geometrically stretched subdivision generator \n% x=subint(x1,x2,x3,x4,na,nb,nc);\n% input\n% x1 left coordinate\n% x2 limit of uniform expansion section\n% x3 limit of equal subinterval section\n% x4 right coordinate and limit of contraction section\n% na number of uniformly expanded subintervals\n% nb number of intermediate uniform subintervals\n% nc number of contracting subintervals\n% output\n% x vector of coordinates\n%\n% calls function fitint\n% sets up global variables global_N, global_INTL, global_LASTDL \n% IFISS function: DJS; 28 February 2005.\n% Copyright (c) 2005 D.J. Silvester, H.C. Elman, A. Ramage \n global global_N global_INTL global_LASTDL \n intla=x2-x1;\n intlb=x3-x2;\n intlc=x4-x3;\n npts=na+nb+nc+1;\n bdl=intlb/nb;\n x=zeros(npts,1);\n x(1)=x1;\n%\n% uniform expansion section\n if na > 0\n%% fixed value here\n% ratio = default('approximate expansion ratio (default 1.2)',1.2); \n ratio = 1.2;\n global_N=na; \n global_INTL=intla;\n global_LASTDL=bdl;\n [ratio,initdl]=fitint(ratio);\n fprintf('computed stretch ratio is %10.5g \\n',ratio)\n dl=initdl;\n for node=2:na+1\n x(node)=x(node-1)+dl;\n dl=dl*ratio;\n end\n if (abs(x(na+1)-x2) > 1e-6)\n fprintf('\\n warning ...\\n calculated coordinate is %10.5g',x(na+1))\n fprintf(' \\n input coordinate is %10.5g',x2)\n x(na+1)=x2;\n end\n end\n%\n% uniform subinterval section\n dl=bdl;\n for node=na+2:na+nb+1\n x(node)=x(node-1) + dl;\n end\n%\n% uniform contraction section\n if nc > 0\n%% fixed value here\n% ratio = default('approximate contraction ratio (default 1.2)',\n ratio = 1.2;\n global_N=nc; \n global_INTL=intlc;\n global_LASTDL=bdl;\n [ratio,initdl]=fitint(ratio);\n% fprintf('computed contraction ratio is %10.5g \\n',ratio)\n dl=global_LASTDL/ratio;\n for node=na+nb+2:npts\n x(node)=x(node-1)+dl;\n dl=dl/ratio;\n end\n if (abs(x(npts)-x4) > 1e-6)\n fprintf('\\n warning ...\\n calculated coordinate is %10.5g',x(npts))\n fprintf(' \\n input coordinate is %10.5g',x4)\n end\n end\n x(npts)=x4;\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/grids/subint.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833737577158, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.5441681068475906}} {"text": "function [tfr,rtfr,hat] = tfrrgab(x,t,N,Nh,trace,K);\n%TFRRGAB Reassigned Gabor spectrogram time-frequency distribution.\n%\t[TFR,RTFR,HAT] = TFRRGAB(X,T,N,NH,TRACE,K) \n%\tcomputes the Gabor spectrogram and its reassigned version.\n%\tThis particular window (a Gaussian window) allows a 20 % faster\n%\talgorithm than the TFRRSP function.\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%\tNH : length of the gaussian window (default : N/4))\n%\tTRACE : if nonzero, the progression of the algorithm is shown\n% (default : 0).\n%\tK : value at both extremities (default 0.001)\n%\tTFR, : time-frequency representation and its reassigned\n%\tRTFR version. When called without output arguments, \n%\t TFRRGAB runs TFRQVIEW.\n%\tHAT : Complex matrix of the reassignment vectors.\n%\n%\tExample :\n%\t sig=fmlin(128,0.1,0.4); tfrrgab(sig,1:128,128,19,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% Copyright (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 <= 2),\n N=xrow;\nend;\n\nhlength=floor(N/4);\nhlength=hlength+1-rem(hlength,2);\n\nif (nargin == 1),\n t=1:xrow; \nend;\n\nif (nargin <= 3),\n Nh=hlength; trace=0; K=0.001;\nelseif (nargin == 4),\n trace = 0; K=0.001;\nelseif (nargin == 5),\n K= 0.001;\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 & nargin==6),\n fprintf('For a faster computation, N should be a power of two\\n');\nend; \n\nif (rem(Nh,2)==0), \n error('Nh must be odd'); \nelseif length(Nh)~=1,\n error('Nh must be a scalar');\nend;\n\nNh2=Nh-2;\nTFTBcontinue=1;\nwhile TFTBcontinue,\n Nh2=Nh2+2;\n h=tftb_window(Nh2,'gauss',K^((Nh2-1)^2 /(Nh-1)^2)); \n TFTBcontinue=(h(Nh2)*(Nh2-1)>2*K);\nend;\n\nK=K^((Nh2-1)^2 /(Nh-1)^2); Nh=Nh2; Lh=(Nh-1)/2; \nh=h; Th=h.*[-Lh:Lh]';\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); tf3= zeros(N,tcol);\nif trace, disp('Gabor spectrogram'); end;\n\nfor icol=1:tcol,\n if trace, disprog(icol,tcol,10); end;\n ti= t(icol); \n tau=-min([round(N/2)-1,Lh,ti-1]):min([round(N/2)-1,Lh,xrow-ti]);\n indices= rem(N+tau,N)+1;\n norm_h=norm(h(Lh+1+tau));\n tfr(indices,icol)=x(ti+tau).*conj( h(Lh+1+tau)) /norm_h;\n tf2(indices,icol)=x(ti+tau).*conj(Th(Lh+1+tau)) /norm_h;\nend ;\ntfr=fft(tfr); tf2=fft(tf2);\ntfr=tfr(:); tf2=tf2(:); tf3=tf3(:);\navoid_warn=find(tfr~=0.0);\ntf3(avoid_warn)=round(imag(2*log(K)*N*tf2(avoid_warn)./tfr(avoid_warn)/(2.0*pi*Lh^2)));\ntf2(avoid_warn)=round(real(tf2(avoid_warn)./tfr(avoid_warn)/Dt));\ntfr=abs(tfr).^2;\nif trace, fprintf ('\\nreassignment: \\n'); end;\ntfr=reshape(tfr,N,tcol);\ntf2=reshape(tf2,N,tcol);\ntf3=reshape(tf3,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 icolhat= icol + tf2(jcol,icol);\n icolhat=min(max(icolhat,1),tcol);\n jcolhat= jcol - tf3(jcol,icol);\n %while (jcolhat<1),jcolhat=jcolhat+N; end;\n %while (jcolhat>N),jcolhat=jcolhat-N; end;\n jcolhat=rem(rem(jcolhat-1,N)+N,N)+1;\n rtfr(jcolhat,icolhat)=rtfr(jcolhat,icolhat) + tfr(jcol,icol) ;\n tf2(jcol,icol)=jcolhat + j * icolhat;\n else\n tf2(jcol,icol)=inf*(1+j);\n rtfr(jcol,icol)=rtfr(jcol,icol) + tfr(jcol,icol) ;\n end;\n end;\nend;\n\nif trace, fprintf('\\n'); end;\nclear tf3;\nif (nargout==0),\n TFTBcontinue=1;\n while (TFTBcontinue==1),\n choice=menu ('Choose the representation:',...\n 'stop',...\n 'Gabor spectrogram',...\n 'reassigned Gabor spectrogram');\n if (choice==1), TFTBcontinue=0;\n elseif (choice==2), \n Q=round(tcol*N/xrow);\n tfrqview(tfr,x,t,'tfrgabor',tcol,Q,h);\n elseif (choice==3),\n tfrqview(rtfr,x,t,'tfrrgab',Nh);\n end;\n end;\nelseif (nargout>2),\n hat=tf2;\nend;\n\n", "meta": {"author": "HeLiangHIT", "repo": "time_frequency", "sha": "09c2abe92355ff5cd867bdb169229682e9d7af7c", "save_path": "github-repos/MATLAB/HeLiangHIT-time_frequency", "path": "github-repos/MATLAB/HeLiangHIT-time_frequency/time_frequency-09c2abe92355ff5cd867bdb169229682e9d7af7c/tf_tool_box/tftb-0.2/mfiles/tfrrgab.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.5441681045105451}} {"text": "%==============================================================================\n% This code is part of the Matlab-based toolbox\n% FAIR - Flexible Algorithms for Image Registration. \n% For details see \n% - https://github.com/C4IR and\n% - http://www.siam.org/books/fa06/\n% ##2\n%==============================================================================\n% \n% - data MRI (head), Omega=(0,128)x(0,128), level=4:7, m=[128,128]\n% - viewer viewImage2D\n% - interpolation splineInter\n% - distance NGF\n% - pre-registration rigid2D\n% - regularizer mbElastic\n% - optimization lBFGS\n% version 2015/05/20\n% ===============================================================================\n\n\nclose all, help(mfilename);\nsetup2DMRIData\n\nimgModel('reset','imgModel','splineInter','regularizer','moments','theta',1e-1);\ndistance('reset','distance','NGF','edge',50);\ntrafo('reset','trafo','rigid2D');\nregularizer('reset','regularizer','mbElastic','alpha',0.1,'mu',1,'lambda',0);\n\nPIRpara = optPara('lBFGS','solver','backslash');\nNPIRpara = optPara('lBFGS','solver',regularizer('get','solver'));\n\n[yc,wc,his] = MLIR(ML,'PIRobj',@PIRBFGSobjFctn,'PIRpara',PIRpara,...\n 'NPIRobj',@NPIRBFGSobjFctn,'NPIRpara',NPIRpara,...\n 'minLevel',4,'maxLevel',7,'parametric',1,'plotMLiter',0);\n\n%==============================================================================\n", "meta": {"author": "C4IR", "repo": "FAIR.m", "sha": "975edebd37b833ae76696792870de5c05efcb9cb", "save_path": "github-repos/MATLAB/C4IR-FAIR.m", "path": "github-repos/MATLAB/C4IR-FAIR.m/FAIR.m-975edebd37b833ae76696792870de5c05efcb9cb/kernel/examples/E9_MRIhead_MLIRlBFGS_NGF_mbElas.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.874077222043951, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5440775230522527}} {"text": "function vifp=vifp_mscale(ref,dist)\n\n% -----------COPYRIGHT NOTICE STARTS WITH THIS LINE------------\n% Copyright (c) 2005 The University of Texas at Austin\n% All rights reserved.\n% \n% Permission is hereby granted, without written agreement and without license or royalty fees, to use, copy, \n% modify, and distribute this code (the source files) and its documentation for\n% any purpose, provided that the copyright notice in its entirety appear in all copies of this code, and the \n% original source of this code, Laboratory for Image and Video Engineering (LIVE, http://live.ece.utexas.edu)\n% at the University of Texas at Austin (UT Austin, \n% http://www.utexas.edu), is acknowledged in any publication that reports research using this code. The research\n% is to be cited in the bibliography as:\n% \n% H. R. Sheikh and A. C. Bovik, \"Image Information and Visual Quality\", IEEE Transactions on \n% Image Processing, (to appear).\n% \n% IN NO EVENT SHALL THE UNIVERSITY OF TEXAS AT AUSTIN BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, \n% OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS DATABASE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF TEXAS\n% AT AUSTIN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n% \n% THE UNIVERSITY OF TEXAS AT AUSTIN SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED \n% WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE DATABASE PROVIDED HEREUNDER IS ON AN \"AS IS\" BASIS,\n% AND THE UNIVERSITY OF TEXAS AT AUSTIN HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n% \n% -----------COPYRIGHT NOTICE ENDS WITH THIS LINE------------\n% \n% This software release consists of a MULTISCALE PIXEL DOMAIN, SCALAR GSM implementation of the algorithm described in the paper:\n% \n% H. R. Sheikh and A. C. Bovik, \"Image Information and Visual Quality\"., IEEE Transactions on Image Processing, (to appear).\n% Download manuscript draft from http://live.ece.utexas.edu in the Publications link.\n% \n% THE PIXEL DOMAIN ALGORITHM IS NOT DESCRIBED IN THE PAPER. THIS IS A COMPUTATIONALLY SIMPLER\n% DERIVATIVE OF THE ALGORITHM PRESENTED IN THE PAPER\n% \n% Input : (1) img1: The reference image as a matrix\n% (2) img2: The distorted image (order is important)\n% \n% Output: (1) VIF the visual information fidelity measure between the two images\n% \n% Default Usage:\n% Given 2 test images img1 and img2, whose dynamic range is 0-255\n% \n% vif = vifvec(img1, img2);\n% \n% Advanced Usage:\n% Users may want to modify the parameters in the code. \n% (1) Modify sigma_nsq to find tune for your image dataset.\n% Email comments and bug reports to hamid.sheikh@ieee.org\n\n\nsigma_nsq=2;\n\nnum=0;\nden=0;\nfor scale=1:4\n \n N=2^(4-scale+1)+1;\n win=fspecial('gaussian',N,N/5);\n \n if (scale >1)\n ref=filter2(win,ref,'valid');\n dist=filter2(win,dist,'valid');\n ref=ref(1:2:end,1:2:end);\n dist=dist(1:2:end,1:2:end);\n end\n \n mu1 = filter2(win, ref, 'valid');\n mu2 = filter2(win, dist, 'valid');\n mu1_sq = mu1.*mu1;\n mu2_sq = mu2.*mu2;\n mu1_mu2 = mu1.*mu2;\n sigma1_sq = filter2(win, ref.*ref, 'valid') - mu1_sq;\n sigma2_sq = filter2(win, dist.*dist, 'valid') - mu2_sq;\n sigma12 = filter2(win, ref.*dist, 'valid') - mu1_mu2;\n \n sigma1_sq(sigma1_sq<0)=0;\n sigma2_sq(sigma2_sq<0)=0;\n \n g=sigma12./(sigma1_sq+1e-10);\n sv_sq=sigma2_sq-g.*sigma12;\n \n g(sigma1_sq<1e-10)=0;\n sv_sq(sigma1_sq<1e-10)=sigma2_sq(sigma1_sq<1e-10);\n sigma1_sq(sigma1_sq<1e-10)=0;\n \n g(sigma2_sq<1e-10)=0;\n sv_sq(sigma2_sq<1e-10)=0;\n \n sv_sq(g<0)=sigma2_sq(g<0);\n g(g<0)=0;\n sv_sq(sv_sq<=1e-10)=1e-10;\n \n \n num=num+sum(sum(log10(1+g.^2.*sigma1_sq./(sv_sq+sigma_nsq))));\n den=den+sum(sum(log10(1+sigma1_sq./sigma_nsq)));\n \nend\nvifp=num/den;", "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/vifp_mscale.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645724, "lm_q2_score": 0.6859494550081926, "lm_q1q2_score": 0.5440306016873974}} {"text": "function [Vx,Vy,reliab]=opticalFlow( I1, I2, varargin )\n% Coarse-to-fine optical flow using Lucas&Kanade or Horn&Schunck.\n%\n% Implemented 'type' of optical flow estimation:\n% LK: http://en.wikipedia.org/wiki/Lucas-Kanade_method\n% HS: http://en.wikipedia.org/wiki/Horn-Schunck_method\n% LK is a local, fast method (the implementation is fully vectorized).\n% HS is a global, slower method (an SSE implementation is provided).\n%\n% Common parameters for LK and HS: 'smooth' determines smoothing prior to\n% flow computation and can make flow estimation more robust. 'resample' can\n% be used to downsample an image for faster but lower quality results, e.g.\n% resample=.5 makes flow computation about 4x faster. LK: 'radius' controls\n% integration window size (and smoothness of flow). HS: 'alpha' controls\n% tradeoff between data and smoothness term (and smoothness of flow) and\n% 'nIter' determines number of gradient decent steps.\n%\n% USAGE\n% [Vx,Vy,reliab] = opticalFlow( I1, I2, pFlow )\n%\n% INPUTS\n% I1, I2 - input images to calculate flow between\n% pFlow - parameters (struct or name/value pairs)\n% .type - ['LK'] may be either 'LK' or 'HS'\n% .smooth - [1] smoothing radius for triangle filter (may be 0)\n% .resample - [1] resampling amount (must be a power of 2)\n% .radius - [5] integration radius for weighted window [LK only]\n% .alpha - [1] smoothness constraint [HS only]\n% .nIter - [250] number of iterations [HS only]\n%\n% OUTPUTS\n% Vx, Vy - x,y components of flow [Vx>0->right, Vy>0->down]\n% reliab - reliability of flow in given window [LK only]\n%\n% EXAMPLE - compute LK flow on test images\n% load opticalFlowTest;\n% [Vx,Vy]=opticalFlow(I1,I2,'smooth',1,'radius',10,'type','LK');\n% figure(1); im(I1); figure(2); im(I2);\n% figure(3); im([Vx Vy]); colormap jet;\n%\n% EXAMPLE - rectify I1 to I2 using computed flow\n% load opticalFlowTest;\n% [Vx,Vy]=opticalFlow(I1,I2,'smooth',1,'radius',10,'type','LK');\n% I1=imtransform2(I1,[],'vs',-Vx,'us',-Vy,'pad','replicate');\n% figure(1); im(I1); figure(2); im(I2);\n%\n% EXAMPLE - compare LK and HS flow\n% load opticalFlowTest;\n% prm={'smooth',1,'radius',10,'alpha',20,'nIter',200,'type'};\n% tic, [Vx1,Vy1]=opticalFlow(I1,I2,prm{:},'LK'); toc\n% tic, [Vx2,Vy2]=opticalFlow(I1,I2,prm{:},'HS'); toc\n% figure(1); im([Vx1 Vy1; Vx2 Vy2]); colormap jet;\n%\n% See also convTri, imtransform2\n%\n% Piotr's Image&Video Toolbox Version 3.02\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\n% get default parameters and do error checking\ndfs={'type','LK','smooth',1,'resample',1,'radius',5,'alpha',1,'nIter',250};\n[type,smooth,resample,radius,alpha,nIter]=getPrmDflt(varargin,dfs,1);\nassert(any(strcmp(type,{'LK','HS'}))); useLk=strcmp(type,'LK');\nif( ~ismatrix(I1) || ~ismatrix(I2) || any(size(I1)~=size(I2)) )\n error('Input images must be 2D and have same dimensions.'); end\n\n% run optical flow in coarse to fine fashion\nif(~isa(I1,'single')), I1=single(I1); I2=single(I2); end\n[h,w]=size(I1); nScales=floor(log2(min(h,w)))-2;\nfor s=1:nScales + round(log2(resample))\n % get current scale and I1s and I2s at given scale\n scale=2^(nScales-s); h1=round(h/scale); w1=round(w/scale);\n if( scale==1 ), I1s=I1; I2s=I2; else\n I1s=imResample(I1,[h1 w1]); I2s=imResample(I2,[h1 w1]); end\n % initialize Vx,Vy or upsample from previous scale\n if(s==1), Vx=zeros(h1,w1,'single'); Vy=Vx; else r=sqrt(h1*w1/numel(Vx));\n Vx=imResample(Vx,[h1 w1])*r; Vy=imResample(Vy,[h1 w1])*r; end\n % transform I1s according to current estimate of Vx and Vy\n if(s), I1s=imtransform2(I1s,[],'pad','replciate','vs',-Vx,'us',-Vy); end\n % smooth images\n I1s=convTri(I1s,smooth); I2s=convTri(I2s,smooth);\n % run optical flow on current scale\n if( useLk ), [Vx1,Vy1,reliab]=opticalFlowLk(I1s,I2s,radius);\n else [Vx1,Vy1]=opticalFlowHs(I1s,I2s,alpha,nIter); reliab=[]; end\n Vx=Vx+Vx1; Vy=Vy+Vy1;\nend\nif(s~=nScales), r=sqrt(h*w/numel(Vx));\n Vx=imResample(Vx,[h w])*r; Vy=imResample(Vy,[h w])*r; end\n\nend\n\nfunction [Vx,Vy,reliab] = opticalFlowLk( I1, I2, radius )\n% Compute elements of A'A and also of A'b\nradius=min(radius,floor(min(size(I1,1),size(I1,2))/2)-1);\n[Ix,Iy]=gradient2(I1); It=I2-I1; AAxy=convTri(Ix.*Iy,radius);\nAAxx=convTri(Ix.^2,radius)+1e-5; ABxt=convTri(-Ix.*It,radius);\nAAyy=convTri(Iy.^2,radius)+1e-5; AByt=convTri(-Iy.*It,radius);\n% Find determinant and trace of A'A\nAAdet=AAxx.*AAyy-AAxy.^2; AAdeti=1./AAdet; AAtr=AAxx+AAyy;\n% Compute components of velocity vectors (A'A)^-1 * A'b\nVx = AAdeti .* ( AAyy.*ABxt - AAxy.*AByt);\nVy = AAdeti .* (-AAxy.*ABxt + AAxx.*AByt);\n% Check for ill conditioned second moment matrices\nreliab = 0.5*AAtr - 0.5*sqrt(AAtr.^2-4*AAdet);\nend\n\nfunction [Vx,Vy] = opticalFlowHs( I1, I2, alpha, nIter )\n% compute derivatives (averaging over 2x2 neighborhoods)\nA00=shift(I1,0,0); A10=shift(I1,1,0);\nA01=shift(I1,0,1); A11=shift(I1,1,1);\nB00=shift(I2,0,0); B10=shift(I2,1,0);\nB01=shift(I2,0,1); B11=shift(I2,1,1);\nEx=0.25*((A01+B01+A11+B11)-(A00+B00+A10+B10));\nEy=0.25*((A10+B10+A11+B11)-(A00+B00+A01+B01));\nEt=0.25*((B00+B10+B01+B11)-(A00+A10+A01+A11));\nEx([1 end],:)=0; Ex(:,[1 end])=0;\nEy([1 end],:)=0; Ey(:,[1 end])=0;\nEt([1 end],:)=0; Et(:,[1 end])=0;\nZ=1./(alpha*alpha + Ex.*Ex + Ey.*Ey);\n% iterate updating Ux and Vx in each iter\nif( 1 )\n [Vx,Vy]=opticalFlowHsMex(Ex,Ey,Et,Z,nIter);\n Vx=Vx(2:end-1,2:end-1); Vy=Vy(2:end-1,2:end-1);\nelse\n Vx=zeros(size(I1),'single'); Vy=Vx;\n for i = 1:nIter\n Mx=.25*(shift(Vx,-1,0)+shift(Vx,1,0)+shift(Vx,0,-1)+shift(Vx,0,1));\n My=.25*(shift(Vy,-1,0)+shift(Vy,1,0)+shift(Vy,0,-1)+shift(Vy,0,1));\n m=(Ex.*Mx+Ey.*My+Et).*Z; Vx=Mx-Ex.*m; Vy=My-Ey.*m;\n Vx=Vx(2:end-1,2:end-1); Vy=Vy(2:end-1,2:end-1);\n end\nend\nend\n\nfunction J = shift( I, y, x )\n% shift I by -1<=x,y<=1 pixels\n[h,w]=size(I); J=zeros(h+2,w+2,'single');\nJ(2-y:end-1-y,2-x:end-1-x)=I;\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/SketchTokens-master/toolbox/images/opticalFlow.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645724, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.544030596595578}} {"text": " function [mat, nexp] = filtmat(arg0, arg1, arg2, arg3, arg4)\n%function mat = filtmat('1d', kernx, nx)\n%\t\t\t1d nonperiodic\n%function mat = filtmat({'1d' 'per'}, kernx, nx)\n%\t\t\t1d periodic\n%function mat = filtmat('2d,mul,sep', kernx, kerny, [nx ny])\n%\t\t\t2d multiplicatively separable nonperiodic\n%function mat = filtmat('3d,mul,sep', kernx, kerny, kernz, [nx ny nz])\n%\t\t\t3d multiplicatively separable nonperiodic\n%\t\t\tkernel(x,y,z) = kernx(x) * kerny(y) * kernz(z)\n%function [mat, nexp] = filtmat({'3d,mul,sep' 'expand'}, kernx, kerny, kernz, [nx ny nz])\n%\t\t\t3d multiplicatively separable nonperiodic, expanded\n%function mat = filtmat('1d,causal', kernx, nx)\n%\t\t\t1d causal filter, ala convmtx\n%\n%\tForm matrix to do 3d linear filtering - odd kernel length.\n%\texpanding is like what happens in 'conv' - output is longer\n\nif ~nargin, help filtmat, error arg, end\nflag_expand = any(strcmp(arg0, 'expand'));\n\nif nargin == 3 && strcmp(arg0, '1d,causal')\n\tmat = filtmat1causal(arg1, arg2);\n\treturn\n\nelseif nargin == 3 && any(strcmp(arg0, '1d'))\n\tif any(strcmp(arg0, 'per'))\n\t\tmat = filtmat1per(arg1, arg2);\n\telse\n\t\tmat = filtmat1(arg1, arg2, flag_expand);\n\tend\n\treturn\n\nelseif nargin == 4 && any(strcmp(arg0, '2d,mul,sep'))\n\tmat = filtmat('3d,mul,sep', arg1, arg2, 1, [arg3 1]);\n\treturn\n\nelseif nargin == 5 && any(strcmp(arg0, '3d,mul,sep'))\n\tk.x = arg1;\n\tk.y = arg2;\n\tk.z = arg3;\n\tn.x = arg4(1);\n\tn.y = arg4(2);\n\tn.z = arg4(3);\nelse\n\tnargin, help filtmat, error arg\nend\n\n\tif flag_expand\n\n\t\t[p.x, o.x] = filtmat1(k.x, n.x, flag_expand);\n\t\t[p.y, o.y] = filtmat1(k.y, n.y, flag_expand);\n\t\t[p.z, o.z] = filtmat1(k.z, n.z, 0);\t% no z expansion\n\n\t\tp.x = kron(speye(n.y*n.z), p.x);\n\t\tp.y = kron(speye(n.z), kron(p.y, speye(o.x)));\n\t\tp.z = kron(p.z, speye(o.x*o.y));\n\n\t\tif 0\n\t\t\tn.xyz = n.x * n.y * n.z;\n\t\t\tt = (o.y-n.y)/2 * o.x;\n\t\t\tp.x = [sparse(t,n.xyz); p.x; sparse(t,n.xyz)];\n\t\t\tt = zeros(o.x,o.y);\n\t\t\tt([1:n.x]+(o.x-n.y)/2-1,:) = 1;\n\t\t\ttt = sparse(o.x*o.y, n.x*n.y);\n\t\t\ttt(find(t(:)),:) = p.y;\n\t\t\tp.y = tt;\n\t\t\tp.z = sparse(1,1);\n\t\t\tif n.z ~= 1, error notdone, end\n\t\tend\n\telse\n\t\tp.x = filtmat1(k.x, n.x, flag_expand);\n\t\tp.y = filtmat1(k.y, n.y, flag_expand);\n\t\tp.z = filtmat1(k.z, n.z, flag_expand);\n\n\t\tp.x = kron(speye(n.y*n.z), p.x);\n\t\tp.y = kron(speye(n.z), kron(p.y, speye(n.x)));\n\t\tp.z = kron(p.z, speye(n.x*n.y));\n\t\to = n;\n\tend\n\n%\tmat = p.x + p.y + p.z;\n\tif flag_expand, warning('fix: expand may not work for multiplicative?'), end\n\tmat = p.z * p.y * p.x;\n\tnexp = [o.x o.y o.z];\n\nfunction mat = filtmat1causal(kern, n)\n\tnk = length(kern);\n\tif nk < n, error n, end\n\tif n ~= nk, error 'not done', end\n\tt = kern(:,ones(1,n));\n\tt = [t; zeros(nk,nk)];\n\tt = t(:);\n\tt((end-nk+1):end) = [];\n\tmat = reshape(t, 2*nk-1,nk);\n\tmat = mat(1:nk,:);\n\nfunction [mat, nexp] = filtmat1(kern, n, flag_expand)\n%\t1d matrix that does linear filtering - odd kernel length.\n%\tflag_expand means output has more entries than input (n+nk-1)\n\n\tnk = length(kern);\n\tic = (nk+1)/2;\t\t% center index\n\tif round(ic) ~= ic,\terror('odd kernel only'), end\n\n\tif flag_expand\n\t\tn = n + nk-1;\n\tend\n\tnexp = n;\n\n\tmat = diag(ones(n,1)*kern(ic));\n\tfor iv=1:(ic-1)\n\t\tmat = mat + diag(ones(n-iv,1) * kern(ic-iv), -iv) ...\n\t\t\t + diag(ones(n-iv,1) * kern(ic+iv), iv);\n\tend\n\n\tif flag_expand\n\t\tmat = mat(:,ic:(end-ic+1));\n\tend\n\tmat = sparse(mat);\n\nfunction mat = filtmat1per(kern, nn)\n%\t1d matrix that does periodic linear filtering. odd or even kernel ok.\n\n\tnk = length(kern);\n\tic = (nk+1)/2;\n\n\tmat = spdiag(ones(nn,1)*kern(ic));\n\tfor kk=1:(ic-1)\n\t\tmat = mat ...\n\t\t\t+ diag(ones(nn-kk,1) * kern(ic-kk),\t-kk) ...\n\t\t\t+ diag(ones(kk ,1) * kern(ic-kk),\tnn-kk);\n\tend\n\n\tfor kk=1:floor(nk/2)\n\t\tmat = mat ...\n\t\t\t+ diag(ones(nn-kk,1) * kern(ic+kk),\tkk) ...\n\t\t\t+ diag(ones(kk ,1) * kern(ic+kk),\tkk-nn);\n\tend\n\tmat = sparse(mat);\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/utilities/filtmat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.5440305898866764}} {"text": "function [xc,good,bad,type] = cornerfinder_saddle_point(xt,I,wintx,winty,wx2,wy2);\n\n%[xc] = cornerfinder_saddle_point(xt,I,wintx,winty);\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\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\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 vIx = [itIx 1-itIx 0]'; \t% accuracy.\n else\n vIx = [0 1+itIx -itIx]';\n end;\n if itIy > 0,\n vIy = [itIy 1-itIy 0];\n else\n 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 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 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\n \n px = cIx + offx;\n py = cIy + offy;\n \n \n if 1, %~saddle,\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 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 else\n \n SI = SI(2:2*wintx+2,2:2*winty+2);\n A = repmat(mask(:),1,6) .* [px(:).^2 px(:).*py(:) py(:).^2 px(:) py(:) ones((2*wintx+1)*(2*winty+1),1)];\n param = inv(A'*A)*A'*( mask(:).*SI(:));\n xc2 = (-inv([2*param(1) param(2) ; param(2) 2*param(3) ]) * param(4:5))'; \n \n end;\n \n v_extra = xc(i,:) - xc2;\n \n xc(i,:) = xc2;\n \n \n compt = compt + 1;\n \n end;\n \n \n \n if 1,\n \n cIx = xc(i,1); \t\t\t%\n cIy = xc(i,2); \t\t\t% Coords. of the point\n crIx = round(cIx); \t\t% on the initial image\n crIy = round(cIy); \t\t% \n itIx = cIx - crIx; \t\t% Coefficients\n itIy = cIy - crIy; \t\t% to compute\n if itIx > 0, \t\t\t% the sub pixel\n vIx = [itIx 1-itIx 0]'; \t% accuracy.\n else\n vIx = [0 1+itIx -itIx]';\n end;\n if itIy > 0,\n vIy = [itIy 1-itIy 0];\n else\n 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 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 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 px = cIx + offx;\n py = cIy + offy;\n \n SI = SI(2:2*wintx+2,2:2*winty+2);\n A = repmat(mask(:),1,6) .* [px(:).^2 px(:).*py(:) py(:).^2 px(:) py(:) ones((2*wintx+1)*(2*winty+1),1)];\n param = inv(A'*A)*A'*( mask(:).*SI(:));\n xc2 = (-inv([2*param(1) param(2) ; param(2) 2*param(3) ]) * param(4:5))'; \n \n \n v_extra = xc(i,:) - xc2;\n \n xc(i,:) = xc2;\n end;\n \n \n \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_saddle_point.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339716830606, "lm_q2_score": 0.6477982043529715, "lm_q1q2_score": 0.5439781589904757}} {"text": "clear all; close all; clear classes; clc;\n\n%% Set flags.\ninspect_only = false;\n\n%% Solve the system.\ns = 120;\nw = 40;\nb = (s + w/2)*2;\ndL = 10;\ndl = 2;\nwvlen = 200;\nclear solveropts;\n[E, H, obj_array, src_array, J] = maxwell_run(...\n\t'OSC', 1e-9, wvlen, ...\n\t'DOM', {'vacuum', 'none', 1.0}, [-610 610; -610 610; 0 dl], [dL dL dl], BC.p, [10*dL 10*dL 0], ...\n\t'OBJ', {'vacuum', 'none', 1.0}, Box([-w/2 w/2; -w/2 w/2; 0 dl], dl), ...\n\t'SOBJ', ... % scatter objects\n\t\t{'Johnson/Au', 'y'}, ...\n\t\t\tPolygonalCylinder(Axis.z, dl, dl/2, [w/2 0; w/2+s*sqrt(3)/2 -s/2; w/2+s*sqrt(3)/2 s/2], dl), ...\n\t\t\tPolygonalCylinder(Axis.z, dl, dl/2, [-w/2 0; -w/2-s*sqrt(3)/2 s/2; -w/2-s*sqrt(3)/2 -s/2], dl), ...\n\t'SRCJ', TFSFPlaneSrc([-b b; -b b; 0 dl], Axis.y, Axis.x), ...\n\tinspect_only);\n\n%% Visualize the solution.\nfigure\nclear opts\nopts.withobjsrc = true;\nopts.withabs = true;\n% opts.withinterp = false;\n% opts.withgrid = true;\n% opts.cscale = 1e-1;\n% opts.cmax = 1.4;\nz_location = 0;\nvis2d(E{Axis.x}, Axis.z, z_location, obj_array, src_array, opts)\n% vis2d(H{Axis.z}, Axis.z, z_location, obj_array, src_array, opts)\n\n% %% Calculate the power emanating from the source.\n% power = powerflux_box(E,H,[-10 10; -10 10; 0 1]);\n% fprintf('power = %e\\n', power);\n", "meta": {"author": "wsshin", "repo": "maxwellfdfd", "sha": "f7d583813781694c8a6f0533a91f56c2a78a9ee5", "save_path": "github-repos/MATLAB/wsshin-maxwellfdfd", "path": "github-repos/MATLAB/wsshin-maxwellfdfd/maxwellfdfd-f7d583813781694c8a6f0533a91f56c2a78a9ee5/example/2d/bowtie_tfsf_2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127678225575, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.5439687171343733}} {"text": " function [xs, info] = pwls_pcg(x, G, W, yi, nder1, R, ...\n\t\tM, niter, stepper)\n%function [xs, info] = pwls_pcg(x, G, W, yi, nder1, R, ...\n%\t\tM, niter, stepper)\n%\n% weighted least squares with convex non-quadratic penalty\n% via preconditioned conjugate gradient algorithm\n% cost(x) = (y-Gx)'W(y-Gx)/2 - n'(y-Gx) + R(x)\n%\n% in\n%\tx\t[np,1]\t\tinitial estimate\n%\tG\t[nd,np]\t\tsystem matrix\n%\tW\t[nd,nd]\t\tdata weighting matrix, usually diag_sp(wi)\n%\tyi\t[nd,1]\t\tnoisy data\n%\tnder1\t[nn,1]\t\tlinear term (obsolete: use \"0\")\n%\tR\t\t\tpenalty object (see Reg1.m)\n%\tM\t[np,np]\t\tpreconditioner (use \"1\" if none)\n%\tniter\t\t\t# total iterations\n%\tstepper\t\t\tmethod for step-size line search\n%\t\t\t\tuse {} for a good default\n% out\n%\txs\t[np,niter]\testimates each iteration\n%\tinfo\t[niter, 3]\tgamma, step, time\n%\n% Copyright 1996-7, Jeff Fessler, The University of Michigan\n\nwarning 'pwls_pcg is obsolete; use pwls_pcg1 instead'\n\nif nargin < 8, help(mfilename), error args, end\n\ncpu etic\n\nif isempty(nder1), nder1 = 0; end\nif isempty(M), M = 1; end\nif nder1 ~= 0, error 'nder1 = 0 required', end\n\nif ~isvar('stepper') || isempty(stepper)\n\tstepper = {'qs', 3};\t% quad surr with this # of subiterations\nend\n\nxs = zeros(length(x), niter);\nxs(:,1) = x;\n\ninfo = zeros(niter,3);\n\n%\n% initialize projections\n%\nGx = G * x;\n\noldinprod = 0;\n\n% iterate\nfor ii=2:niter\n\tticker(mfilename, ii, niter)\n\n\t%\n\t% (negative) gradient\n\t%\n\tngrad = G' * (W * (yi-Gx) - nder1);\n\n\tpgrad = R.cgrad(R, x);\n\tngrad = ngrad - pgrad;\n\n\t%\n\t% preconditioned gradient\n\tpregrad = M * ngrad;\n\n\t% direction\n\tnewinprod = ngrad' * pregrad;\n\tif ii == 2\n\t\tddir = pregrad;\n\t\tgamma = 0;\n\telse\n\t\tif oldinprod == 0\n\t\t\twarn 'inprod=0. going nowhere!'\n\t\t\tgamma = 0;\n\t\telse\n\t\t\tgamma = newinprod / oldinprod;\t% Fletcher-Reeves\n%\t\t\tgamma = (newinprod - oldgrad' * pregrad) / oldinprod;\n\t\tend\n\t\tddir = pregrad + gamma * ddir;\n\tend\n\toldgrad = ngrad;\n\toldinprod = newinprod;\n\n\t% check if descent direction\n\tif real(ddir' * ngrad) < 0\n\t\twarning 'wrong direction'\n\t\tkeyboard\n%\t\tddir = pregrad;\t% revert\n%\t\toldinprod = 0;\t% reset\n\tend\n\n\t% step size in search direction\n\tGdir = G * ddir;\n%\tCdir = R.C * ddir;\n\n\t% one step based on quadratic surrogate for penalty\n\tif streq(stepper{1}, 'qs1')\n%\t\tpdenom = Cdir' * (R.wpot(R.wt, Cdir) .* Cdir); % cannot be?\n\t\tpdenom = (abs(ddir).^2)' * R.denom(R, x);\n\t\tdenom = Gdir'*(W*Gdir) + pdenom;\n\t\tif denom == 0\n\t\t\twarning 'found exact solution??? step=0 now!?'\n\t\t\tstep = 0;\n\t\telse\n\t\t\tstep = real((ddir' * grad) / denom);\n\t\tend\n\n\t% iteratively minimize \\Half || y-G (x+alf*ddir) ||_W^2 + R(x + alf*ddir)\n\telseif streq(stepper{1}, 'qs')\n\t\tnsub = stepper{2};\n\t\tdGWGd = Gdir'*(W*Gdir);\n\t\tdGWr = Gdir'*(W*(yi-Gx));\n\t\tstep = 0;\n\t\tfor is=1:nsub\n%\t\t\tpdenom = Cdir' * (R.wpot(R.wt, Cdir) .* Cdir);\n\t\t\tpdenom = (abs(ddir).^2)' * R.denom(R, x+step*ddir);\n\t\t\tdenom = dGWGd + pdenom;\n\t\t\tpgrad = R.cgrad(R, x + step * ddir);\n\t\t\tstep = step - (-dGWr + step * dGWGd + ddir' * pgrad) ...\n\t\t\t\t/ denom;\n%\t\t\tprintf('%d-%d %g', ii, is, step)\n\t\tend\n\n\telse\n\t\terror 'bad stepper'\n\tend\n\n\tif step < 0\n\t\twarning('downhill?')\n\t\tkeyboard\n\tend\n\n\t% update\n\tGx\t= Gx + step * Gdir;\n%\tCx\t= Cx + step * Cdir;\n\tx\t= x + step * ddir;\n\txs(:,ii) = x;\n\n\tinfo(ii,1) = gamma;\n\tinfo(ii,2) = step;\n\tinfo(ii,3) = cpu('etoc');\t% accum. time\nend\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/wls/pwls_pcg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127492339909, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.5439687052928842}} {"text": "function M = make_convn_mat(F, sz, shape, pad)\n%MAKE_CONVN_MAT Flexible N-D convolution matrix\n% M = MAKE_CONVN_MAT(F, SZ[, SHAPE[, PAD]]) returns the convolution\n% matrix for the matrix F. SZ gives the size of the array that the\n% convolution should be applied to. The returned matrix M is sparse. \n% If X is of size SZ and SHAPE is 'full', then reshape(M * X(:), SZ +\n% size(F) - 1) is the same as convn(X, F).\n%\n% The optional parameter SHAPE controls which parts of the convolution\n% result to return in M:\n% * 'full': (default) returns the full N-D convolution, i.e. the \n% behavior is identical to convn(X, F, 'full').\n% * 'same': returns the central part of the convolution that \n% is the same size as X, i.e. the behavior is\n% identical to convn(X, F, 'same').\n% * 'sameswap': identical to 'same' except that rounding needed for\n% even-sized filters is performed the opposite way.\n% * 'valid': returns only the part of the result that can be\n% computed without assuming zero-padded arrays,\n% i.e. the behavior is identical to convn(X, F,\n% 'valid').\n%\n% The optional parameter PAD controls whether to return an M that pads\n% the result of the convolution with zeros (default no padding):\n% * 'full': returns the result padded to the output size of a\n% full N-D convolution (works with SHAPE set to 'same'\n% and 'valid'). \n% * 'same': returns the result padded to the central part of the\n% convolution that is the same size as X (works with\n% SHAPE set to 'valid').\n% * 'sameswap': identical to 'same' except that rounding needed for\n% even-sized filters is performed the opposite way.\n% \n% See also CONVMTXN.\n% \n% Author: Stefan Roth, Department of Computer Science, TU Darmstadt\n% Contact: sroth@cs.tu-darmstadt.de\n% $Date: 2007-03-27 14:09:11 -0400 (Tue, 27 Mar 2007) $\n% $Revision: 252 $\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 \n % Default to full matrix\n if (nargin < 3)\n shape = 'full';\n end\n \n ndims = length(sz);\n\n % Border sizes for 'same' and 'sameswap'\n Fsize_lo_2 = ceil((size(F) - 1) / 2);\n Fsize_hi_2 = floor((size(F) - 1) / 2);\n \n % Border sizes for 'valid'\n Fsize = size(F) - 1;\n\n switch(shape)\n case 'same'\n % Mark valid and invalid pixels (i.e. the ones within and outside\n % of the part to be returned)\n valid = true(sz+size(F)-1);\n \n for d = 1:ndims\n for e = 1:ndims\n sub{e} = ':';\n end\n \n sub{d} = 1:Fsize_lo_2(d); \n valid(sub{:}) = false;\n sub{d} = size(valid, d)-Fsize_hi_2(d)+1:size(valid, d); \n valid(sub{:}) = false;\n end\n\n if (nargin > 3 && strcmp(pad, 'full'))\n % If we're padding to 'full' set the coefficients on the border\n % to zero\n M = convmtxn(F, sz, valid);\n else\n % If we're *not* padding, then suppress the rows of M that\n % correspond to the border\n M = convmtxn(F, sz);\n M = M(valid, :);\n end\n \n case 'sameswap'\n % Mark valid and invalid pixels (i.e. the ones within and outside\n % of the part to be returned), but round the other way\n valid = true(sz+size(F)-1);\n \n for d = 1:ndims\n for e = 1:ndims\n sub{e} = ':';\n end\n \n sub{d} = 1:Fsize_hi_2(d); \n valid(sub{:}) = false;\n sub{d} = size(valid, d)-Fsize_lo_2(d)+1:size(valid, d); \n valid(sub{:}) = false;\n end\n \n if (nargin > 3 && strcmp(pad, 'full'))\n % If we're padding to 'full' set the coefficients on the border\n % to zero\n M = convmtxn(F, sz, valid);\n else\n % If we're *not* padding, then suppress the rows of M that\n % correspond to the border\n M = convmtxn(F, sz);\n M = M(valid, :);\n end\n \n case 'valid'\n % Mark valid and invalid pixels (i.e. the ones within and outside\n % of the part to be returned)\n valid = true(sz+size(F)-1);\n \n for d = 1:ndims\n for e = 1:ndims\n sub{e} = ':';\n end\n \n sub{d} = 1:Fsize(d); \n valid(sub{:}) = false;\n sub{d} = size(valid, d)-Fsize(d)+1:size(valid, d); \n valid(sub{:}) = false;\n end\n \n if (nargin > 3)\n % If we're padding, then figure out the area to be padded \n\n switch (pad)\n case 'same'\n % Mark valid and invalid pixels (i.e. the ones within and outside\n % of the part to be padded)\n pad_valid = true(sz+size(F)-1);\n \n for d = 1:ndims\n for e = 1:ndims\n sub{e} = ':';\n end\n \n sub{d} = 1:Fsize_lo_2(d); \n pad_valid(sub{:}) = false;\n sub{d} = size(valid, d)-Fsize_hi_2(d)+1:size(valid, d); \n pad_valid(sub{:}) = false;\n end\n \n % Set coefficients on the border to zero\n M = convmtxn(F, sz, valid);\n \n % Suppress rows of M outside of the padded area\n M = M(pad_valid, :);\n \n case 'sameswap'\n % Mark valid and invalid pixels (i.e. the ones within and outside\n % of the part to be padded), but round the other way\n pad_valid = true(sz+size(F)-1);\n \n for d = 1:ndims\n for e = 1:ndims\n sub{e} = ':';\n end\n \n sub{d} = 1:Fsize_hi_2(d); \n pad_valid(sub{:}) = false;\n sub{d} = size(valid, d)-Fsize_lo_2(d)+1:size(valid, d); \n pad_valid(sub{:}) = false;\n end\n \n % Set coefficients on the border to zero\n M = convmtxn(F, sz, valid);\n \n % Suppress rows of M outside of the padded area\n M = M(pad_valid, :);\n \n otherwise\n % Padding to 'full'; only set coefficients on the border to zero\n M = convmtxn(F, sz, valid); \n end\n else\n % No padding; suppress all rows on the border\n M = convmtxn(F, sz);\n M = M(valid, :);\n end\n \n otherwise\n % Full convolution; return everything\n M = convmtxn(F, sz);\n \n end\n", "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/make_convn_mat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.5438129576231865}} {"text": "function [ulf, vlf, lf, hf, lfhf, ttlpwr] = CalcLfHfParams(PSD, F, limits,plot_on)\n% [ulf, vlf, lf, hf, lfhf, ttlpwr] = CalcLfHfParams(PSD, F, limits,plot_on)\n%\n% OVERVIEW: Compute the frequency domain features for a given PSD and\n% frequency bans limits\n% \n% INPUT: \n% PSD - power spectral density \n% F - frequency vector\n% limits - frequency domain analysis limits\n% plot_on - \n%\n% OUTPUT: \n%\t- ulf : (ms^2) Power in the ultra low frequency range (default < 0.003 Hz)\n%\t- vlf : (ms^2) Power in very low frequency range (default 0.003 <= vlf < 0.04 Hz)\n%\t- lf : (ms^2) Power in low frequency range (default 0.04Hz <= lf < 0.15 Hz)\n%\t- hf : (ms^2) Power in high frequency range (default 0.15 <= hf < 0.4 Hz)\n%\t- lfhf : Ratio LF [ms^2]/HF [ms^2]\n%\t- ttlpwr : (ms^2) Total spectral power (approximately <0.4 Hz)\n% \n%\tREPO: \n% https://github.com/cliffordlab/PhysioNet-Cardiovascular-Signal-Toolbox\n% ORIGINAL SOURCE AND AUTHORS: \n% Main script written by Adriana N. Vest\n% Dependent scripts written by various authors \n% (see functions for details) \n%\tCOPYRIGHT (C) 2016 \n% LICENSE: \n% This software is offered freely and without warranty under \n% the GNU (v3 or later) public license. See license file for\n% more information\n%%\nif nargin <3\n ULF = [0 .003];\n VLF = [0.003 .04];\n LF = [.04 .15];\n HF = [0.15 0.4];\n limits = [ULF; VLF; LF; HF];\nend\nif nargin < 4\n plot_on =1;\nend\n\nIndx_ULF = find( (limits(1,1) <= F) & (F <= limits(1,2)) );\nIndx_VLF = find( (limits(2,1) <= F) & (F <= limits(2,2)) );\nIndx_LF = find( (limits(3,1) <= F) & (F <= limits(3,2)) );\nIndx_HF = find( (limits(4,1) <= F) & (F <= limits(4,2)) );\nspace = F(2)-F(1);\n\nulf = sum(PSD(Indx_ULF)*space) * 1e6; % convert to ms^2\nvlf = sum(PSD(Indx_VLF)*space) * 1e6; % convert to ms^2\nlf = sum(PSD(Indx_LF)*space) * 1e6; % convert to ms^2\nhf = sum(PSD(Indx_HF)*space) * 1e6; % convert to ms^2\n\nttlpwr = sum([ulf vlf lf hf]);\n\nlf_n = lf/ttlpwr; % normalized\nhf_n = hf/ttlpwr;\nlfhf = round(lf_n/hf_n*100)/100; % lf/hf ratio\n\nif plot_on\n figure\n % plot PSD\n plot(F,10*log10(PSD),'b','linewidth',2)\n hold on\n % plot limits on graph for lf and hf\n plot([F(Indx_LF(1)) F(Indx_LF(1))],[-80 40],'k:')\n hold on\n plot([F(Indx_LF(end)) F(Indx_LF(end))],[-80 40],'k:')\n hold on\n plot([F(Indx_HF(end)) F(Indx_HF(end))],[-80 40],'k:')\n\n % labelsc\n text(0.07,30,'LF','Fontname','Times New Roman','Fontsize',10)\n text(0.25,30,'HF','Fontname','Times New Roman','Fontsize',10)\n %text(0.15, 35, 'Power Spectral Density','Fontname','Times New Roman','Fontsize',10)\n text(0.3, -60, strcat('LF/HF=',num2str(lfhf)),'Fontname','Times New Roman','Fontsize',10)\n ylabel('Normalized PSD (db/Hz)','Fontname','Times New Roman','fontsize',10)\n xlabel('Frequency (Hz)','Fontname','Times New Roman','fontsize',10)\n axis([0 .45 -80 40]);\n box off\nend % end plot\n\nend % end function\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/HRV_Metrics_Tools/CalcLfHfParams.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.5438129511628611}} {"text": "function [Vlims, dVlims] = opf_vlim_fcn(x, mpc, idx, mpopt)\n%OPF_VLIM_FCN Evaluates voltage magnitudes and their gradients.\n% [Vlims, dVlims] = OPF_VLIM_FCN(X, MPC, IDX, MPOPT)\n%\n% Computes the voltage magnitudes using real and imaginary part of complex voltage for\n% AC optimal power flow. Computes constraint vectors and their gradients.\n%\n% Inputs:\n% X : optimization vector\n% MPC : MATPOWER case struct\n% IDX : index of buses whose voltage magnitudes should be fixed\n% MPOPT : MATPOWER options struct\n%\n% Outputs:\n% VLIMS : vector of voltage magnitudes\n% DVLIMS : (optional) magnitude gradients\n%\n% Examples:\n% Vlims = opf_vlim_fcn(x, mpc, mpopt);\n% [Vlims, dVlims] = opf_vlim_fcn(x, mpc, idx, mpopt);\n%\n% See also OPF_VLIM_HESS\n\n% MATPOWER\n% Copyright (c) 2018, Power Systems Engineering Research Center (PSERC)\n% by Baljinnyam Sereeter, Delft University of Technology\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%% define named indices into data matrices\n[PQ, PV, REF, NONE, BUS_I, BUS_TYPE, PD, QD, GS, BS, BUS_AREA, VM, ...\n VA, BASE_KV, ZONE, VMAX, VMIN, LAM_P, LAM_Q, MU_VMAX, MU_VMIN] = idx_bus;\n\n%% unpack data\n[Vr, Vi] = deal(x{:});\n\n%% problem dimensions\nnb = length(Vi); %% number of buses\nn = length(idx); %% number of buses with voltage limits\n\n%% compute voltage magnitude\nVm2 = Vr(idx).^2 + Vi(idx).^2;\nVlims = [ mpc.bus(idx, VMIN).^2 - Vm2;\n Vm2 - mpc.bus(idx, VMAX).^2 ];\n\nif nargout > 1\n %% compute partials of voltage magnitude w.r.t Vr and Vi\n dVm_dVr = sparse(1:n, idx, 2 * Vr(idx), n, nb);\n dVm_dVi = sparse(1:n, idx, 2 * Vi(idx), n, nb);\n dVlims = [ -dVm_dVr -dVm_dVi; %% Vlims w.r.t Vr, Vi\n dVm_dVr dVm_dVi ];\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/opf_vlim_fcn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391595913457, "lm_q2_score": 0.6297746004557471, "lm_q1q2_score": 0.5437420973532472}} {"text": "function [vert,conn,tria,tnum] = tridiv2(varargin)\n%TRIDIV2 \"quadtree\" refinement for 2-simplex triangulations.\n% [VERT,EDGE,TRIA,TNUM] = TRIDIV2(VERT,EDGE,TRIA,TNUM) re-\n% turns a globally refined triangulation, in which all ed-\n% ges are bisected about their midpoints. Such refinement\n% splits each triangle into four new sub-triangles accord-\n% ing to a shape-preserving scheme.\n%\n% VERT is a V-by-2 array of XY coordinates in the triangu-\n% lation, EDGE is an array of constrained edges, TRIA is a\n% T-by-3 array of triangles, and TNUM is a T-by-1 array of\n% part indices. Each row of TRIA and EDGE define an eleme-\n% nt. VERT(TRIA(II,1),:), VERT(TRIA(II,2),:) and VERT(TRIA\n% (II,3),:) are the coordinates of the II-TH triangle. The\n% edges in EDGE are defined in a similar manner. NUM is an\n% array of part indexing, such that TNUM(II) is the index \n% of the part in which the II-TH triangle resides.\n%\n% [VERT,EDGE,TRIA,TNUM] = TRIDIV2(... ,TDIV) returns a se-\n% lectively refined mesh, where TDIV is a T-by-1 logical \n% array, with TDIV(KK) = TRUE if TRIA(KK,:) is to be refi-\n% ned. Such triangles are refined using the four-way split\n% described above. Additionally, a \"halo\" of adjacent tri-\n% angles are also refined to preseve compatibility of the\n% mesh. Such triangles are refined using a two-way bisect-\n% ion type scheme. \n\n% See also REFINE2, SMOOTH2\n\n% Darren Engwirda : 2017 --\n% Email : de2363@columbia.edu\n% Last updated : 29/01/2017\n\n%---------------------------------------------- extract args\n vert = []; conn = []; tria = []; tnum = [] ;\n tdiv = []; \n \n if (nargin>=+1), vert = varargin{1}; end\n if (nargin>=+2), conn = varargin{2}; end\n if (nargin>=+3), tria = varargin{3}; end\n if (nargin>=+4), tnum = varargin{4}; end\n if (nargin>=+5), tdiv = varargin{5}; end\n \n%---------------------------------------------- default arg.\n if (isempty(tnum))\n tnum = ones(size(tria,1),1) ;\n end\n if (isempty(tdiv))\n tdiv = true(size(tria,1),1) ;\n end\n \n%---------------------------------------------- basic checks \n if ( ~isnumeric(vert) || ...\n ~isnumeric(conn) || ...\n ~isnumeric(tria) || ...\n ~isnumeric(tnum) || ...\n ~islogical(tdiv) )\n error('tridiv2:incorrectInputClass' , ...\n 'Incorrect input class.') ;\n end\n \n%---------------------------------------------- basic checks\n tnum = tnum(:) ; tdiv = tdiv(:) ;\n if (ndims(vert) ~= +2 || ...\n ndims(conn) ~= +2 || ...\n ndims(tria) ~= +2 || ...\n ndims(tnum) ~= +2 || ...\n ndims(tdiv) ~= +2 )\n error('tridiv2:incorrectDimensions' , ...\n 'Incorrect input dimensions.');\n end\n if (size(vert,2)~= +2 || ...\n size(conn,2)~= +2 || ...\n size(tria,2)~= +3 || ...\n size(tnum,2)~= +1 || ...\n size(tria,1)~= size(tnum,1) )\n error('tridiv2:incorrectDimensions' , ...\n 'Incorrect input dimensions.');\n end\n\n nvrt = size(vert,1) ;\n\n%---------------------------------------------- basic checks\n if (min(min(conn(:,1:2))) < +1 || ...\n max(max(conn(:,1:2))) > nvrt )\n error('tridiv2:invalidInputs', ...\n 'Invalid EDGE input array.') ;\n end\n \n if (min(min(tria(:,1:3))) < +1 || ...\n max(max(tria(:,1:3))) > nvrt )\n error('tridiv2:invalidInputs', ...\n 'Invalid TRIA input array.') ;\n end\n\n%------------------------------ assemble extended adj. info.\n [edge,tria] = tricon2(tria,conn) ;\n\n ediv = false(size(edge,1),1) ;\n ediv(tria(tdiv,4:6)) = true ;\n\n snum = length(find(ediv));\n\n while (true)\n\n %-------------------------- tria's with >= 2 edge splits\n div3 = sum(double( ...\n ediv(tria(:,4:6))),2)>=2;\n \n %-------------------------- expand onto adj. edge splits\n ediv(tria(div3,4:6)) = true ; \n \n snew = length(find(ediv)) ;\n \n if (snew == snum), break; end\n \n snum = snew ;\n \n end\n\n%------------------------------ tria's with == 1 edge splits\n div1 = sum( ...\n double( ediv(tria(:,4:6))),2)==1;\n\n%------------------------------ indexing for mid-point vert.\n ivec = zeros(size(edge,1),1);\n ivec(ediv) = ...\n (1:snum)' + size(vert,1);\n\n%------------------------------------------ update vert. set\n emid = vert(edge(ediv,1),:) ...\n + vert(edge(ediv,2),:) ;\n vert =[vert ; emid * 0.5] ;\n \n%------------------------------------------ update edge. set\n [cvec,eloc] = ...\n setset2(conn,edge(ediv, 1:2)) ;\n \n epos = ivec(ediv);\n epos = epos(eloc(eloc>0)) ;\n \n conn = [conn(~cvec,1:2) ; ...\n conn(cvec,1) , epos ; ...\n conn(cvec,2) , epos ] ;\n \n%------------------------------------ push 1-to-4 refinement \n tr41 = ones(length(find(div3)),3) ;\n tn41 = ones(length(find(div3)),1) ;\n tn41(:,1) = tnum(div3,1);\n tr41(:,1) = tria(div3,1);\n tr41(:,2) = ivec(tria(div3,4));\n tr41(:,3) = ivec(tria(div3,6));\n \n tr42 = ones(length(find(div3)),3) ;\n tn42 = ones(length(find(div3)),1) ;\n tn42(:,1) = tnum(div3,1);\n tr42(:,1) = ivec(tria(div3,4));\n tr42(:,2) = tria(div3,2);\n tr42(:,3) = ivec(tria(div3,5));\n \n tr43 = ones(length(find(div3)),3) ;\n tn43 = ones(length(find(div3)),1) ;\n tn43(:,1) = tnum(div3,1);\n tr43(:,1) = ivec(tria(div3,6));\n tr43(:,2) = ivec(tria(div3,5));\n tr43(:,3) = tria(div3,3);\n \n tr44 = ones(length(find(div3)),3) ;\n tn44 = ones(length(find(div3)),1) ;\n tn44(:,1) = tnum(div3,1);\n tr44(:,1) = ivec(tria(div3,6));\n tr44(:,2) = ivec(tria(div3,4));\n tr44(:,3) = ivec(tria(div3,5));\n \n%----------------------- push 1-to-2 refinement about edge 1\n tvec = false(size(tria,1), 1) ;\n tvec(ediv(tria(:,4))&div1) = true ;\n \n tr21 = ones(length(find(tvec)),3) ;\n tn21 = ones(length(find(tvec)),1) ;\n tn21(:,1) = tnum(tvec,1);\n tr21(:,1) = ivec(tria(tvec,4));\n tr21(:,2) = tria(tvec,3);\n tr21(:,3) = tria(tvec,1);\n \n tr22 = ones(length(find(tvec)),3) ;\n tn22 = ones(length(find(tvec)),1) ;\n tn22(:,1) = tnum(tvec,1);\n tr22(:,1) = ivec(tria(tvec,4));\n tr22(:,2) = tria(tvec,2);\n tr22(:,3) = tria(tvec,3);\n\n%----------------------- push 1-to-2 refinement about edge 2\n tvec = false(size(tria,1), 1) ;\n tvec(ediv(tria(:,5))&div1) = true ;\n \n tr23 = ones(length(find(tvec)),3) ;\n tn23 = ones(length(find(tvec)),1) ;\n tn23(:,1) = tnum(tvec,1);\n tr23(:,1) = ivec(tria(tvec,5));\n tr23(:,2) = tria(tvec,1);\n tr23(:,3) = tria(tvec,2);\n \n tr24 = ones(length(find(tvec)),3) ;\n tn24 = ones(length(find(tvec)),1) ;\n tn24(:,1) = tnum(tvec,1);\n tr24(:,1) = ivec(tria(tvec,5));\n tr24(:,2) = tria(tvec,3);\n tr24(:,3) = tria(tvec,1);\n \n%----------------------- push 1-to-2 refinement about edge 3\n tvec = false(size(tria,1), 1) ;\n tvec(ediv(tria(:,6))&div1) = true ;\n \n tr25 = ones(length(find(tvec)),3) ;\n tn25 = ones(length(find(tvec)),1) ;\n tn25(:,1) = tnum(tvec,1);\n tr25(:,1) = ivec(tria(tvec,6));\n tr25(:,2) = tria(tvec,2);\n tr25(:,3) = tria(tvec,3);\n \n tr26 = ones(length(find(tvec)),3) ;\n tn26 = ones(length(find(tvec)),1) ;\n tn26(:,1) = tnum(tvec,1);\n tr26(:,1) = ivec(tria(tvec,6));\n tr26(:,2) = tria(tvec,1);\n tr26(:,3) = tria(tvec,2);\n \n%------------------------------------------ update tria. set\n tria = [tria(~div1&~div3,1:3) ; ...\n tr41 ; tr42 ; tr43 ; tr44 ; ...\n tr21 ; tr22 ; \n tr23 ; tr24 ; \n tr25 ; tr26 ] ;\n \n tnum = [tnum(~div1&~div3,1:1) ; ...\n tn41 ; tn42 ; tn43 ; tn44 ; ...\n tn21 ; tn22 ; \n tn23 ; tn24 ; \n tn25 ; tn26 ] ;\n \nend\n\n\n\n", "meta": {"author": "CHLNDDEV", "repo": "OceanMesh2D", "sha": "56222604a5c1fe897d10c8b08cb3380ef8b43740", "save_path": "github-repos/MATLAB/CHLNDDEV-OceanMesh2D", "path": "github-repos/MATLAB/CHLNDDEV-OceanMesh2D/OceanMesh2D-56222604a5c1fe897d10c8b08cb3380ef8b43740/utilities/GEOM_UTIL/mesh-util/tridiv2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581510799253, "lm_q2_score": 0.7371581741774411, "lm_q1q2_score": 0.5434021567300961}} {"text": "function imb=regPutBorde(im,Nx,Ny,method);\n% regPutBorde - Puts a border to an image:\n%\tmethod=1 -> consider the image periodical\n%\tmethod=2 -> specular\n%\tmethod=3 -> repeat the edge pixel\n%\t\n%\timb = regPutBorde(im,Nx,Ny,method);\n%\n% ON - 10/96 (from putborde)\n% Oscar Nestares - 5/99 (renamed to regPutBorde)\n%\n\n[sy sx]=size(im);\nimb=zeros(sy+2*Ny,sx+2*Nx);\nimb(1+Ny:sy+Ny,1+Nx:sx+Nx)=im;\n\nif method == 1\n\timb(1:Ny,1+Nx:sx+Nx)=im(sy-Ny+1:sy,:);\n\timb(sy+Ny+1:sy+2*Ny,1+Nx:sx+Nx)=im(1:Ny,:);\n\timb(1+Ny:sy+Ny,1:Nx)=im(:,sx-Nx+1:sx);\n\timb(1+Ny:sy+Ny,sx+Nx+1:sx+2*Nx)=im(:,1:Nx);\n\timb(1:Ny,1:Nx)=im(sy-Ny+1:sy,sx-Nx+1:sx);\n\timb(1:Ny,sx+Nx+1:sx+2*Nx)=im(sy-Ny+1:sy,1:Nx);\n\timb(sy+Ny+1:sy+2*Ny,1:Nx)=im(1:Ny,sx-Nx+1:sx);\n\timb(sy+Ny+1:sy+2*Ny,sx+Nx+1:sx+2*Nx)=im(1:Ny,1:Nx);\nelseif method == 2\n\timb(Ny:-1:1,1+Nx:sx+Nx)=im(2:Ny+1,:);\n\timb(sy+2*Ny:-1:sy+Ny+1,1+Nx:sx+Nx)=im(sy-Ny:sy-1,:);\n\timb(1+Ny:sy+Ny,Nx:-1:1)=im(:,2:Nx+1);\n\timb(1+Ny:sy+Ny,sx+2*Nx:-1:sx+Nx+1)=im(:,sx-Nx:sx-1);\n\timb(Ny:-1:1,Nx:-1:1)=im(2:Ny+1,2:Nx+1);\n\timb(Ny:-1:1,sx+2*Nx:-1:sx+Nx+1)=im(2:Ny+1,sx-Nx:sx-1);\n\timb(sy+2*Ny:-1:sy+Ny+1,Nx:-1:1)=im(sy-Ny:sy-1,2:Nx+1);\n\timb(sy+2*Ny:-1:sy+Ny+1,sx+2*Nx:-1:sx+Nx+1)=im(sy-Ny:sy-1,sx-Nx:sx-1);\nelseif method==3\n\tfor k=1:Nx\n\t\timb(Ny+1:sy+Ny,k)=im(:,1);\n\t\timb(Ny+1:sy+Ny,k+sx+Nx)=im(:,sx);\n\tend\n\tfor k=1:Ny\n\t\timb(k,Nx+1:sx+Nx)=im(1,:);\n\t\timb(k+sy+Ny,Nx+1:sx+Nx)=im(sy,:);\n\tend\nelse\n\terror('Not a valid value for method')\nend\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrAlign/registrationOscar/regPutBorde.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.5433168597574229}} {"text": "function colors = distinguishable_colors(n_colors, bg, func)\n% DISTINGUISHABLE_COLORS: pick colors that are maximally perceptually distinct\n%\n% When plotting a set of lines, you may want to distinguish them by color.\n% By default, Matlab chooses a small set of colors and cycles among them,\n% and so if you have more than a few lines there will be confusion about\n% which line is which. To fix this problem, one would want to be able to\n% pick a much larger set of distinct colors, where the number of colors\n% equals or exceeds the number of lines you want to plot. Because our\n% ability to distinguish among colors has limits, one should choose these\n% colors to be \"maximally perceptually distinguishable.\"\n%\n% This function generates a set of colors which are distinguishable\n% by reference to the \"Lab\" color space, which more closely matches\n% human color perception than RGB. Given an initial large list of possible\n% colors, it iteratively chooses the entry in the list that is farthest (in\n% Lab space) from all previously-chosen entries. While this \"greedy\"\n% algorithm does not yield a global maximum, it is simple and efficient.\n% Moreover, the sequence of colors is consistent no matter how many you\n% request, which facilitates the users' ability to learn the color order\n% and avoids major changes in the appearance of plots when adding or\n% removing lines.\n%\n% Syntax:\n% colors = distinguishable_colors(n_colors)\n% Specify the number of colors you want as a scalar, n_colors. This will\n% generate an n_colors-by-3 matrix, each row representing an RGB\n% color triple. If you don't precisely know how many you will need in\n% advance, there is no harm (other than execution time) in specifying\n% slightly more than you think you will need.\n%\n% colors = distinguishable_colors(n_colors,bg)\n% This syntax allows you to specify the background color, to make sure that\n% your colors are also distinguishable from the background. Default value\n% is white. bg may be specified as an RGB triple or as one of the standard\n% \"ColorSpec\" strings. You can even specify multiple colors:\n% bg = {'w','k'}\n% or\n% bg = [1 1 1; 0 0 0]\n% will only produce colors that are distinguishable from both white and\n% black.\n%\n% colors = distinguishable_colors(n_colors,bg,rgb2labfunc)\n% By default, distinguishable_colors uses the image processing toolbox's\n% color conversion functions makecform and applycform. Alternatively, you\n% can supply your own color conversion function.\n%\n% Example:\n% c = distinguishable_colors(25);\n% figure\n% image(reshape(c,[1 size(c)]))\n%\n% Example using the file exchange's 'colorspace':\n% func = @(x) colorspace('RGB->Lab',x);\n% c = distinguishable_colors(25,'w',func);\n\n% Copyright 2010-2011 by Timothy E. Holy\n\n% Parse the inputs\nif (nargin < 2)\n bg = [1 1 1]; % default white background\nelse\n if iscell(bg)\n % User specified a list of colors as a cell aray\n bgc = bg;\n for i = 1:length(bgc)\n bgc{i} = parsecolor(bgc{i});\n end\n bg = cat(1,bgc{:});\n else\n % User specified a numeric array of colors (n-by-3)\n bg = parsecolor(bg);\n end\nend\n\n% Generate a sizable number of RGB triples. This represents our space of\n% possible choices. By starting in RGB space, we ensure that all of the\n% colors can be generated by the monitor.\nn_grid = 30; % number of grid divisions along each axis in RGB space\nx = linspace(0,1,n_grid);\n[R,G,B] = ndgrid(x,x,x);\nrgb = [R(:) G(:) B(:)];\nif (n_colors > size(rgb,1)/3)\n error('You can''t readily distinguish that many colors');\nend\n\n% Convert to Lab color space, which more closely represents human\n% perception\nif (nargin > 2)\n lab = func(rgb);\n bglab = func(bg);\nelse\n C = makecform('srgb2lab');\n lab = applycform(rgb,C);\n bglab = applycform(bg,C);\nend\n\n% If the user specified multiple background colors, compute distances\n% from the candidate colors to the background colors\nmindist2 = inf(size(rgb,1),1);\nfor i = 1:size(bglab,1)-1\n dX = bsxfun(@minus,lab,bglab(i,:)); % displacement all colors from bg\n dist2 = sum(dX.^2,2); % square distance\n mindist2 = min(dist2,mindist2); % dist2 to closest previously-chosen color\nend\n\n% Iteratively pick the color that maximizes the distance to the nearest\n% already-picked color\ncolors = zeros(n_colors,3);\nlastlab = bglab(end,:); % initialize by making the \"previous\" color equal to background\nfor i = 1:n_colors\n dX = bsxfun(@minus,lab,lastlab); % displacement of last from all colors on list\n dist2 = sum(dX.^2,2); % square distance\n mindist2 = min(dist2,mindist2); % dist2 to closest previously-chosen color\n [~,index] = max(mindist2); % find the entry farthest from all previously-chosen colors\n colors(i,:) = rgb(index,:); % save for output\n lastlab = lab(index,:); % prepare for next iteration\nend\n\n\n\n%-------------------------------------------------------------------------\nfunction c = parsecolor(s)\nif ischar(s)\n c = colorstr2rgb(s);\nelseif isnumeric(s) && size(s,2) == 3\n c = s;\nelse\n error('MATLAB:InvalidColorSpec','Color specification cannot be parsed.');\nend\n\n\n\n\n%-------------------------------------------------------------------------\nfunction c = colorstr2rgb(c)\n% Convert a color string to an RGB value.\n% This is cribbed from Matlab's whitebg function.\n% Why don't they make this a stand-alone function?\nrgbspec = [1 0 0;0 1 0;0 0 1;1 1 1;0 1 1;1 0 1;1 1 0;0 0 0];\ncspec = 'rgbwcmyk';\nk = find(cspec==c(1));\nif isempty(k)\n error('MATLAB:InvalidColorString','Unknown color string.');\nend\nif k~=3 || length(c)==1,\n c = rgbspec(k,:);\nelseif length(c)>2,\n if strcmpi(c(1:3),'bla')\n c = [0 0 0];\n elseif strcmpi(c(1:3),'blu')\n c = [0 0 1];\n else\n error('MATLAB:UnknownColorString', 'Unknown color string.');\n end\nend\n", "meta": {"author": "BUNPC", "repo": "Homer3", "sha": "d0fac4b22d1069eaa5cba268a225eb117ddcdca1", "save_path": "github-repos/MATLAB/BUNPC-Homer3", "path": "github-repos/MATLAB/BUNPC-Homer3/Homer3-d0fac4b22d1069eaa5cba268a225eb117ddcdca1/Utils/Shared/distinguishable_colors.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.7090191214879992, "lm_q1q2_score": 0.5433168456226456}} {"text": "function [ element_node, element_att ] = triangle_element_data_example ( ...\n element_num, element_order, element_att_num )\n\n%*****************************************************************************80\n%\n%% TRIANGLE_ELEMENT_DATA_EXAMPLE returns the element information for the example.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 10 October 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer ELEMENT_NUM, the number of elements.\n%\n% Input, integer ELEMENT_ORDER, the order of the elements.\n%\n% Input, integer ELEMENT_ATT_NUM, the number of element \n% attributes.\n%\n% Output, integer ELEMENT_NODE(ELEMENT_ORDER,ELEMENT_NUM), \n% the indices of the nodes that make up each element.\n%\n% Output, real ELEMENT_ATT(ELEMENT_ATT_NUM,ELEMENT_NUM), \n% the attributes of each element.\n%\n element_att = [];\n\n element_node = [ ...\n 1, 2, 6; ...\n 7, 6, 2; ...\n 2, 3, 7; ...\n 8, 7, 3; ...\n 3, 4, 8; ...\n 9, 8, 4; ...\n 4, 5, 9; ...\n 10, 9, 5; ...\n 6, 7, 11; ...\n 12, 11, 7; ...\n 7, 8, 12; ...\n 13, 12, 8; ...\n 8, 9, 13; ...\n 14, 13, 9; ...\n 9, 10, 14; ...\n 15, 14, 10; ...\n 11, 12, 16; ...\n 17, 16, 12; ...\n 12, 13, 17; ...\n 18, 17, 13; ...\n 16, 17, 19; ...\n 20, 19, 17; ...\n 17, 18, 20; ...\n 21, 20, 18 ]';\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/triangle_io/triangle_element_data_example.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743168019989179, "lm_q2_score": 0.731058584489497, "lm_q1q2_score": 0.5432993607311515}} {"text": "% Digital circuit sizing example (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%\n% Solves the problem of choosing gate scale factors x_i to give\n% minimum ckt delay, subject to limits on the total area and power.\n% Uses max gate arrival time T formulation that avoids evaluation\n% of the delay over all paths in the circuit.\n%\n% minimize T_bar\n% s.t. T_j <= T_bar for j an output gate\n% T_j + d_i <= T_i for j in FI(i)\n% P <= Pmax, A <= Amax\n% x >= 1\n%\n% where variables are x and T.\n%\n% We use the circuit topology presented in figure 1 (page 902),\n% where we take gates 1, 3 and 6 to be inverters (INV),\n% gates 2 and 7 to be three input NANDs (NAND3),\n% and gates 4 and 5 to be two input NORs (NOR2).\n\n%********************************************************************\n% user specified data (specify problem constant and ckt topology)\n%********************************************************************\nm = 7; % number of gates\nVdd = 5; % supply voltage\nAmax = 250; % maximum area spec\n\n% gate specs\nINV = struct('Cin',3, 'Cint',3, 'Rdrv',0.48, 'A',3, 'Ileak',0.006);\nNAND3 = struct('Cin',4, 'Cint',6, 'Rdrv',0.48, 'A',8, 'Ileak',0.007);\nNOR2 = struct('Cin',5, 'Cint',6, 'Rdrv',0.48, 'A',10, 'Ileak',0.009);\n\nclear gates;\ngates([1 3 6]) = INV;\ngates([2 7]) = NAND3;\ngates([4 5]) = NOR2;\n\n% primary inputs and primary outputs labels (start with m+1)\nprimary_inputs = [8 9 10];\nprimary_outputs = [11 12];\nM = m + length( primary_inputs ) + length( primary_outputs );\n\n% fan-in cell array\nFI = cell(M,1);\nFI{1} = 8;\nFI{2} = [8 9 10];\nFI{3} = 10;\nFI{4} = [1 2];\nFI{5} = [2 3];\nFI{6} = 4;\nFI{7} = [3 4 5];\nFI{8} = [];\nFI{9} = [];\nFI{10} = [];\nFI{11} = 6;\nFI{12} = 7;\n\n% primary output has Cin capacitance (but has no Cload)\nCin_po = sparse(M,1);\nCin_po(primary_outputs) = [10 10];\n\n% primary input has Cload capacitance (but has no Cin)\nCload_pi = sparse(M,1);\nCload_pi(primary_inputs) = [10 10 10];\n\n% activity frequency of gates and primary inputs\nf_gates = 0.001*ones(m,1);\nf_pi = sparse(M,1);\nf_pi(primary_inputs) = 0.001*[10 10 10];\n\n%********************************************************************\n% derived problem data (computed from user inputs)\n%********************************************************************\n% fan-out cell array (compute it from the fan-in cell array)\nFO = cell(M,1);\nfor gate = [1:m primary_outputs]\n preds = FI{gate};\n for k = 1:length(preds)\n FO{preds(k)}(end+1) = gate;\n end\nend\n\n% input and internal capacitance of gates, and driving resistance\nCin_norm = [gates.Cin]';\nCint_norm = [gates.Cint]';\nRdrv_norm = [gates.Rdrv]';\n\n% area specification for each gate with unit scaling\nA_norm = [gates.A]';\n\n% leakage current of gate i with unit scaling\nIleak_norm = [gates.Ileak]';\n\n%********************************************************************\n% optimization (with tradeoff curve generation)\n%********************************************************************\n% objective is the upper bound on the overall delay\n% and that is the max of arrival times for output gates\noutput_gates = [FI{primary_outputs}];\n\n% varying parameters for the tradeoff curve\nN = 25;\nPmax = linspace(10,20,N);\nmin_delay = zeros(N,1);\ndisp('Generating the optimal tradeoff curve...')\nfor n = 1:N\n fprintf('Pmax = %6.2f: ',Pmax(n));\n cvx_begin gp quiet\n % optimization variables\n variable x(m) % scale factor\n variable T(m) % arrival times\n\n % input capacitance is an affine function of sizes\n Cin = Cin_norm.*x;\n Cint = Cint_norm.*x;\n\n % driving resistance is inversily proportional to sizes\n R = Rdrv_norm./x;\n\n % gate delay is the product of its driving resistance and load cap.\n Cload = cvx( zeros(m,1) );\n for gate = 1:m\n if ~ismember( FO{gate}, primary_outputs )\n Cload(gate) = sum( Cin(FO{gate}) );\n else\n Cload(gate) = Cin_po( FO{gate} );\n end\n end\n\n % delay\n D = 0.69*ones(m,1).*R.*( Cint + Cload );\n\n % total area\n area = A_norm'*x;\n\n % total power calculation\n Pdyn = Vdd^2*sum( f_pi(primary_inputs).*Cload_pi(primary_inputs) ) + ...\n Vdd^2*(f_gates'*(Cint + Cload));\n Pstat = Vdd*Ileak_norm'*x;\n power = Pdyn + Pstat;\n\n minimize( max( T(output_gates) ) )\n subject to\n % constraints\n x >= 1; %#ok\n area <= Amax; %#ok\n power <= Pmax(n); %#ok\n\n % create timing constraints\n for gate = 1:m\n if ~ismember( FI{gate}, primary_inputs )\n for j = FI{gate}\n % enforce T_j + D_j <= T_i over all gates j that drive i\n D(gate) + T(j) <= T(gate); %#ok\n end\n else\n % enforce D_i <= T_i for gates i connected to primary inputs\n D(gate) <= T(gate); %#ok\n end\n end\n cvx_end\n fprintf( 'delay = %3.2f\\n', cvx_optval );\n min_delay(n) = cvx_optval;\nend\n\n% plot the tradeoff curve\nfigure, clf\nplot(Pmax,min_delay);\nxlabel('Pmax'); ylabel('Dmin');\ntitle(['Tradeoff curve for Amax = ' num2str(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/dig_ckt_sizing.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8080671950640465, "lm_q2_score": 0.672331705744791, "lm_q1q2_score": 0.543289195613819}} {"text": "function [soln,eqn,info] = DivCurl3PDWG(node,elem,bdFlag,pde,option,varargin)\n%% DivCurl3PDWG div-curl system equation: \n% primal-dual weak-Galerkin in 3-D to solve the following system.\n% div(epsilon*u)=f in \\Omega, \n% curl(u) = g in \\Omega, \n% Dirichlet boundary condition epsilon*u \\cdot n =g_n on \\Gamma_0, \n%\n% The code is vectorized with no loops. Data structure follows iFEM tradition.\n%\n% Reference: A New Numerical Method for Div-Curl Systems with Low Regularity Assumptions\n% S. Cao, C. Wang, J. Wang, https://arxiv.org/abs/2101.03466\n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details.\n\nif ~exist('option','var'), option = []; end\nif ~isfield(option,'inverseh'), option.inverseh = true; end\nif ~isfield(option,'dquadorder'), option.dquadorder = 3; end\n\n[lambda,w] = quadpts3(option.dquadorder); % quadrature order is 1 or 2\nnQuad = size(lambda,1);\n\nif ~exist('bdFlag','var')\n bdFlag = setboundary3(node,elem,'Dirichlet');\nend\n\n\n%% Mesh related geometric quantities\n\n% local edge to face indices, first two edges' local indices on a face\nloc_e2f = [4 5; 2 3; 1 3; 1 2];\n% local face to vertices indices, positive oriented\nloc_f2v = [2 3 4; 1 4 3; 1 2 4; 1 3 2];\n\nloc_e2v = [1 2; 1 3; 1 4; 2 3; 2 4; 3 4];\n\n[elem2face,face] = dof3face(elem);\nNT = size(elem,1);\nNF = size(face,1); \nelem2intdof = reshape(1:3*NT, 3, NT)';\n\n[Dphi,volume] = gradbasis3(node,elem);\n\nhK = (6*volume).^(1/3);\n\nelem2ve = zeros(NT,3,6);\nfor e = 1:6 % six edges\n elem2ve(:,:,e) = node(elem(:,loc_e2v(e,2)),:)-node(elem(:,loc_e2v(e,1)),:);\nend\n\nelem2ve = elem2ve./repmat(sqrt(sum(elem2ve.^2,2)),1,3); % normalize for basis\n\nfaceNormal = cross(node(face(:,2),:) - node(face(:,1),:),...\n node(face(:,3),:) - node(face(:,2),:),2);\nfaceArea = 0.5*sqrt(sum(faceNormal.^2,2));\nfaceArea2elem = faceArea(elem2face);\nfaceArea2elemTotal = sum(faceArea2elem,2);\n\ncenter = (node(elem(:,1),:) + node(elem(:,2),:) + ...\n node(elem(:,3),:) + node(elem(:,4),:))/4;\n\n\n%% permeability tensor\nt = cputime; % record assembling time\n\nif ~isfield(pde,'Eps'), pde.Eps = []; end\n\nif ~isempty(pde.Eps) && isnumeric(pde.Eps)\n Eps2elem = repmat(pde.Eps, [1,1,NT]); % Eps is a constant matrix\n Eps2elem = permute(Eps2elem,[3,1,2]); % switch the element idx to the 1st dim\nend\n\nif ~isempty(pde.Eps) && ~isnumeric(pde.Eps)\n Eps2elem = zeros(NT,3,3); %#ok\n % Eps2elem is a NTx3x3 array so that Eps2elem(i,:,:) is the tensor at the\n % center of i-th element\n Epstmp = arrayfun(@(rowidx) pde.Eps(center(rowidx,:)), ...\n 1:size(center,1), 'UniformOutput',0);\n Eps2elem = cat(3,Epstmp{:});\n Eps2elem = permute(Eps2elem,[3,1,2]); % switch the element idx to the 1st dim\nend\n\n%% compute eps \\nabla_w phi\nEpsDphi = zeros(NT,3,4); \nfor i = 1:4\n EpsDphi(:,:,i) = sum(bsxfun(@times, Eps2elem, Dphi(:,:,i)), 2);\nend\n\n%% assembling\n% DoF order: # of Dofs\n% \\lambda_h: NT + NF, local 1+4\n% u_h: 3*NT\n% s_h: s_0 + s_b; NT + NF (simply-connected case), local 1+4\n% q_h: q_0 + q_b; 3*NT + 2*NF (for H(curl) vector field)\n% assembling indices following locally within each group\n\n%% equation 1 for u_h and lambda_h\n\nblockUlambda = sparse(4*NT+NF,4*NT+NF); %#ok\n% (u_h, \\epsilon\\nabla_w phi)\n% + \\sum h_T^{-1} <\\lambda_0 - \\lambda_b, \\varphi_0 - \\varphi_b>_{boundary T}\n\n%% (u_h, \\epsilon\\nabla_w phi_{face})\n% locally the basis for P_0(T)^3 is edge [1, 2], [1, 3], and [1, 4]\n% size (NT+NF, 3*NT)\nC = sparse(NF,3*NT); %(u_h, \\epsilon\\nabla_w phi_{face})\n\nfor j = 1:3 % constant vector space spanned by 3 edge vectors\n for i = 1:4 % face 1 to 4\n % Cij = (q_j, eps \\nabla_w \\phi_{F_i})\n % \\nabla_w \\phi_{F_i} = -3\\nabla \\phi_i\n \n Cij = dot(elem2ve(:,:,j),-3*EpsDphi(:,:,i),2).*volume;\n \n ii = double(elem2face(:,i));\n jj = elem2intdof(:,j);\n C = C + sparse(ii,jj,Cij,NF,3*NT);\n end\nend\n\nUgradphi = [sparse(NT, 3*NT); C];\n\n\n%% \\sum h_T^{-1} <\\lambda_0 - \\lambda_b, \\varphi_0 - \\varphi_b>_{boundary T}\n% this is essetially a mass matrix stab\nStab_Mh = sparse(NT+NF,NT+NF); %#ok\n\nL0ij = faceArea2elemTotal./hK;\nLambda00 = sparse(1:NT, 1:NT, L0ij, NT, NT); %% <\\lambda_0, \\lambda_0>\n\nLambda0b = sparse(NT, NF); %% <\\lambda_b, \\lambda_0>\nLambdabb = sparse(NF, NF); %% <\\lambda_b, \\lambda_b>\nfor j = 1:4 % face 1 to 4\n jj = double(elem2face(:,j));\n Lbj = faceArea2elem(:,j)./hK; % = <\\lambda_{F_j}, \\lambda_0>\n Lambda0b = Lambda0b + sparse(1:NT, jj, Lbj, NT, NF);\n Lambdabb = Lambdabb + sparse(jj, jj, Lbj, NF, NF);\nend\n\nStab_Mh = [Lambda00 -Lambda0b; -Lambda0b' Lambdabb]; \n% Stablization on M_h should have null space dimension 1 (global constant)\n\n%% \\sum h_T _{boundary T}\n\nStab_Sh = sparse(NT+NF,NT+NF); %#ok\n\nS0ij = faceArea2elemTotal.*hK;\nS00 = sparse(1:NT, 1:NT, S0ij, NT, NT); %% \n\n\nSb0 = sparse(NT, NF); %% \nSbb = sparse(NF, NF); %% \nfor j = 1:4 % face 1 to 4\n jj = double(elem2face(:,j));\n Sbj = faceArea2elem(:,j).*hK; % = <\\lambda_{F_j}, \\lambda_0>\n Sb0 = Sb0 + sparse(1:NT, jj, Sbj, NT, NF);\n Sbb = Sbb + sparse(jj, jj, Sbj, NF, NF);\nend\n\nStab_Sh = [S00 -Sb0; -Sb0' Sbb]; \n% Stablization on s_h should have null space dimension 1 (global constant)\n\n%% Equation 1 for u_h and q_h = {q_0, q_b}\n\n%% (u_h, \\epsilon\\nabla_w \\times psi_{face})\n% locally the basis for P_0(T)^3 is the edge vector representing \n% the edge [1, 2], [1, 3], and [1, 4] (local indexing of iFEM tradition)\n% locally the basis for the tangential component are \n% the edge 1 and 2 vectors for the triangular face (local indexing on this face)\n% size: (3*NT+2*NF, 3*NT)\n\nD = sparse(2*NF,3*NT); \n%(u_h, \\nabla_w \\times psi_{face}) with 2 basis vec at each face\n\nfor i = 1:4 % face 1 to 4\n for j = 1:3 % constant vector space spanned by 3 edge vectors\n for e = 1:2 % two basis vectors on each face\n % Dije = (q_j, eps \\nabla_w \\times \\psi_{F_i,e})\n % \\nabla_w \\times [0, \\psi_{F_i}] =\n % (rotation of \\psi_{F_i} counter-clockwise by pi/2)*|F_i|/|K|\n % = 3 \\psi_{F_i} \\times \\nabla phi_i\n \n curlpsiFe = 3*mycross(elem2ve(:,:,loc_e2f(i,e)), Dphi(:,:,i));\n Dije = dot(elem2ve(:,:,j),curlpsiFe,2).*volume;\n \n % k-th (global face indexing) face has 2 DoFs in W_h: 2k-1, and 2k\n ii = 2*double(elem2face(:,i)) - e + 1;\n jj = elem2intdof(:,j);\n D = D + sparse(ii,jj, Dije, 2*NF,3*NT);\n end\n end\nend\n\nUcurlpsi = [sparse(3*NT, 3*NT); D];\n\n%% (\\psi, \\epsilon\\nabla_w s_h)\nPsigrads = sparse(3*NT+2*NF, NT+NF);\n\n\nE = sparse(3*NT,NF);\nfor i = 1:3 % constant vector space spanned by 3 edge vectors W_{h,0} \n for j = 1:4 % face 1 to 4\n % Eij = (\\psi_{K,i}, eps \\nabla_w \\phi_{F_j})\n % \\nabla_w \\phi_{F_j} = -3\\nabla \\phi_j\n \n Eij = dot(elem2ve(:,:,i),-3*EpsDphi(:,:,j),2).*volume;\n \n ii = elem2intdof(:,i);\n jj = double(elem2face(:,j));\n E = E + sparse(ii,jj,Eij,3*NT,NF);\n end\nend\n\n%%% E is C's transpose, the code above is for booking-keeping\nE = C';\nPsigrads(1:3*NT,NT+1:end) = E;\n\n%% \\sum h_T^{-1} <(q_0-q_b)\\times n, (\\psi_0-\\psi_b)\\times n>_{boundary T}\n\n\n% \\sum h_T^{-1} _{boundary T}\nWS00 = sparse(3*NT, 3*NT);\nfor i = 1:3 % constant vector space spanned by 3 edge vectors W_{h,0} \n for j = 1:3 % constant vector space spanned by 3 edge vectors W_{h,0} \n S00ijface = 0;\n for f = 1:4\n psi0crossn = mycross(elem2ve(:,:,i), Dphi(:,:,f)); % test\n q0crossn = mycross(elem2ve(:,:,j), Dphi(:,:,f)); % trial\n \n S00ijface = S00ijface + 9*dot(q0crossn,psi0crossn,2)...\n .*volume.^2./faceArea2elem(:,f);\n end\n S00ijface = S00ijface./hK;\n ii = elem2intdof(:,i);\n jj = elem2intdof(:,j);\n WS00 = WS00 + sparse(ii,jj,S00ijface,3*NT, 3*NT);\n end\nend\n\n% \\sum h_T^{-1} _{boundary T}\nWSb0 = sparse(3*NT, 2*NF);\nfor i = 1:3 % constant vector space spanned by 3 edge vectors W_{h,0} \n for j = 1:4 % 4 face for W_{h,b} each basis has support only on F_j\n for e = 1:2 % each face has 2 DoFs\n psi0crossn = mycross(elem2ve(:,:,i), Dphi(:,:,j)); % test\n qbcrossn = mycross(elem2ve(:,:,loc_e2f(j,e)), Dphi(:,:,j)); % trial\n \n Sb0ijface = 9*dot(qbcrossn,psi0crossn,2)...\n .*volume.^2./faceArea2elem(:,j)./hK;\n \n ii = elem2intdof(:,i);\n % k-th (global face indexing) face has 2 DoFs\n jj = 2*double(elem2face(:,j)) - e + 1;\n WSb0 = WSb0 + sparse(ii,jj,Sb0ijface,3*NT,2*NF);\n end\n end\nend\n\n% \\sum h_T^{-1} _{boundary T}\nWSbb = sparse(2*NF, 2*NF);\nfor f = 1:4 \n % this term is non-zero only when both trial and test\n % are associated with the same face\n for i = 1:2 % each face has 2 DoFs\n for j = 1:2\n psibcrossn = mycross(elem2ve(:,:,loc_e2f(f,i)), Dphi(:,:,f));\n qbcrossn = mycross(elem2ve(:,:,loc_e2f(f,j)), Dphi(:,:,f));\n \n Sbbijface = 9*dot(qbcrossn,psibcrossn,2)...\n .*volume.^2./faceArea2elem(:,f)./hK;\n \n % k-th (global face indexing) face has 2 DoFs\n ii = 2*double(elem2face(:,f)) - i + 1;\n jj = 2*double(elem2face(:,f)) - j + 1;\n WSbb = WSbb + sparse(ii,jj,Sbbijface,2*NF,2*NF);\n end\n end\nend\n\nStab_Wh = [WS00 -WSb0; -WSb0' WSbb]; \n% Stab_Wh should have null space dimension \n% = span{gradient of continuous P_1 Langrange} = # node -1\n\n%% overall stiffness matrix for the system\nblockUlambda = [Stab_Mh Ugradphi; Ugradphi' sparse(3*NT,3*NT)];\nblockOffDiag = sparse(4*NT+3*NF, 4*NT+NF); \nblockOffDiag(NT+NF+1:end, NT+NF+1:end) = Ucurlpsi;\nblockQs = [-Stab_Sh Psigrads'; Psigrads Stab_Wh];\nbigA = [blockUlambda blockOffDiag'; blockOffDiag blockQs];\n\n%% right hand sides\n\n%% -(f,\\varphi_0)\nft = zeros(NT,1);\n\nfor p = 1:nQuad\n\t\t% quadrature points in the x-y-z coordinate\n\t\tpxyz = 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 + lambda(p,4)*node(elem(:,4),:);\n\t\tfp = pde.f(pxyz);\n ft = ft + w(p)*fp;\nend\n\nFphi0 = -accumarray((1:NT)',ft.*volume,[NT 1]);\n\n%% \\sum_{T} _{\\partial T} near \\partial \\Omega\nGNphib = zeros(NF,1); % _{\\partial T}\n% update: face quadorder increased\n\nif ~isfield(option,'gNquadorder')\n option.gNquadorder = 5; % default order exact for linear gN\nend\n[lambdagN, weightgN] = quadpts(option.gNquadorder); % linear bases\nnQuadgN = size(lambdagN,1);\n\nfor i = 1:4 % 4 faces\n idxBdElem = find(bdFlag(:,i) > 0); % if an element has a boundary face \n\n if ~isempty(idxBdElem)\n bdNormal = -3*repmat(volume(idxBdElem,:),1,3).*Dphi(idxBdElem,:,:); \n % scaled normal with face area built-in\n loc_face = loc_f2v(i,:);\n \n EpsUdotN = zeros(size(idxBdElem,1),1);\n \n for pp = 1:nQuadgN\n % quadrature points in the x-y coordinate\n ppxyz = lambdagN(pp,1)*node(elem(idxBdElem,loc_face(1)),:) ...\n + lambdagN(pp,2)*node(elem(idxBdElem,loc_face(2)),:) ...\n + lambdagN(pp,3)*node(elem(idxBdElem,loc_face(3)),:);\n \n \n u_bd = pde.exactu(ppxyz);\n EpsU = sum(bsxfun(@times, Eps2elem(idxBdElem,:,:), u_bd), 2);\n EpsUdotN = EpsUdotN + ...\n weightgN(pp)*dot(squeeze(EpsU), bdNormal(:,:,i), 2);\n \n end\n \n GNphib = GNphib + accumarray(elem2face(idxBdElem,i), EpsUdotN, [NF 1]);\n end\nend\n\n%% (g, \\psi_0)\nGpsi0 = zeros(3*NT,1);\n\nfor i = 1:3 % 3 vector basis on each element for \\psi_0\n gtpsi0 = zeros(NT,1);\n for p = 1:nQuad\n % quadrature points in the x-y-z coordinate\n pxyz = lambda(p,1)*node(elem(:,1),:) ...\n + lambda(p,2)*node(elem(:,2),:) ...\n + lambda(p,3)*node(elem(:,3),:) ...\n + lambda(p,4)*node(elem(:,4),:);\n gp = pde.g(pxyz);\n \n gtpsi0 = gtpsi0 + w(p)*dot(gp, elem2ve(:,:,i), 2);\n end\n \n Gpsi0 = Gpsi0 + accumarray(elem2intdof(:,i), gtpsi0.*volume, [3*NT 1]);\nend\n%% RHS\nRhs = [Fphi0; GNphib]; % test: phi_0, phi_b\nRhs = [Rhs; zeros(3*NT, 1)]; % test: v\nRhs = [Rhs; zeros(NT, 1)]; % test: r_0\nRhs = [Rhs; zeros(NF, 1)]; % test: r_b\nRhs = [Rhs; Gpsi0]; % test: psi_0\nRhs = [Rhs; zeros(2*NF, 1)]; % test: psi_b\n\n%% set up free dof\n% DoF order: # of Dofs\n% prefix with \"idx\": global indices\n% the DoF variable itself is boolean (fastest on MATLAB)\n% \\lambda_h: NT + NF, local 1+4 (no BC)\n% u_h: 3*NT (no BC)\n% s_h: s_0 + s_b; NT + NF (simply-connected case), s_b = 0 on Gamma_0\n% q_h: q_0 + q_b; 3*NT + 2*NF (for H(curl) vector field) q_b\\cross n =0\n% assembling indices following locally within each group\n\nisBdFace = false(NF,1);\nisBdFace(elem2face(bdFlag(:) > 0)) = true;\nidxBdFace = find(isBdFace);\nidxBdFaceVec = [2*idxBdFace-1 2*idxBdFace]';\nidxBdFaceVec = idxBdFaceVec(:);\n\nfreeDof = true(8*NT+4*NF,1);\nidxBdSb = idxBdFace + 5*NT+NF; % boundary DoF indices for s_b\nidxBdQb = idxBdFaceVec + 8*NT+2*NF; % boundary DoF indices for q_b\n\n\n%%%%% fixing 1 in lambda_0 is enough, the others are optional %%%%%\n%%% current config according to the paper: fixing 1 in lambda_0\n%%% bd dofs of s and q\nfreeDof([1; idxBdSb; idxBdQb]) = false; \n\n%%%%% fixing bd dofs for q\n% freeDof([1; idxBdQb]) = false; \n\n%%%%% fixing bd dofs for s\n% freeDof([1; idxBdSb]) = false;\n\nidxIntBdFace = [];\n% old way of handling cavity (second betti number not zero)\nif any(elem2face(bdFlag(:) == 2)) && false \n disp('Modifying cavity dofs')\n isIntBdFace = false(NF,1);\n isIntBdFace(elem2face(bdFlag(:) == 2)) = true;\n idxIntBdFace = find(isIntBdFace);\n idxIntBdSb = idxIntBdFace + 5*NT+NF; % boundary DoF indices for s_b on cavity\n freeDof(idxIntBdSb) = true;\nend\n\n%% Record assembling time\nassembleTime = cputime - t;\nif ~isfield(option,'printlevel'), option.printlevel = 1; end\nif option.printlevel >= 2\n fprintf('Time to assemble matrix equation %4.2g s\\n',assembleTime);\nend\n\n%% direct solve\nNDof = 8*NT+4*NF;\n\nbigSoln = zeros(NDof,1);\n\n[~,sys] = memory;\nif sum(freeDof) > 2e6 && sys.PhysicalMemory.Available < 3e10\n % 2 million DoFs need about 27GB free memory to be solved\n % 3 million DoFs need about 39GB free memory\n fprintf('Number of DoF %d exceeds estimated max dofs allowed in memory, stop. \\n',sum(freeDof)); \n return\nend\nbigSoln(freeDof) = bigA(freeDof, freeDof)\\Rhs(freeDof);\n\n%% post-processing for cavity\n% TO-DO: current code allows only 1 cavity\nif any(elem2face(bdFlag(:) == 2))\n disp('Post-processing cavity dofs')\n intBdFaceVec = false(size(freeDof,1), 1);\n isIntBdFace = false(NF,1);\n isIntBdFace(elem2face(bdFlag(:) == 2)) = true;\n idxIntBdFace = find(isIntBdFace);\n idxIntBdSb = idxIntBdFace + 5*NT+NF; % boundary DoF indices for s_b on cavity\n intBdFaceVec(idxIntBdSb) = true;\n \n AintBdFaceVec = bigA*intBdFaceVec; \n sbConst = dot((Rhs - bigA*bigSoln),AintBdFaceVec)/dot(AintBdFaceVec,AintBdFaceVec);\n fprintf('s_b on the interior boundary is %6.4g \\n',sbConst);\n bigSoln = bigSoln + sbConst*intBdFaceVec;\nend\n\n\n%% computing error\nerrL2U = zeros(NT,1);\n\nidxUDoF = (NT+NF+1:NT+NF+3*NT)';\nuh = bigSoln(idxUDoF);\nuhElem = zeros(NT,3);\n\nidxq0DoF = (5*NT+2*NF+1:5*NT+2*NF+3*NT)';\nqh0 = bigSoln(idxq0DoF);\nqh0Elem = zeros(NT,3);\n\nidxqbDoF = (8*NT+2*NF+1:8*NT+4*NF)';\nqhb = bigSoln(idxqbDoF);\n\nidxqDoF = (5*NT+2*NF+1:8*NT+4*NF)';\nqh = bigSoln(idxqDoF);\n\nidxlambdaDoF = (1:NT+NF)';\nlambdah = bigSoln(idxlambdaDoF);\n\nlambdah0 = bigSoln((1:NT)');\nlambdahb = bigSoln((NT+1:NT+NF)');\n\nidxsDoF = (4*NT+NF+1:5*NT+2*NF)';\nsh = bigSoln(idxsDoF);\nsh0 = bigSoln((4*NT+NF+1:5*NT+NF)');\nshb = bigSoln((5*NT+NF+1:5*NT+2*NF)');\n\nfor k = 1:3 % three bases in each K \n uhElem = uhElem + repmat(uh(elem2intdof(:,k)),1,3).*elem2ve(:,:,k);\n qh0Elem = qh0Elem + repmat(qh0(elem2intdof(:,k)),1,3).*elem2ve(:,:,k);\nend\n\n\n[lambda,w] = quadpts3(option.dquadorder+2); % quadrature order is 1 or 2\nnQuad = size(lambda,1);\nfor p = 1:nQuad\n pxyz = lambda(p,1)*node(elem(:,1),:) ...\n + lambda(p,2)*node(elem(:,2),:) ...\n + lambda(p,3)*node(elem(:,3),:) ...\n + lambda(p,4)*node(elem(:,4),:);\n \n up = pde.exactu(pxyz);\n EpsUminusUh = sum(bsxfun(@times, Eps2elem, up - uhElem), 2);\n errL2U = errL2U + w(p)*dot(squeeze(EpsUminusUh), up - uhElem, 2);\nend\n\n\nerrL2U = sqrt(errL2U.*volume);\nerrL2UTotal = norm(errL2U);\n\n% idxfreeFace = find(~isBdFace);\n% idxFreeFaceVec = [2*idxfreeFace-1 2*idxfreeFace]';\n% idxFreeFaceVec = idxFreeFaceVec(:);\n% errorStabTotal = sqrt(qh(idxFreeFaceVec)'*...\n% Stab_Wh(idxFreeFaceVec,idxFreeFaceVec)*qh(idxFreeFaceVec)...\n% +lambdah'*Stab_Mh*lambdah);\nerrorStabTotal = sqrt(qh'*Stab_Wh*qh+lambdah'*Stab_Mh*lambdah);\nerrorsTotal = sqrt(sh'*Stab_Sh*sh);\n\n\n\n%% Output information\nif nargout == 1\n soln = bigSoln;\nelse\n soln = struct('u',uh,...\n 'uh2elem', uhElem,...\n 'q0',qh0,...\n 'qb',qhb,...\n 'lambda0',lambdah0,...\n 'lambdab',lambdahb,...\n 's0',sh0,...\n 'sb',shb);\n eqn = struct('A',bigA,'b',Rhs,...\n 'face',face,...\n 'freeDof',freeDof,...\n 'bdDofScalar',idxBdFace,...\n 'bdDofVec',idxBdFaceVec,...\n 'bdDofCavity',idxIntBdFace,...\n 'errorU',errL2UTotal, ...\n 'errorqlambda', errorStabTotal,...\n 'errorS', errorsTotal,...\n 'errorUelem',errL2U,...\n 'NFace',NF);\n info.assembleTime = assembleTime;\nend\n\n\n%% end of function\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/DivCurl3PDWG.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677430095496, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5432385399195818}} {"text": "%\n% T = build_toep( c, d, n );\n%\n% Given:\n% c - the nonzero part of a central column of a banded Toeplitz\n% matrix\n% d - 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%\nfunction T = build_toep( c, d, n )\n\nm = length( c );\n\ncol = zeros(n,1);\nrow = col';\ncol(1:m-d+1,1) = c(d:m);\nrow(1,1:d) = c(d:-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/@kronMatrix/private/build_toep.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5430953206755218}} {"text": "function [T_request_Nm, OverallRatio] = control_ForceRequestConverter(F_x_request_N, ...\n tire_radius_m, i_c, i_f, i_r, i_gearset, ...\n gear_in)\n%__________________________________________________________________________\n%% Documentation\n%\n% Author: Dominik St�rk (dominik.staerk@tum.de)\n% \n% Start Date: 21.12.2020\n% \n% Description: \n% This function converts the requested overall longitudinal force \n% in a torque request for the engine. The effects of gear-ratios and \n% -efficiencies as well as differentials and acceleration-losses are taken\n% into account.\n% \n% Inputs: \n% F_x_request_N - requested overall longitudinal force [N] \n% tire_radius_m - tire`s radius [m]\n% i_c [2x1] - central differential ratio and efficiency [-, -]\n% i_f [2x1] - front differential ratio and efficiency [-, -]\n% i_r [2x1] - rear differential ratio and efficiency [-, -]\n% i_gearset [4x7] - gear information \n% gear_in - currently selected gear\n%\n% Outputs:\n% T_request_Nm - requested engine torque [Nm]\n\np_torque_rear = 1;\n\n%% request engine torque\nT_Nm = F_x_request_N * tire_radius_m;\n\nif gear_in ~= 0\n T_request_Nm = T_Nm / (i_c(1)*i_c(2) * ...\n ((1-p_torque_rear)*i_f(1)*i_f(2) + p_torque_rear*i_r(1)*i_r(2)) * ...\n i_gearset(2, gear_in+1)*i_gearset(4, gear_in+1));\n OverallRatio = (i_c(1)*i_c(2) * ...\n ((1-p_torque_rear)*i_f(1)*i_f(2) + p_torque_rear*i_r(1)*i_r(2)) * ...\n i_gearset(2, gear_in+1)*i_gearset(4, gear_in+1))/tire_radius_m;\nelse\n % use first gear even if in neutral\n T_request_Nm = T_Nm / (i_c(1)*i_c(2) * ...\n ((1-p_torque_rear)*i_f(1)*i_f(2) + p_torque_rear*i_r(1)*i_r(2)) * ...\n i_gearset(2, gear_in+2)*i_gearset(4, gear_in+1));\n % no brake torque when in neutral\n OverallRatio = 0;\nend\n", "meta": {"author": "TUMFTM", "repo": "mod_vehicle_dynamics_control", "sha": "48b12705b72740b0c1574b0da2eab66fe0c75127", "save_path": "github-repos/MATLAB/TUMFTM-mod_vehicle_dynamics_control", "path": "github-repos/MATLAB/TUMFTM-mod_vehicle_dynamics_control/mod_vehicle_dynamics_control-48b12705b72740b0c1574b0da2eab66fe0c75127/control/src/ice/control_ForceRequestConverter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767810736693, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5429654631929225}} {"text": "function c = ttv(a,v,dims)\n%TTV Tensor times vector for ktensor.\n%\n% Y = TTV(X,A,N) computes the product of Kruskal tensor X with a\n% (column) vector A. The integer N specifies the dimension in X\n% along which A is multiplied. If size(A) = [I,1], then X must have\n% size(X,N) = I. Note that ndims(Y) = ndims(X) - 1 because the N-th\n% dimension is removed.\n%\n% Y = TTV(X,{A1,A2,...}) computes the product of tensor X with a\n% sequence of vectors in the cell array. The products are computed\n% sequentially along all dimensions (or modes) of X. The cell array\n% contains ndims(X) vectors.\n%\n% Y = TTV(X,{A1,A2,...},DIMS) computes the sequence tensor-vector\n% products along the dimensions specified by DIMS.\n%\n% See also TENSOR/TTV, KTENSOR, KTENSOR/TTM.\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%%% ERROR CHECKING %%%\n%%%%%%%%%%%%%%%%%%%%%%\n\n% Check the number of arguments\nif (nargin < 2)\n error('TTV requires at least two arguments.');\nend\n\n% Check for 3rd argument\nif ~exist('dims','var')\n dims = [];\nend\n\n% Check that 2nd argument is cell array. If not, recall with v as a\n% cell array with one element.\nif ~iscell(v)\n c = ttv(a,{v},dims);\n return;\nend\n\n% Get sorted dims and index for multiplicands\n[dims,vidx] = tt_dimscheck(dims,ndims(a),numel(v)); \n\n% Check that each multiplicand is the right size.\nfor i = 1:numel(dims)\n if ~isequal(size(v{vidx(i)}),[size(a,dims(i)) 1])\n error('Multiplicand is wrong size');\n end\nend\n\n% Figure out which dimensions will be left when we're done\nremdims = setdiff(1:ndims(a),dims);\n\n% Collapse dimensions that are being multiplied out\nnewlambda = a.lambda;\nfor i = 1:numel(dims) \n newlambda = newlambda .* ( a.u{dims(i)}' * v{vidx(i)} );\nend\n\n% Create final result\nif isempty(remdims)\n c = sum(newlambda);\nelse\n c = ktensor(newlambda,a.u{remdims});\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/@ktensor/ttv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.5428053165298592}} {"text": "function visible = visiblevertices(FV, R)\n\nV2 = (R*FV.vertices')';\n\n% Store the vertex depths for z-buffering\nZ = V2(:, 3);\n\n% Compute the projected vertices in the image plane\nUV(:, 1) = V2(:, 1) ;\t% orthographic projection for x\nUV(:, 2) = V2(:, 2) ;\t% orthographic projection for y\n\n% Transform to the pixel plane (the axes remain switched)\nUV(:, 1) = UV(:, 1)-min(UV(:, 1));\nUV(:, 2) = UV(:, 2)-min(UV(:, 2));\nUV = UV + 1;\n\nUV=(UV./max(UV(:))).*1000;\nwidth=1000;\nheight=1000;\n\n% Get the triangle vertices\nv1 = FV.faces(:, 1);\nv2 = FV.faces(:, 2);\nv3 = FV.faces(:, 3);\nNfaces = size(FV.faces, 1);\n\n% Compute bounding boxes for the projected triangles\nx = [UV(v1, 1), UV(v2, 1), UV(v3, 1)];\ny = [UV(v1, 2), UV(v2, 2), UV(v3, 2)];\nminx = ceil (min(x, [], 2));\nmaxx = floor(max(x, [], 2));\nminy = ceil (min(y, [], 2));\nmaxy = floor(max(y, [], 2));\n\nclear x y\n\n% Frustum culling\nminx = max(1, minx);\nmaxx = min(width, maxx);\nminy = max(1, miny);\nmaxy = min(height, maxy);\n\n% Construct the pixel grid (can speed up by precomputing if shared among the images)\n[rows, cols] = meshgrid(1: width, 1: height);\n\n% Initialize the depth-, face- and weight-buffers\nzbuffer = -inf(height, width);\nfbuffer = zeros(height, width);\nwbuffer1 = NaN(height, width);\nwbuffer2 = NaN(height, width);\nwbuffer3 = NaN(height, width);\n\n% For each triangle (can speed up by comparing the triangle depths to the z-buffer and priorly sorting the triangles by increasing depth)\nfor i = 1: Nfaces\n \n % If some pixels lie in the bounding box\n if minx(i) <= maxx(i) && miny(i) <= maxy(i)\n \n % Get the pixels lying in the bounding box\n px = rows(miny(i): maxy(i), minx(i): maxx(i));\n py = cols(miny(i): maxy(i), minx(i): maxx(i));\n px = px(:);\n py = py(:);\n \n % Compute the edge vectors\n e0 = UV(v1(i), :);\n e1 = UV(v2(i), :) - e0;\n e2 = UV(v3(i), :) - e0;\n \n % Compute the barycentric coordinates (can speed up by first computing and testing a solely)\n det = e1(1) * e2(2) - e1(2) * e2(1);\n tmpx = px - e0(1);\n tmpy = py - e0(2);\n a = (tmpx * e2(2) - tmpy * e2(1)) / det;\n b = (tmpy * e1(1) - tmpx * e1(2)) / det;\n \n % Test whether the pixels lie in the triangle\n test = a >= 0 & b >= 0 & a + b <= 1;\n \n % If some pixels lie in the triangle\n if any(test)\n \n % Get the pixels lying in the triangle\n px = px(test);\n py = py(test);\n \n % Interpolate the triangle depth for each pixel\n w2 = a(test);\n w3 = b(test);\n w1 = 1 - w2 - w3;\n pz = Z(v1(i)) * w1 + Z(v2(i)) * w2 + Z(v3(i)) * w3;\n \n % For each pixel lying in the triangle\n for j = 1: length(pz)\n \n % Frustum culling\n% if pz(j) <= -near && pz(j) >= -far\n \n % Update the depth-, face- and weight-buffers\n if pz(j) > zbuffer(py(j), px(j))\n zbuffer(py(j), px(j)) = pz(j);\n fbuffer(py(j), px(j)) = i;\n wbuffer1(py(j), px(j)) = w1(j);\n wbuffer2(py(j), px(j)) = w2(j);\n wbuffer3(py(j), px(j)) = w3(j);\n end\n \n% end\n \n end\n \n end\n \n end\n \nend\n\n%figure; imshow(zbuffer,[])\n\nclear UV Z zbuffer px py pz minx maxx miny maxy\n\n% Get the vertices to render\ntest = fbuffer ~= 0;\nf = unique(fbuffer(test));\nv = unique([v1(f); v2(f); v3(f)]);\nf = find(any(ismember(FV.faces, v), 2));\nNfaces = length(f);\n\nvisible = v;\n\nreturn\n\n% Compute the edge vectors\ne1s = V2(v2(f), :) - V2(v1(f), :);\ne2s = V2(v3(f), :) - V2(v1(f), :);\ne3s = V2(v2(f), :) - V2(v3(f), :);\n\nclear V2\n\n% Normalize the edge vectors\ne1s_norm = e1s ./ repmat(sqrt(sum(e1s.^2, 2)), 1, 3);\ne2s_norm = e2s ./ repmat(sqrt(sum(e2s.^2, 2)), 1, 3);\ne3s_norm = e3s ./ repmat(sqrt(sum(e3s.^2, 2)), 1, 3);\n\n% Compute the angles\nangles(:, 1) = acos(sum(e1s_norm .* e2s_norm, 2));\nangles(:, 2) = acos(sum(e3s_norm .* e1s_norm, 2));\nangles(:, 3) = pi - (angles(:, 1) + angles(:, 2));\n\n% Compute the triangle weighted normals\ntriangle_normals = cross(e1s, e3s, 2);\nw1_triangle_normals = triangle_normals .* repmat(angles(:, 1), 1, 3);\nw2_triangle_normals = triangle_normals .* repmat(angles(:, 2), 1, 3);\nw3_triangle_normals = triangle_normals .* repmat(angles(:, 3), 1, 3);\n\nclear e1s e2s e3s e1s_norm e2s_norm e3s_norm angles triangle_normals\n\n% Initialize the vertex normals\nnormals = zeros(Nvertices, 3);\n\n% Update the vertex normals\nfor i = 1: Nfaces\n normals(v1(f(i)), :) = normals(v1(f(i)), :) + w1_triangle_normals(i, :);\n normals(v2(f(i)), :) = normals(v2(f(i)), :) + w2_triangle_normals(i, :);\n normals(v3(f(i)), :) = normals(v3(f(i)), :) + w3_triangle_normals(i, :);\nend\n\nclear w1_triangle_normals w2_triangle_normals w3_triangle_normals\n\n% Normalize the vertex normals\nnormals = normals(v, :);\nnormals = normals ./ repmat(sqrt(sum(normals.^2, 2)), 1, 3);\n\n% Self-occlusions\ntest = normals(:, 3) >= 0;\n\n% Interpolate the z-buffer at the projected vertices\nvZ = inf(size(FV.vertices, 1), 1);\nvZ(test) = interp2(rows, cols, zbuffer, UV(test, 1), UV(test, 2), '*linear');\n\n% Fix the border\ntmp_test = vZ(test) == -inf;\nvZ(test(tmp_test))\t= interp2(rows, cols, zbuffer, UV(test(tmp_test), 1), UV(test(tmp_test), 2), '*nearest');\n\n% Compute the vertex visibility index in terms of relative depth compared to the z-buffer\ntest(test) = abs(vZ(test) - Z(test)) <= 0.05 * (max(Z) - min(Z));\n\nclear ambient1 diffuse1 specular1 ambient2 diffuse2 specular2 ambient3 diffuse3 specular3 v\n\n% Initialize the image\nim1 = NaN(height, width);\nim2 = NaN(height, width);\nim3 = NaN(height, width);\n\n% Rasterize the image\nv1 = v1(fbuffer(test));\nv2 = v2(fbuffer(test));\nv3 = v3(fbuffer(test));\nw1 = wbuffer1(test);\nw2 = wbuffer2(test);\nw3 = wbuffer3(test);\nim1(test) = w1 .* texture1(v1) + w2 .* texture1(v2) + w3 .* texture1(v3);\nim2(test) = w1 .* texture2(v1) + w2 .* texture2(v2) + w3 .* texture2(v3);\nim3(test) = w1 .* texture3(v1) + w2 .* texture3(v2) + w3 .* texture3(v3);\n\nclear v1 v2 v3 w1 w2 w3 \n\n% Reshape the image\nim = cat(3, im1, im2, im3);\n\nclear im1 im2 im3 test\n\nim = flipud(fliplr(im));\n\nend", "meta": {"author": "waps101", "repo": "3DMM_edges", "sha": "848e9775c0581ae97469eacad60dfe3943c30707", "save_path": "github-repos/MATLAB/waps101-3DMM_edges", "path": "github-repos/MATLAB/waps101-3DMM_edges/3DMM_edges-848e9775c0581ae97469eacad60dfe3943c30707/utils/visiblevertices.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.5427900290023574}} {"text": "function [bcx,bcy] = specific_flow(xbd,ybd)\n%backwardstep_flow Reference problem 5.2 inflow condition \n% [bcx,bcy] = specific_flow(xbd,ybd);\n% input\n% xbd x coordinate vector\n% ybd y coordinate vector \n%\n% specifies backward step flow boundary condition\n% IFISS function: DJS; 6 March 2005.\n% Copyright (c) 2005 D.J. Silvester, H.C. Elman, A. Ramage \nbcx=0*xbd; bcy=0*xbd;\nk=find(xbd==-1); bcx(k)=4*ybd(k).*(1-ybd(k));\nreturn\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/toms866/stokes_flow/test_problems/backwardstep_flow.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7520125848754471, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.5427599741841497}} {"text": "function [M,P] = ckf_predict(M,P,f,Q,f_param)\n% CKF_PREDICT - Cubature Kalman filter prediction step\n%\n% Syntax:\n% [M,P] = CKF_PREDICT(M,P,[f,Q,f_param])\n%\n% In:\n% M - Nx1 mean state estimate of previous step\n% P - NxN state covariance of previous step\n% f - Dynamic model function as a matrix A defining\n% linear function f(x) = A*x, inline function,\n% function handle or name of function in\n% form f(x,param) (optional, default eye())\n% Q - Process noise of discrete model (optional, default zero)\n% f_param - Parameters of f (optional, default empty)\n%\n% Out:\n% M - Updated state mean\n% P - Updated state covariance\n%\n% Description:\n% Perform additive form spherical-radial cubature Kalman filter (CKF)\n% prediction step.\n%\n% Function f(.) should be such that it can be given a\n% DxN matrix of N sigma Dx1 points and it returns \n% the corresponding predictions for each sigma\n% point. \n%\n% See also:\n% CKF_UPDATE, CRTS_SMOOTH, CKF_TRANSFORM, SPHERICALRADIAL\n% \n% References:\n% Arasaratnam and Haykin (2009). Cubature Kalman Filters.\n% IEEE Transactions on Automatic Control, vol. 54, no. 5, pp.1254-1269\n\n% Copyright (c) 2010 Arno Solin\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%%\n\n %\n % Check which arguments are there\n %\n if nargin < 2\n error('Too few arguments');\n end\n if nargin < 3\n f = [];\n end\n if nargin < 4\n Q = [];\n end\n\n %\n % Apply defaults\n %\n if isempty(f)\n f = eye(size(M,1));\n end\n if isempty(Q)\n Q = zeros(size(M,1));\n end\n \n %\n % Do transform and add process noise\n %\n if nargin < 5\n [M,P] = ckf_transform(M,P,f); \n else\n [M,P] = ckf_transform(M,P,f,f_param);\n end\n P = P + Q;\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/ckf_predict.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683106, "lm_q2_score": 0.6370307875894138, "lm_q1q2_score": 0.5427201644268808}} {"text": "function [Vx,Vy] = computeFlowBkgSup(im1curr,im2curr,params,gparams)\n% function [Vx,Vy] = computeFlowBkgSup(im1curr,im2curr,params)\n% Computes flow and then suppresses flow in the background.\n\n%There is some flow towards the center that can't be estimated\n% properly. The flow increases as we go away from the center.\n% d_err is to account for that.\n\nsz = round(size(im1curr));\nbwimg = zeros(sz(1),sz(2));\nctr = [ceil( (sz(1)+1)/2),ceil( (sz(2)+1)/2)];\nbwimg(ctr(1),ctr(2))=1;\ndimg = bwdist(bwimg,'euclidean');\n[xx,yy]= meshgrid(1:sz(2),1:sz(1));\naimg = atan2(-(yy-ctr(1)),-(xx-ctr(2)));\n\ndd_err = dimg/size(im1curr,1);\nflow_thres = gparams.flow_thres;\n\nuv = estimate_flow_interface(im1curr,im2curr,...\n 'hs-brightness',{'max_warping_iters',gparams.warping_iters});\n\nif ~params.stationary,\n Vx = uv(:,:,1);\n Vy = uv(:,:,2);\n return;\nend\n\ncdx = params.dx;\ncdy = params.dy;\ncurt = params.theta;\nrotd = [cos(curt) sin(curt); -sin(curt) cos(curt)]*[cdx;cdy];\ncdx = -rotd(1); cdy = -rotd(2);\n\nctheta = params.dtheta;\nrotflowu = dimg.*(cos(aimg+ctheta)-cos(aimg));\nrotflowv = dimg.*(sin(aimg+ctheta)-sin(aimg));\n\n\ndd1 = sqrt( (uv(:,:,1)-cdx-rotflowu).^2 + (uv(:,:,2)-cdy-rotflowv).^2);\n\ncrdx = params.rdx; crdy = params.rdy;\nrotd = [cos(curt) sin(curt); -sin(curt) cos(curt)]*[crdx;crdy];\nfly_flow = rotd;\n\ndd2 = sqrt( (uv(:,:,1)-fly_flow(1)).^2 + (uv(:,:,2)-fly_flow(2)).^2);\ndd = min(dd1,dd2);\nfor ndx = 1:2\n tt = uv(:,:,ndx);\n tt( dd<(dd_err+flow_thres)) = 0;\n uv(:,:,ndx) = tt;\nend\nVx = uv(:,:,1);\nVy = uv(:,:,2);\n", "meta": {"author": "kristinbranson", "repo": "JAABA", "sha": "5d778a23e3e7cf272df9a89a72b1b66d94f535d7", "save_path": "github-repos/MATLAB/kristinbranson-JAABA", "path": "github-repos/MATLAB/kristinbranson-JAABA/JAABA-5d778a23e3e7cf272df9a89a72b1b66d94f535d7/spaceTime/computeFlowBkgSup.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683106, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.5427201585561001}} {"text": "% Copyright 2016 Google Inc.\n%\n% Licensed under the Apache License, Version 2.0 (the \"License\");\n% you may not use this file except in compliance with the License.\n% You may obtain a copy of the License at\n%\n% http ://www.apache.org/licenses/LICENSE-2.0\n%\n% Unless required by applicable law or agreed to in writing, software\n% distributed under the License is distributed on an \"AS IS\" BASIS,\n% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n% See the License for the specific language governing permissions and\n% limitations under the License.\n\nfunction A = buildSecondDerivZMatrix(grid_size)\n\n% d/dz for every entry in the cube except the first and last slice.\nm = grid_size(1) * grid_size(2) * (grid_size(3) - 2);\nn = grid_size(1) * grid_size(2) * grid_size(3);\ne = ones(m, 1);\ninterior = spdiags([e, -2 * e, e], ...\n [0, grid_size(1) * grid_size(2), 2 * grid_size(1) * grid_size(2)], ...\n m, n);\n\nboundary_z1 = makeBoundaryZ1(n);\nboundary_zend = makeBoundaryZEnd(n);\n\n% The matrix for a full cube.\ncube = [boundary_z1; interior; boundary_zend];\n\n% Repeat the cube for the last 2 dimensions.\nA = sparse(0, 0);\nfor v = 1:grid_size(5)\n for u = 1:grid_size(4)\n A = blkdiag(A, cube);\n end\nend\n\n% Boundary conditions for the first slice.\n% n is the number of columns for the full matrix (the number of variables\n% in the grid).\nfunction A = makeBoundaryZ1(n)\n mm = grid_size(1) * grid_size(2);\n nn = grid_size(1) * grid_size(2) * 2;\n e = ones(mm, 1);\n B = spdiags([-e, e], [0, grid_size(1) * grid_size(2)], mm, nn);\n % Concat zero columns to the right so we can vertical concat with the full\n % matrix later.\n A = [B, sparse(mm, n - nn)];\nend\n\n% Boundary conditions for the last slice.\nfunction A = makeBoundaryZEnd(n)\n mm = grid_size(1) * grid_size(2);\n nn = grid_size(1) * grid_size(2) * 2;\n e = ones(mm, 1);\n B = spdiags([e, -e], [0, grid_size(1) * grid_size(2)], mm, nn);\n % Concat zero columns to the right so we can vertical concat with the full\n % matrix later.\n A = [sparse(mm, n - nn), B];\nend\n\n\nend\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/bgu/buildSecondDerivZMatrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933535169629, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.542706166450244}} {"text": "function [vars,eval] = km_akcca(pars,data)\n% KM_AKCCA performs Alternating Kernel Canonical Correlation Analysis to\n% blindly identify and equalize a single-input multiple-output Wiener.\n%\n% Input:\t- pars: structure containing parameters of the alternating KCCA\n% algorithm\n%\t\t\t- data: structure containing the available data x, and the\n% unavailable data (source signal s, internal signals y, and \n% linear channels B)\n% Output:\t- vars: estimated variables\n% - eval: structure containing the resuls of the algorithm\n% evaluation\n% USAGE: [vars,eval] = km_akcca(pars,data)\n%\n% Author: Steven Van Vaerenbergh (steven *at* gtas.dicom.unican.es), 2011.\n%\n% The algorithm in this file is based on the following publication:\n% S. Van Vaerenbergh, J. Via and I. Santamaria, \"Blind Identification of \n% SIMO Wiener Systems based on Kernel Canonical Correlation Analysis\", \n% accepted for publication in IEEE Transactions on Signal Processing, 2013.\n%\n% This file is part of the Kernel Methods Toolbox for MATLAB.\n% https://github.com/steven2358/kmbox\n\n% AKCCA CORE\n[vars, eval] = AKCCA_CORE_INIT(pars,data.x); % initialize\nvars.it = 0;\neval.converged = false;\nwhile ((vars.it < pars.it_max) && ~eval.converged)\n fprintf('.');\n vars.it = vars.it+1;\n vars = AKCCA_CORE_LINID(pars,vars); % CCA 1: estimate h and obtain z\n vars = AKCCA_CORE_NLINID(pars,vars); % CCA 2: estimate alpha and obtain y\n vars = AKCCA_CORE_EQ(pars,vars); % EQUALIZATION\n eval = AKCCA_CORE_EVAL(pars,vars,data,eval); % Error calculation and check convergence\nend\nfprintf('\\n');\n\n\n\nfunction [vars,eval] = AKCCA_CORE_INIT(pars,x)\n\n% READ PARAMETERS AND VARIABLES\np = pars.p;\nm = pars.m;\nN = pars.data_N;\nnum_it = pars.it_max;\nktype = pars.kernel.type;\n% ktype = pars.kernel{1};\nkpar = pars.kernel.par;\ndiff_nlin = ~pars.identical_nonlin;\t% boolean indicating different nonlinearities\n\n% CONSTRUCT KERNEL MATRIX DECOMPOSITIONS\nK = cell(p,1);\nc = cell(p,1);\nif diff_nlin,\n switch pars.decomp\n case 'KPCA'\n for i=1:p,\n if isa(kpar,'function_handle')\t% determine kernel parameter\n parfun = kpar;\n c{i} = parfun(x{i});\n else c{i} = kpar(i);\n end\n Kfull = km_kernel_center(x{i},x{i},x{i},ktype,c{i});\n Kfull = 0.5*(Kfull+Kfull');\t% avoid matlab rounding errors\n [V,D] = eig(Kfull);\n [D_sort,ind] = sort(real(diag(D)),'descend');\n if m<1,\t% m represents the fraction of energy to be witheld\n energy = sum(D_sort);\n cumul_energy = cumsum(D_sort)/energy;\n m = sum(cumul_energy < 1-m)+1;\t% new m is number of required eigenvectors\n end\n K{i} = V(:,ind(1:m));\n end\n case 'ICD'\n \n for i=1:p,\n if isa(kpar,'function_handle')\t% determine kernel parameter\n parfun = kpar;\n c{i} = parfun(x{i});\n else\n c{i} = kpar(i);\n end\n if m<1,\t% m represents the precision in ICD\n precision = m;\n mm = N;\n else\n precision = 1E-10;\n mm = m;\n end\n G = km_kernel_icd(x{i},ktype,c{i},mm,precision);\n G = G-repmat(mean(G),N,1);\n K{i} = G;\n end\n otherwise\n error 'wrong decomposition method';\n end\n\n y_est = x;\n \nelse\n Xf = [];\n for i=1:p,\n Xf = [Xf;x{i}]; %#ok\n end\n \n if isa(kpar,'function_handle')\t% determine kernel parameter\n parfun = kpar;\n c = parfun(Xf);\n else c = kpar(i);\n end\n \n switch pars.decomp\n case 'KPCA'\n Kfull = km_kernel_center(Xf,Xf,Xf,ktype,c);\n Kfull = 0.5*(Kfull+Kfull');\n [V,D] = eig(Kfull);\n [D_sort,ind] = sort(real(diag(D)),'descend');\n \n if m<1,\t% m represents the fraction of energy to be witheld\n energy = sum(D_sort);\n cumul_energy = cumsum(D_sort)/energy;\n m = sum(cumul_energy < 1-m)+1;\t% new m is number of required eigenvectors\n else\n m=m*p;\n end\n for i=1:p,\n stind = (i-1)*N + 1;\n ndind = stind+N - 1;\n K{i} = V(stind:ndind,ind(1:m));\n end\n \n case 'ICD'\n \n if m<1,\t% m represents the precision in ICD\n precision = m;\n mm = N;\n else\n precision = 1E-10;\n mm=m*p;\n end\n G = km_kernel_icd(Xf,ktype,c,mm,precision);\n G = G-repmat(mean(G),p*N,1);\n \n for i=1:p,\n stind = (i-1)*N + 1;\n ndind = stind+N - 1;\n K{i} = G(stind:ndind,:);\n end\n otherwise\n error 'wrong decomposition method';\n end\n \n y_est = x;\nend\n\n% WRITE EVAL AND VARIABLES\neval.MSE_y = zeros(1,num_it);\neval.MSE_z = zeros(2,num_it);\neval.MSE_h = zeros(1,num_it);\neval.result = zeros(1,num_it);\n\nvars.y_est = y_est;\t\t% initialize without taking into account the nonlinearity\nvars.K = K;\t\t% reduced kernel matrices\nvars.x = x;\t\t% original output data\nvars.c = c; % kernel parameter\n\n\n\nfunction vars = AKCCA_CORE_LINID(pars,vars)\n% estimate linear filters\n\n% COPY PARAMETERS\np = pars.p;\nL = pars.model_L;\nN = pars.data_N;\nK = vars.K;\n\ny_est = vars.y_est;\n\n% PROGRAM\nn = N-L+1;\n\n% get time-embedded data matrices\nKa = cell(p,1);\nfor i=1:p,\n\tKa{i} = zeros(n,L);\n% \tfor n_ind = 1:n, % too slow, better fill differently\n% \t\tKa{i}(n_ind,:) = y_est{i}(n_ind+L-1:-1:n_ind)';\n% \tend\n for l_ind = 1:L,\n Ka{i}(:,l_ind) = y_est{i}(L-l_ind+1:L-l_ind+n)';\n end\nend\n\nh = SIMO_id_CCA(Ka);\n\nzh_est = cell(p);\nW = cell(p);\n% rescale solution to fulfill restriction sumsqr = 1\nsumnrg_h = 0;\nfor i=1:p,\n\tfor j=1:p,\n\t\tif(i~=j)\n\t\t\tsumnrg_h = sumnrg_h + sum((Ka{i}*h{j}).^2);\n\t\tend\n\tend\nend\nfor i=1:p,\n\th{i} = h{i}/sqrt(sumnrg_h);\nend\n\nfor i=1:p,\n\tfor j=1:p,\n\t\tif (i~=j)\n mi = size(K{i},2);\n W{i,j} = zeros(n,mi);\n\t\t\tzh_est{i,j} = Ka{i}*h{j};\t% system output\n% for n_ind=1:n, % too slow, better fill differently\n% kimat = K{i}(n_ind+L-1:-1:n_ind,:);\n% W{i,j}(n_ind,:) = h{j}'*kimat;\t% auxiliary variable\n% end\n for l_ind = 1:L, % superfast\n W{i,j} = W{i,j} + h{j}(l_ind)*K{i}(L-l_ind+1:L-l_ind+n,:);\n end\n\t\tend\n\tend\nend\n\n% COPY VARIABLES\nvars.h = h;\t\t% filter estimation\nvars.zh_est = zh_est;\t% new output estimate\nvars.W = W;\t\t% auxiliary variable (filtered kernel matrices)\n\n\n\nfunction vars = AKCCA_CORE_NLINID(pars,vars)\n% estimate inverse nonlinearities\n\n% READ PARAMETERS AND VARIABLES\np = pars.p;\ndiff_nlin = ~pars.identical_nonlin;\t% boolean indicating different nonlinearities\n\nK = vars.K;\nW = vars.W;\nreg = pars.reg;\n\n% PROGRAM: 1 iteration\nza_est = cell(p);\ny_est = cell(p,1);\nif diff_nlin\n\t% standard case: no identical nonlinearity\n\ta = SIMO_id_CCA_dual(W,reg);\n\n\t% rescale solution to fulfill restriction sumsqr = 1\n\tsumnrg_a = 0;\n\tfor i=1:p,\n\t\tfor j=1:p,\n\t\t\tif(i~=j)\n\t\t\t\tsumnrg_a = sumnrg_a + sum((W{i,j}*a{i}).^2);\n\t\t\tend\n\t\tend\n\tend\n\n\tfor i=1:p,\n\t\ta{i} = a{i}/sqrt(sumnrg_a);\n\t\ty_est{i} = K{i}*a{i};\t% get y estimates\n\t\ty_est{i} = y_est{i}/sqrt(norm(y_est{i}))*sqrt(norm(vars.x{i}));\t% normalize\n\t\tfor j=1:p,\n\t\t\tif (i~=j)\n\t\t\tza_est{i,j} = W{i,j}*a{i};\t% system output\n\t\t\tend\n\t\tend\n\tend\nelse\n\t% identical nonlinearity\n\ta = SIMO_id_CCA_dual_identical(W,reg);\n\tfor i=1:p,\n\t\ty_est{i} = K{i}*a;\t% get y estimates\n\t\tfor j=1:p,\n\t\t\tif (i~=j)\n\t\t\tza_est{i,j} = W{i,j}*a;\t% system output\n\t\t\tend\n\t\tend\n\tend\nend\n\n% WRITE VARIABLES\nvars.alpha = a;\nvars.y_est = y_est;\nvars.za_est = za_est;\n\n\n\nfunction vars = AKCCA_CORE_EQ(pars,vars)\n% equalize linear channels (zero-forcing)\n\n% COPY PARAMETERS\np = pars.p;\nL = pars.model_L;\nN = pars.data_N;\nk = pars.zf_k;\n\ny_est = vars.y_est;\nh = vars.h;\n\n% PROGRAM\n% use k observations to generate filter matrix and estimate equalizers\nHc = cell(p,1); Hr = cell(p,1);\nTH = zeros(p*k,k+L-1);\nfor i=1:p,\n\tHc{i} = [h{i}(1);zeros(k-1,1)];\n\tHr{i} = [h{i}' zeros(1,k-1)];\n\tTH(i:p:end,:) = toeplitz(Hc{i},Hr{i});\nend\n\n% zero-forced equalizing\nZF = pinv(TH);\n\n% S_est = zeros(N-k+1,k);\n% Yi = zeros(p*k,1);\n% for i=1:N-k+1, % too slow, better fill differently\n% \tfor j=1:p,\n% \t\tyi = y_est{j}(i+k-1:-1:i);\n% \t\tYi(j:p:end) = yi;\n% \tend\n% \ts_esti = ZF*Yi;\n% \tS_est(i,:) = s_esti(1:k).';\n% end\nYY = zeros(N-k+1,p*k);\nfor j = 1:p,\n for k_ind=1:k,\n col = (k_ind-1)*p + j;\n YY(:,col) = y_est{j}(k-k_ind+1:N-k_ind+1);\n end\nend\nS_est = YY*ZF(1:k,:)';\n\ncnorms = zeros(k,1);\nfor i=1:k,\n\tcnorms(i) = norm(ZF(:,i));\nend\n[mm,zfi] = min(cnorms); %#ok\ns_est = S_est(:,zfi);\n\ninds = k-zfi+1:N-zfi+1;\n\n% COPY VARIABLES\nvars.s_est = s_est;\nvars.ind_s = inds;\nvars.ZF = ZF;\n\n\n\nfunction eval = AKCCA_CORE_EVAL(pars,vars,data,eval)\n% evaluate solutions: calculate errors\n\n% COPY PARAMETERS\np = pars.p;\nvb = pars.verbose;\n\ny_est = vars.y_est;\ns_est = vars.s_est;\nh = vars.h;\nit = vars.it;\ninds = vars.ind_s;\n\ns = data.s; % true source signal\nB = data.B; % true channels\ny = data.y; % true internal channels\n\n% PROGRAM\nMSE_y = 0; MSE_h = 0; MSE_za = 0; MSE_zh = 0;\nfor i=1:p,\n\t% check if system internals are known\n\tif (iscell(y))\n\t\t% MSE Y\n\t\tMSE_y = MSE_y + norm_compare(y{i},y_est{i})/p;\n\t\t% MSE H\n\t\tnumz = length(h{i})-length(B{i});\n\t\tif (numz>0)\n\t\t\t% channel overestimation case\n\t\t\tB{i} = [B{i};zeros(numz,1)];\n\t\tend\n\t\tMSE_h = MSE_h + norm_compare(B{i},h{i})/p;\n\tend\n\t\n\t% MSE Z\n\tif isfield(vars,'za_est')\n\t\tza_est = vars.za_est;\n\tend\n\tzh_est = vars.zh_est;\n\n\tfor j=i+1:p,\n\t\tif (i~=j)\n\t\t\tMSE_zh = MSE_zh + sum((zh_est{i,j}-zh_est{j,i}).^2);\n\t\t\tif isfield(vars,'za_est')\n\t\t\t\tMSE_za = MSE_za + sum((za_est{i,j}-za_est{j,i}).^2);\n\t\t\tend\n\t\tend\n\tend\nend\n\nsignal_test = s(inds);\nsignal_est = s_est;\n\nswitch lower(pars.data_type)\n\tcase {'gaussian'}\n\t\t% result = MSE between s and s_est\n\t\tresult = norm_compare(signal_test,signal_est);\n\tcase 'bits'\n\t\t% result = BER\n\t\t[MSEsb,sci] = scale_compare(signal_test,signal_est); %#ok\n\t\tresult = sum(sign(signal_test)~=sign(signal_est/sci))/length(signal_test);\n s_est = sign(signal_est/sci);\n\totherwise\n\t\tdisp('Unknown signal type.')\nend\n\n% OUTPUT\nif vb, fprintf(1,'MSE z_a: %f\\n',MSE_za); end;\nif vb, fprintf(1,'MSE z_h: %f\\n',MSE_zh); end;\nif vb, fprintf(1,'MSE y: %f\\n',MSE_y); end;\nif vb, fprintf(1,'Result: %f\\n',result); end;\n\n% COPY VARIABLES\neval.MSE_h(it) = MSE_h;\neval.MSE_y(it) = MSE_y;\neval.MSE_z(1,it) = MSE_zh;\neval.MSE_z(2,it) = MSE_za;\neval.result(it) = result;\neval.s_est = s_est;\n\n% CHECK STOP\nif (it>2)\n\t% stop when both sub-iterations obtain consecutive equal costs\n\tchange1 = abs(eval.MSE_z(2*it)-eval.MSE_z(2*it-2));\n\tchange2 = abs(eval.MSE_z(2*it-1)-eval.MSE_z(2*it-3));\n\tif ((change1 < pars.it_stop) && (change2 < pars.it_stop))\n\t\teval.converged = true;\n\t\tnum = pars.it_max - it;\n\t\teval.MSE_h(it+1:pars.it_max) = repmat(MSE_h,num,1);\n\t\teval.MSE_y(it+1:pars.it_max) = repmat(MSE_y,num,1);\n\t\teval.MSE_z(2*it+1:2*pars.it_max) = repmat(MSE_zh,2*num,1);\n\t\teval.result(it+1:pars.it_max) = repmat(result,num,1);\n\tend\nend\n\neval.finalresult = result;\n\n\n\nfunction [h,alphas,betas] = SIMO_id_CCA(X)\n% SIMO_ID_CCA estimates various channels of a SIMO system using CCA.\n% Finds the optimal h_i such that X_i h_j = X_j H_i s.t. sum (i = j)\n% ||X_i h_j||^2 = 1.\n% Input:\t- X: cell containing p sets of length N and dimension L (N x L)\n% Output:\t- h: identified channels (cell)\n%\t\t\t- alphas: sorted eigenvectors\n%\t\t\t- betas: sorted eigenvalues\n%\n% Steven Van Vaerenbergh 2008\n\np = length(X);\nL = size(X{1},2);\n\nRf = zeros(p*L); Df = zeros(p*L);\nfor i=1:p,\n\tD = zeros(L);\n\tfor j=1:p,\n\t\tif i~=j\n\t\t\tsti = (i-1)*L+1;\n\t\t\tndi = i*L;\n\t\t\tstj = (j-1)*L+1;\n\t\t\tndj = j*L;\n\t\t\tRf(sti:ndi,stj:ndj) = X{j}'*X{i};\n\t\t\tD = D + X{j}'*X{j};\n\t\tend\n\tend\n\tDf(sti:ndi,sti:ndi) = D;\nend\n\n[alphas,betas] = eig(Rf,Df);\n[betas,ind] = sort(real(diag(betas)),'ascend');\nalpha = alphas(:,ind(end));\n% alpha = alpha/norm(alpha);\n\nh = cell(p,1);\nfor i=1:p,\n\tsti = (i-1)*L+1;\n\tndi = i*L;\n\th{i} = alpha(sti:ndi);\nend\n\n\n\nfunction [h,alphas,betas] = SIMO_id_CCA_dual_identical(X,reg)\n% SIMO_ID_CCA estimates various channels of a SIMO system using CCA.\n% Finds the optimal h_i such that X_ij h = X_ji h \n% Input:\n%\tX: cell containing pxp data sets of length N and dimension m (N by m)\n% reg: regularization\n%\t\n% outputs:\n%\th: identified channels\n%\talphas: sorted eigenvectors\n%\tbetas: sorted eigenvalues\n%\n% Reference: Via, Santamaria [...]\n%\n% Steven Van Vaerenbergh 2008\n\nif nargin<2\n reg = 1E-8;\nend\n\np = size(X,1);\nm = size(X{1,2},2);\n\nRf = zeros(m); Df = zeros(m);\nfor i=1:p,\n\tfor j=1:p,\n\t\tif i~=j\n\t\t\tRf = Rf + X{i,j}'*X{j,i};\n\t\t\tDf = Df + X{i,j}'*X{i,j};\n\t\tend\n\tend\nend\nDf = Df + reg*eye(size(Df));\n\t\n% solve eigenvalue problem\n[alphas,betas] = eig(Rf,Df);\n[betas_a,ind] = sort(real(diag(betas))); %#ok\nh = alphas(:,ind(end));\n\n\n\nfunction [h,alphas,betas] = SIMO_id_CCA_dual(X,reg)\n% SIMO_ID_CCA estimates various channels of a SIMO system using CCA.\n% Finds the optimal h_i such that X_ij h_i = X_ji h_j s.t. sum (i~=j) \n% ||X_ij h_i||^2 = 1.\n% Input:\t- X: cell containing pxp sets of length N and dimension mi (N x mi).\n% - reg: regularization\n% Outputs:\t- h: identified channels (cell)\n%\t\t\t- alphas: sorted eigenvectors\n%\t\t\t- betas: sorted eigenvalues\n%\n% Steven Van Vaerenbergh 2008\n\nif nargin<2\n reg = 1E-8;\nend\n\np = size(X,1);\nm = zeros(p,1);\nfor i=1:p,\n\tj = mod(i,p)+1;\n\tm(i) = size(X{i,j},2);\nend\nmcum = [0;cumsum(m)];\n\nRf = zeros(mcum(end)); Df = zeros(mcum(end));\nfor i=1:p,\n\tD = zeros(m(i));\n\tfor j=1:p,\n\t\tif i~=j\n\t\t\tsti = mcum(i)+1;\n\t\t\tndi = sti+m(i)-1;\n\t\t\tstj = mcum(j)+1;\n\t\t\tndj = stj+m(j)-1;\n\t\t\tRf(sti:ndi,stj:ndj) = X{i,j}'*X{j,i};\n\t\t\tD = D + X{i,j}'*X{i,j};\n\t\tend\n\tend\n\tDf(sti:ndi,sti:ndi) = D + reg*eye(size(D));\nend\n\n[alphas,betas] = eig(Rf,Df);\n[betas,ind] = sort(real(diag(betas)),'ascend');\nalpha = alphas(:,ind(end));\n% alpha = alpha/norm(alpha);\n\nh = cell(p,1);\nfor i=1:p\n\tsti = mcum(i)+1;\n\tndi = mcum(i+1);\n\th{i} = alpha(sti:ndi);\nend\n\n\n\nfunction MSE = norm_compare(data_1,data_2)\n% NORM_COMPARE calculates the squared error between 2 normalized signals\n\ndata_1_norm = data_1/norm(data_1);\ndata_2_norm = data_2/norm(data_2);\n\n% take into account sign ambiguity\nerr_vecA = data_1_norm - data_2_norm;\nerr_vecB = data_1_norm + data_2_norm;\n\nMSEA = err_vecA'*err_vecA;\nMSEB = err_vecB'*err_vecB;\n\nMSE = min(MSEA,MSEB);\n\n\n\nfunction [MSE,sc] = scale_compare(data_1,data_2)\n\ndata_1_norm = data_1/norm(data_1);\nsc = data_1_norm'*data_2/(data_2'*data_2);\n\nerr_vec = data_1_norm - sc*data_2;\n\nMSE = err_vec'*err_vec;\nsc = sc*norm(data_1);\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/kmbox/lib/km_akcca.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.661922862511608, "lm_q1q2_score": 0.5427061438620792}} {"text": "function [p] = ft_connectivity_plm(inputdata, varargin)\n\n% FT_CONNECTIVITY_PLM computes the phase linearity measurement from a cell array of\n% time-domain data, where each cell is an epoch. This implements the metric described\n% in Baselice et al. \"Phase Linearity Measurement: a novel index for brain functional\n% connectivity\", IEEE Transactions on Medical Imaging, 2018.\n%\n% Use as\n% [p] = ft_connectivity_plm(inputdata, ...)\n%\n% The input data input should be organized as a cell-array, one element for each\n% epoch/repetition. Each cell should be a matrix of of nchan x nsamples values.\n%\n% Additional optional input arguments come as key-value pairs:\n% 'bandwidth'\t=\tscalar, half-bandwidth parameter: the frequency range across which to integrate\n% 'fsample' = sampling frequency, needed to convert bandwidth to number of bins\n%\n% The output p contains the phase linearity measurement in the [0, 1] interval. It is\n% organized as a 3D matrix of Nrpt x Nchan x Nchan dimensions.\n%\n% See also CONNECTIVITY, FT_CONNECTIVITYANALYSIS\n\n% Copyright (C) 2018, Fabio Baselice, Pierpaolo Sorrentino, 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% the sequence of steps is as follows:\n% - Hilbert transformation\n% - multiply with complex conjugate\n% - fft\n% - remove volume conduction component\n% - integrate over bandwidth\n\n% NOTE BY JM: if the user inputs data with different length trials, the fft per trial is going\n% to have different frequency resolutions, which is not good. Better to throw an error in that\n% case.\nfs = ft_getopt(varargin, 'fsample');\nB = ft_getopt(varargin, 'bandwidth');\nif isempty(fs)\n error('sampling rate is not defined');\nend\nif isempty(B)\n warning('bandwidth parameter is not defined, assumed 1Hz');\n B=1;\nend\n\nnsmp = cellfun('size', inputdata, 2);\nassert(all(nsmp==nsmp(1)), 'currently there is no support for input, where the trials are of different length');\n\nnrpt=numel(inputdata);\nfor k = 1:numel(inputdata)\n inputdata{k} = hilbert(inputdata{k}')';\nend\n% NOTE by JM: Is it expected that the data has been bandpassfiltered at\n% this point? How would this be checked?\n\nnchan=size(inputdata{1},1);\ntrial_length=size(inputdata{1},2);\nph_min=0.1; % Eps of Eq.(17) of the manuscript\nf=(fs/trial_length)*(0:(trial_length-1));\nf_integr=(abs(f)ph_min); % Volume conduction suppression\n temp=(abs(temp)).^2;\n p_temp=sum(temp(f_integr))./sum(temp);\n p(kchan1, kchan2, ktime)=p_temp;\n p(kchan2, kchan1, ktime)=p_temp;\n end\n end\nend\n\np = permute(p, [3 1 2]); % permute to adhere to the conventional matrix shape of the ft_connectivity_* codebase\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_plm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5424643008390645}} {"text": "function [L,L_u,L_k] = pix2PluckerRay(k,u)\n\n% PIX2PLUCKERRAY Plucker ray from optical center through pixel.\n% PIX2PLUCKERRAY(K,U) is a Plucker line passing over pixel U and the\n% optical center, in a pin-Hole camera of intrinsic vector K.\n%\n% [R, R_k, R_u] = PIX2PLUCKERRAY(...) returns the Jacobians wrt K and U.\n\n% Copyright 2008-2009 Joan Sola @ LAAS-CNRS.\n\nif nargout == 1\n\n n = [0;0;0];\n v = invPinHole(u,1,k);\n\n L = [n;v];\n\nelse\n\n n = [0;0;0];\n [v,V_u,~,V_k] = invPinHole(u,1,k);\n\n L = [n;v];\n L_u = [zeros(3,2);V_u];\n L_k = [zeros(3,4);V_k];\n\nend\n\nreturn\n\n%%\nsyms u1 u2 u0 v0 au av real\nk = [u0;v0;au;av];\nu = [u1;u2];\n\n[L,L_u,L_k] = pix2PluckerRay(k,u);\n\nsimplify(L_u - jacobian(L,u))\nsimplify(L_k - jacobian(L,k))\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/pix2PluckerRay.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943822145998, "lm_q2_score": 0.7154239897159438, "lm_q1q2_score": 0.5421442803082979}} {"text": "function c = vertcat(varargin)\n% function C=vertcat(A,B);\n%\n% DESCRIPTION\n% Vertical concatenation of polynomial objects.\n%\n% INPUTS\n% A,B: polynomials\n%\n% OUTPUTS\n% C: vertical concatenation of input matrices.\n%\n% SYNTAX\n% [A; B]\n% Vertical concatenation of polynomial matrices A and B.\n% A and B must have the same number of columns.\n% [A1; A2; A3; ...]\n% Vertical concatenation of several polynomial matrices.\n% C = vertcat(A1,A2,A3,..);\n% Function-call form of vertical concatenation.\n%\n% See also horzcat\n\n% 6/8/2002: PJS Initial Coding\n\nif nargin==1\n c = varargin{1};\nelse\n % Promote a to polynomial\n a = polynomial(varargin{1});\n [nra,nca] = size(a);\n \n % Promote b to polynomial\n b = polynomial(varargin{2});\n [nrb,ncb] = size(b);\n \n if isempty(b);\n c = a;\n elseif isempty(a);\n c = b;\n elseif nca == ncb\n % Get Dimensions\n nta = size(a.degmat,1);\n nva = length(a.varname);\n ntb = size(b.degmat,1);\n nvb = length(b.varname);\n \n if nva==0 && nvb==0\n % Combine constant terms\n ar = combine(a);\n coef1 = reshape(ar.coefficient,[nra nca]);\n br = combine(b);\n coef2 = reshape(br.coefficient,[nrb ncb]);\n \n % Stack up Coefficients and Form Polynomial\n coefficient = [coef1; coef2];\n c = polynomial(coefficient);\n else\n % Form Degmat, Varname, and Matdim\n adeg = a.degmat;\n bdeg = b.degmat;\n degmat = blkdiag(adeg,bdeg);\n varname = [a.varname(:); b.varname(:)];\n matdim = [nra+nrb nca];\n \n % Stack up Coefficients\n idx1 = [];\n idx2 = [];\n for i1 = 0:(nca-1);\n idx1 = [idx1 (1:nra)+i1*(nra+nrb)];\n idx2 = [idx2 nra+(1:nrb)+i1*(nra+nrb)];\n end;\n coef1 = spalloc(nta,(nra+nrb)*nca,nnz(a.coefficient));\n coef1(:,idx1) = a.coefficient;\n coef2 = spalloc(ntb,(nra+nrb)*ncb,nnz(b.coefficient));\n coef2(:,idx2) = b.coefficient;\n coefficient = [coef1; coef2];\n \n % Form Polynomial and combine terms\n chkval = 0; % skip validity check\n c = polynomial(coefficient,degmat,varname,matdim,chkval);\n c = combine(c);\n end\n \n else\n error('All columns must have the same row dimension')\n end\n \n if nargin>2\n c = vertcat(c,varargin{3:end});\n end\nend\n\n\n", "meta": {"author": "yu-jiang", "repo": "radpbook", "sha": "88b9fa7d0a541099cdd1ac29383c89e087d1d895", "save_path": "github-repos/MATLAB/yu-jiang-radpbook", "path": "github-repos/MATLAB/yu-jiang-radpbook/radpbook-88b9fa7d0a541099cdd1ac29383c89e087d1d895/tools/SOSTOOLS.300/SOSTOOLS.300/multipoly/@polynomial/vertcat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.5421442770795282}} {"text": "function[varargout]=makefigs_gulftransfer(str)\n%MAKEFIGS_TRANSFER Makes all figures for Lilly and Elipot (2021).\n%\n% This function makes all figures for \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% This may take a while as some of the plots are computationally\n% intensive.\n% __________________________________________________________________\n% This is part of JLAB --- type 'help jlab' for more information\n% (C) 2021 J.M. Lilly --- type 'help jlab_license' for details\n\n\nif nargin==0\n str='noprint';\nend\n\nif strcmp(str,'--f')\n makefigs_gulfdrifters('noprint');return\nend\n\n%This is where you want things to be printed to\ndirname='/Users/lilly/Desktop/Dropbox/Projects/transfer/theory/figures';\n\n%/*************************************************************************\n%basic figure of transfer function\nrho=1027;\nfc=1e-4;\nomega=[-8.5:.01:8.5]*fc;\nz=[0:.1:50]';\nzo=20;\ndelta=20;zo=20;h=50;mu=delta.^2./zo;\nG1=rho.*fc.*windtrans(omega*24*3600,z,fc*24*3600,delta,mu,inf);\nG2=rho.*fc.*windtrans(omega*24*3600,z,fc*24*3600,delta,mu,50);\nG1(~isfinite(G1))=1e6;\n[ommat,zmat]=meshgrid(omega,z);\nzeta=2*sqrt(2)*frac(zo,delta).*sqrt((1+zmat./zo).*abs(1+ommat./fc));\n\n%str='Transfer Function Magnitude (m^2s/kg)';\nstr='Log10 Transfer Function Magnitude (m^{-1})';\n\nfigure,\nclf\nsubplot(1,2,1),contourf(omega./fc,z,log10(abs(G1))',-10:.1:6),nocontours,flipy,hold on\ntext(-8,48,'(a)','color','w')\nsubplot(1,2,2),contourf(omega./fc,z,log10(abs(G2))',-10:.1:6),nocontours,flipy,hold on\ntext(-8,48,'(b)','color','w')\n\nfor i=1:2\n subplot(1,2,i)\n caxis([-4 -1]),hlines(20,'0.5k:'),%vlines(-1,'w'),\n %hlines([10 40],'2w')\n if i==1\n hlines([10 40],'0.5D')\n else\n hlines([40],'0.5D')\n end\n xtick([-10:2:10])\n ylabel('Depth (m)')\n xlabel('Nondimensional Frequency $\\omega/|f|$','interpreter','latex')\n %contour(omega./fc,z,zeta,[4 7],'w','linewidth',2)\n contour(omega./fc,z,zeta,[4 7.5],'w')\nend\nsubplot(1,2,1)\ntext(-1,5,'I','color',[1 1 1],'HorizontalAlignment','center')\ntext(-1,25,'IV','color',[1 1 1],'HorizontalAlignment','center')\ntext(-1,45,'VII','color',[1 1 1],'HorizontalAlignment','center')\ntext(2,5,'II','color',[1 1 1]*0,'HorizontalAlignment','center')\ntext(-4,5,'II','color',[1 1 1]*0,'HorizontalAlignment','center')\ntext(1,25,'V','color',[1 1 1]*0,'HorizontalAlignment','center')\ntext(-3,25,'V','color',[1 1 1]*0,'HorizontalAlignment','center')\ntext(0.4,45,'VIII','color',[1 1 1]*0,'HorizontalAlignment','center')\ntext(-2.4,45,'VIII','color',[1 1 1]*0,'HorizontalAlignment','center')\ntext(5.5,5,'III','color',[1 1 1]*0,'HorizontalAlignment','center')\ntext(-7.5,5,'III','color',[1 1 1]*0,'HorizontalAlignment','center')\ntext(5.5,25,'VI','color',[1 1 1]*0,'HorizontalAlignment','center')\ntext(-7.5,25,'VI','color',[1 1 1]*0,'HorizontalAlignment','center')\ntext(5.5,45,'IX','color',[1 1 1],'HorizontalAlignment','center')\ntext(-7.5,45,'IX','color',[1 1 1],'HorizontalAlignment','center')\n\nsubplot(1,2,2)\n%text(-1,5,'I-$h$','color',[1 1 1],'HorizontalAlignment','center')\ntext(-1,25,'IV-$h$','color',[1 1 1],'HorizontalAlignment','center')\ntext(-1,45,'VII-$h$','color',[1 1 1]*0,'HorizontalAlignment','center')\n%text(2,5,'II-$h$','color',[1 1 1]*0,'HorizontalAlignment','center')\n%text(-4,5,'II-$h$','color',[1 1 1]*0,'HorizontalAlignment','center')\ntext(1,25,'V-$h$','color',[1 1 1]*0,'HorizontalAlignment','center')\ntext(-3,25,'V-$h$','color',[1 1 1]*0,'HorizontalAlignment','center')\ntext(0.4,45,'VIII-$h$','color',[1 1 1]*0,'HorizontalAlignment','center')\ntext(-2.4,45,'VIII-$h$','color',[1 1 1]*0,'HorizontalAlignment','center')\n%text(5.5,5,'III-$h$','color',[1 1 1]*0,'HorizontalAlignment','center')\n%text(-7.5,5,'III-$h$','color',[1 1 1]*0,'HorizontalAlignment','center')\ntext(5.5,25,'VI-$h$','color',[1 1 1]*0,'HorizontalAlignment','center')\ntext(-7.5,25,'VI-$h$','color',[1 1 1]*0,'HorizontalAlignment','center')\ntext(5.5,45,'IX-$h$','color',[1 1 1],'HorizontalAlignment','center')\ntext(-7.5,45,'IX-$h$','color',[1 1 1],'HorizontalAlignment','center')\n\nha=packfig(1,2,'col');\naxes(ha(1)),%ylim([0 62]),ytick([0:10:50])\nhc=colorbar('SouthOutside');\nhc.Label.String=str;\npos1=get(ha(1),'position');\npos2=get(ha(2),'position');\npos=get(hc,'position');%pos(4)=pos(4)/2;\n%set(hc,'position',[pos(1)+0.195 pos(2) pos(3) pos(4)])\nset(hc,'position',[pos(1)+0.195 pos(2)+.02 pos(3) pos(4)/2])\nset(ha(2),'position',[pos2(1) pos1(2) pos2(3) pos1(4)])\nset(ha(1),'position',pos1)\nfontsize 10 10 9 8\nset(gcf,'paperposition',[1 1 10 6])\nif strcmp(str,'print')\n jprint(dirname,'transferfunctionschematic')\nend\n% %--------------------------------------------------------------------------\n% %Green's function \n% rho=1027;\n% fc=1e-4;\n% %omega=[-100:.01:100]*fc;\n% omega=[-1000:.01:1000]*fc;\n% z=[0:.1:49.9]';\n% zo=20;\n% delta=20;zo=20;h=50;mu=delta.^2./zo;\n% %G1=rho.*fc.*windtrans(omega*24*3600,z,fc*24*3600,delta,mu,inf);\n% G2=rho.*fc.*windtrans(omega*24*3600,z,fc*24*3600,delta,mu,50);\n% g1=ifft(ifftshift(G1,1));\n% g2=ifft(ifftshift(G2,1));\n% \n% figure,\n% jpcolor(1:1e4,z,log10(abs(g2(1:1e4,:)))'),caxis([-7 -3.5]),flipy,hold on\n% contour(1:1e4,z,real(g2(1:1e4,:))',[0 0],'k')\n%\\*************************************************************************\n \n%/*************************************************************************\n%basic figure of transfer function, flower version\nrho=1027;\nfc=1e-4;\nomega=[-8.5:.01:8.5]*fc;\nz=[0:5:45]';\nzo=20;\ndelta=20;zo=20;h=50;mu=delta.^2./zo;\nlnomega=logspace(2,100,10000);\nomega=[-fliplr(lnomega) -100:.1:-8.6 -8.5:.001:-1-0.005 -1-0.005:1e-7:-1+0.005 -1+0.005:0.001 :8.5 8.6:.1:100 lnomega]*fc;\n\nG1=rho.*abs(fc).*windtrans(omega*24*3600,z,fc*24*3600,delta,mu,inf);\nG2=rho.*abs(fc).*windtrans(omega*24*3600,z,fc*24*3600,delta,mu,50);\nfigure\nclf,\nsubplot(1,2,1)\nhl=plot(G1);hold on,linestyle(hl,'0.5D'),\nhl=plot(G1(:,1)); linestyle(hl,'2k')\nhl=plot(G1(:,end));linestyle(hl,'2k--')\nsubplot(1,2,2)\nhl=plot(G2);hold on,linestyle(hl,'0.5D'),\nhl=plot(G2(:,1)); linestyle(hl,'2k')\nhl=plot(G2(:,end));linestyle(hl,'2k--')\nfor i=1:2\n subplot(1,2,i)\n axis square, axis equal\n if i==1\n axis([-.1 1.5 -.8 .8]),\n xtick([-0.8:.2:1.6])\n text(1.35,0.7,['(' setstr(96+i) ')'])\n elseif i==2\n axis([-.01 .13 -.07 .07])\n text(0.117,0.06,['(' setstr(96+i) ')'])\n end\n \n vlines(0,'0.5k:'),hlines(0,'0.5k:')\n xlabel('Real Part of $\\widetilde G(\\omega,z)$ (m$^{-1}$)','interpreter','latex')%(Dimensionless)')\n ylabel('Imaginary Part of $\\widetilde G(\\omega,z)$ (m$^{-1}$)','interpreter','latex')% (Dimensionless)')\n %xtick([-.4:.2:1.2]),ytick([-.6:.2:.6])\nend\nset(gcf,'paperposition',[1 1 10 5])\nif strcmp(str,'print')\n jprint(dirname,'schematicflowers')\nend\n%\\*************************************************************************\n\n\n%/*************************************************************************\n%green's functions for schematic\nrho=1027;\nfc=1e-4;\n%omega=[-100:.0001:100]*fc;\nomega=[-10000:.01:10000]*fc;\nz=[0:1/2:49.5]';\nzo=20;\ndelta=20;zo=20;h=50;mu=delta.^2./zo;\n\n[G1,G2]=vzeros(length(omega),length(z));\n\n%z=[0:5:45]';\nparfor i=1:length(z)\n i\n% G1(:,i)=rho.*abs(fc).*windtrans(omega*24*3600,z(i),fc*24*3600,delta,mu,inf);\n G2(:,i)=rho.*abs(fc).*windtrans(omega*24*3600,z(i),fc*24*3600,delta,mu,50);\nend\nG2(:,end+1)=1e-16+0*G2(:,end);\nz=[z;50];\n%g1=ifft(ifftshift(G1,1));\ng2=ifft(ifftshift(G2,1));\ng2=g2./maxmax(abs(g2));\n\n\n%fc=2 pi rad/ 10^4 seconds\n%fN= 2 pi rad\n%dt= 1/2 seconds\n%Tf = 2 pi / fc = 10^4 seconds \nt=[1:size(g2,1)]'*frac(1,2)./10^4;\n\nfigure\nii=1:40000;\nsubplot(3,1,1)\ncontourf(t(ii),z,log10(abs(g2(ii,:)))',[-10:.1:0]);nocontours,hold on,flipy\ncontour(t(ii),z,log10(abs(g2(ii,:)))',[-12:1:0],'w');\nhlines(z(1:10:end),'0.2D')\nhlines(z(1),'2k')\nhlines(z(end-10),'2k--')\n%contour(t(ii),z,real(g2(ii,:))',[0 0],'k:');\ncaxis([-5.5 -1.5]),ylim([-.01 49.999]),xlim([0 2]),xtick([0:.25:2])\nvlines(0.25005+[0:1/2:2],'0.25k:')\nylabel('Depth (m)')\ntext(1.875,2.5,'(a)','color','k')\nsubplot(3,1,2)\nh=plot(t(ii),real(g2(ii,1:10:end))*1000);ylim(1000*[-.009 .009]+1000*0.005)\nlinestyle(h,'0.5D'),linestyle(h(1),'2k'),linestyle(h(end-1),'2k--')\nylabel('Real Part of $g(t,z)$ ($\\times 1000 / \\mathrm{max}\\{g\\}$)','interpreter','latex')\ntext(1.875,12.7,'(b)','color','k')\nhold on,vlines(0.25005+[0:1/2:2],'0.25k:'),xtick([0:.25:2])\n%h=plot(t(ii),abs(g2(ii,1:10:end))*1000);\nsubplot(3,1,3)\nh=plot(t(ii),imag(g2(ii,1:10:end))*1000);ylim(1000*[-.009 .009])\nlinestyle(h,'0.5D'),linestyle(h(1),'2k'),linestyle(h(end-1),'2k--')\nylabel('Imaginary Part of $g(t,z)$ ($\\times 1000 / \\mathrm{max}\\{g\\}$)','interpreter','latex')\nxlabel('Time (Inertial Periods $2\\pi / f$)','interpreter','latex')\ntext(1.875,8,'(c)','color','k')\nhold on,vlines(0.25005+[0:1/2:2],'0.25k:'),xtick([0:.25:2])\npackfig(3,1)\n\nset(gcf,'paperposition',[1 1 5 10])\nif strcmp(str,'print')\n jprint(dirname,'greensfunction')\nend\n%\\*************************************************************************\n\nif 0\n%/*************************************************************************\n%green's functions for schematic\nrho=1027;\nfc=1e-4;\n%omega=[-100:.0001:100]*fc;\nomega=[-10000:.01:10000]*fc;\nz=[0:1/2:49.5]';\ndelta=20;zo=20;h=50;mu=delta.^2./zo;\ndelta=10;zo=10;h=50;mu=delta.^2./zo;\n\n[G1,G2]=vzeros(length(omega),length(z));\n\n%z=[0:5:45]';\nparfor i=1:length(z)\n i\n % G1(:,i)=rho.*abs(fc).*windtrans(omega*24*3600,z(i),fc*24*3600,delta,mu,inf);\n G2(:,i)=rho.*abs(fc).*windtrans(omega*24*3600,z(i),fc*24*3600,delta,mu,50);\nend\n%G1(~isfinite(G1))=0;\nG2(:,end+1)=1e-16+0*G2(:,end);\nz=[z;50];\n%g1=ifft(ifftshift(G1,1));\ng2=ifft(ifftshift(G2,1));\ng2=g2./maxmax(abs(g2));\n\n\n%fc=2 pi rad/ 10^4 seconds\n%fN= 2 pi rad\n%dt= 1/2 seconds\n%Tf = 2 pi / fc = 10^4 seconds \nt=[1:size(g2,1)]'*frac(1,2)./10^4;\n\nclf\nii=1:40000;\nsubplot(3,1,1)\ncontourf(t(ii),z,log10(abs(g2(ii,:)))',[-12:.1:0]);nocontours,hold on,flipy\ncontour(t(ii),z,log10(abs(g2(ii,:)))',[-12:1/2:0],'w');\nhlines(z(1:10:end),'0.2D'),hlines(z(1),'2k'),hlines(z(end-10),'2k--')\n%contour(t(ii),z,real(g2(ii,:))',[0 0],'k:');\ncaxis([-5.5 -1.5]),ylim([-.01 49.999]),xlim([0 2]),xtick([0:.25:2])\nvlines(0.25005+[0:1/2:2],'0.25k:')\nylabel('Depth (m)')\ntext(1.875,2.5,'(a)','color','k')\nsubplot(3,1,2)\nh=plot(t(ii),real(g2(ii,1:10:end))*1000);ylim(1000*[-.009 .009]+1000*0.005-1.5)\nlinestyle(h,'0.5D'),linestyle(h(1),'2k'),linestyle(h(end-1),'2k--')\nylabel('Real Part of $g(t,z)$ ($\\times 10^3 / \\mathrm{max}\\{g\\}$)','interpreter','latex')\ntext(1.875,12.7-1.5,'(b)','color','k')\nhold on,vlines(0.25005+[0:1/2:2],'0.25k:'),xtick([0:.25:2])\n%h=plot(t(ii),abs(g2(ii,1:10:end))*1000);\nsubplot(3,1,3)\nh=plot(t(ii),imag(g2(ii,1:10:end))*1000);ylim(1000*[-.009 .009])\nlinestyle(h,'0.5D'),linestyle(h(1),'2k'),linestyle(h(end-1),'2k--')\nylabel('Imaginary Part of $g(t,z)$ ($\\times 10^3 / \\mathrm{max}\\{g\\}$)','interpreter','latex')\ntext(1.875,8,'(c)','color','k')\nhold on,vlines(0.25005+[0:1/2:2],'0.25k:'),xtick([0:.25:2])\nxlabel('Time (Inertial Periods $2\\pi / f$)','interpreter','latex')\n% subplot(4,1,4)\n% %gke=5*fliplr(log10(cumsum(squared(fliplr(g2)),2)));\n% gke=5*log10(cumsum(squared(g2),2));\n% contourf(t(ii),z,gke(ii,:)',[-50:.5:0]);nocontours,hold on,flipy\n% contour(t(ii),z,gke(ii,:)',[-50:5:0],'w');\n% hlines(z(1:10:end),'0.2D'),hlines(z(1),'2k'),hlines(z(end-10),'2k--')\n% caxis([-40 -5]),ylim([-.01 49.999]),xlim([0 2]),xtick([0:.25:2])\n% vlines(0.25005+[0:1/2:2],'0.25k:')\n% text(1.875,2.5,'(d)','color','k')\n% %ylabel('Kinetic Energy $\\int_{-h}^z |g(t,x)|^2 \\mathrm{d}x$')\n% ylabel('Kinetic Energy $\\int_{0}^z |g(t,x)|^2 \\mathrm{d}x$')\n% xlabel('Time (Inertial Periods $2\\pi / f$)','interpreter','latex')\n% packfig(4,1)\n%set(gcf,'paperposition',[1 1 5 13])\n\npackfig(3,1)\nset(gcf,'paperposition',[1 1 5 10])\nif strcmp(str,'print')\n jprint(dirname,'greensfunction_broader')\nend\n%\\*************************************************************************\nend\n\n\n%/*************************************************************************\n%illustration of problems with overflow\nlog10delta=linspace(-1,4,100);\nlog10mu=linspace(-7,4,100);\nh=100;\n%h=1000;\n%h=1e6;\n%h=1e8;\nfc=1e-4;\n\nGi1=vzeros(length(log10mu),length(log10delta));\nGi2=vzeros(length(log10mu),length(log10delta));\nGi3=vzeros(length(log10mu),length(log10delta));\nGi4=vzeros(length(log10mu),length(log10delta));\n%f=0;\nf=2.*fc*24*3600;\n%f=fc*24*3600*0.99;\n%f=fc*24*3600*8;\ntic\nfor i=1:length(log10mu)\n i\n for j=1:length(log10delta)\n Gi1(i,j)=windtrans(f,15,fc*24*3600,10.^log10delta(j),10.^log10mu(i),h,'two');\n Gi2(i,j)=windtrans(f,15,fc*24*3600,10.^log10delta(j),10.^log10mu(i),h,'far');\n Gi3(i,j)=windtrans(f,15,fc*24*3600,10.^log10delta(j),10.^log10mu(i),h,'general');\n Gi4(i,j)=windtrans(f,15,fc*24*3600,10.^log10delta(j),10.^log10mu(i),h,'expansion');\n end\nend\n%etime1=toc\n%etime2=toc\n\nfigure,\nclf\nsubplot(1,3,1),contourf(log10delta,log10mu,log10(abs(Gi3)),[-200:.1:0]),nocontours,hold on\ncontour(log10delta,log10mu,log10(abs(Gi3)),[-200:10:0],'w'),caxis([-12 maxmax(log10(abs(Gi1)))])\nhc=colorbar('South');\nhc.Label.String='Log10 Magnitude at $\\omega = -2f$';\nhc.Label.Interpreter='latex';\npos=get(hc,'position');\nset(hc,'position',[pos(1)+pos(1)/10 pos(2) pos(3)+pos(1)/10 pos(4)/2])\nsubplot(1,3,2),contourf(log10delta,log10mu,log10(abs(Gi1)),[-200:.1:0]),nocontours,hold on\ncontour(log10delta,log10mu,log10(abs(Gi1)),[-200:10:0],'w'),caxis([-12 maxmax(log10(abs(Gi1)))])\nsubplot(1,3,3),contourf(log10delta,log10mu,log10(abs(Gi2-Gi4)./abs(Gi4)),[-14:.1:0]),nocontours,hold on\ncaxis([-14 -3])\nhc2=colorbar('North');\nhc2.Label.String='Log10 Fractional Error at $\\omega = -2f$';\nhc2.Label.Interpreter='latex';\npos2=get(hc2,'position');\nset(hc2,'position',[pos2(1)-pos2(1)/28 pos2(2)-0.03 pos2(3)+pos(1)/10 pos2(4)/2])\n\n[demat,mumat]=meshgrid(10.^log10delta,10.^log10mu);\nfor i=1:3\n subplot(1,3,i),%contour(log10delta,log10mu,log10(abs(Gi1-Gi2)./abs(Gi1)),[-3.4 -3.4],'k','linewidth',2)\n text(3.5,3.7,['(' setstr(96+i) ')'],'color','k')\n xlim([-1 3.99])\n axis equal,xlim([-1 3.99]),ylim([-5 4])\n ylabel('Log10 Madsen Depth $\\mu$ (m)','interpreter','latex')\n xlabel('Log10 Ekman Depth $\\delta$ (m)','interpreter','latex')\n %contour(log10delta,log10mu,log10(demat./mumat*2*sqrt(2)*sqrt(3)),[1 1]*3,'color',[1 1 1]*0.6,'linewidth',2)\n contour(log10delta,log10mu,log10(demat./mumat*2*sqrt(2)*sqrt(3)),[1 1]*2.9,'color',[1 1 1]*0.6,'linewidth',2)\nend\npackfig(1,3,'columns')\nset(hc,'position',[pos(1)+pos(1)/10 pos(2)+.1 pos(3)+pos(1)/10 pos(4)/2])\nset(hc2,'position',[pos2(1)-pos2(1)/28 pos2(2)-0.03-.07 pos2(3)+pos(1)/10 pos2(4)/2])\n%set(gcf,'paperposition',[1 1 11 5])\nset(gcf,'paperposition',[1 1 11 8])\nif strcmp(str,'print')\n jprint(dirname,'overflowproblem')\nend\n%\\*************************************************************************\n\n\n%/*************************************************************************\n%symmetry plots\nrho=1027;\n%log10delta=linspace(-1,4,101);\n%log10mu=linspace(-7,4,100);\nlog10delta=linspace(-4,4,201);\nlog10mu=linspace(-8,4,200);\n%h=10000;\nh=[16 1e2 1e3 1e4 1e5 1e6];\n%h=[15.01 15.1 16 26 1e2 1e3 1e4 1e5 1e6];\nfc=1e-4;\n\n\n[demat,mumat]=meshgrid(10.^log10delta,10.^log10mu);\nzomat=demat.^2./mumat;\n\nA=zeros(size(demat,1),size(demat,2),length(h));\nA0=zeros(size(demat,1),size(demat,2),length(h));\nfor i=1:length(h)\n A(:,:,i)=frac(2,mumat).*log(frac(1+h(i)./zomat,1+15./zomat));\n A0(:,:,i)=frac(2,mumat).*log(1+h(i)./zomat);\nend \n\n%Gf=vzeros(length(log10mu),length(log10delta),length(h));\n%Gf0=vzeros(length(log10mu),length(log10delta),length(h));\n% for i=1:length(log10mu)\n% i\n% parfor j=1:length(log10delta)\n% for k=1:6\n% Gf(i,j,k)=rho.*fc.*windtrans(-fc*24*3600,15,fc*24*3600,10.^log10delta(j),10.^log10mu(i),h(k));\n% Gf0(i,j,k)=rho.*fc.*windtrans(-fc*24*3600,0,fc*24*3600,10.^log10delta(j),10.^log10mu(i),h(k));\n% end\n% end\n% end\n% maxmax(abs(A-Gf))\n% maxmax(abs(A0-Gf0))\n% jpcolor(log10(abs(A(:,:,1)-Gf(:,:,1))./A(:,:,1)))\n% %these agree to the numerical noise level\n\nomega=[-3:.001:1]*fc;\nlog10zo=[-12:.1:12]';\nii=1:10:length(log10zo);\n\nclear dei mui dei0 mui0 dei1 mui1\nzo=10.^log10zo;\nfor j=1:length(h)\n dei{j,1}=sqrt(frac(2*zo,1).*log(frac(1+h(j)./zo,1+15./zo)));\n mui{j,1}=dei{j}.^2./zo;\n dei1{j,1}=sqrt(frac(2*zo,10).*log(frac(1+h(j)./zo,1+15./zo)));\n mui1{j,1}=dei1{j}.^2./zo;\n dei0{j,1}=sqrt(frac(2*zo,1).*log(frac(1+h(j)./zo,1)));\n mui0{j,1}=dei0{j}.^2./zo;\nend\n%--------------------------------------------------------------------------\nfigure,\nclf\ncontourf(log10delta,log10mu,log10(A(:,:,3)),[-10:.1:10]),nocontours,hold on\ncontour(log10delta,log10mu,log10(A(:,:,3)),[0 0 ],'k','linewidth',1.5)\ncontour(log10delta,log10mu,log10(A(:,:,3)),[-10:1:10],'k','linewidth',0.5)\ncontour(log10delta,log10mu,log10(zomat),[-20:20],'w','linewidth',0.5)\ncontour(log10delta,log10mu,log10(zomat),[0 0],'w','linewidth',1.5)\nplot(log10(dei{3}(1:10:end)),log10(mui{3}(1:10:end)),'ko','markerfacecolor','k','markersize',4)\ncaxis([-4.7 7.3]),axis equal,ylim([-7 4]),xlim([-4 4]),\nylabel('Log10 Madsen Depth $\\mu$ (m)','interpreter','latex')\nxlabel('Log10 Ekman Depth $\\delta$ (m)','interpreter','latex')\nhc=colorbar('SouthOutside');\nhc.Label.String='Log10 Inertial Amplitude A (m$^{-1}$)';\nhc.Label.Interpreter='latex';\nhc.Ticks=[-4:1:8];\nset(gcf,'paperposition',[1 1 4*1.5 5*1.5])\n%text(-0.92,3.7,'M'),text(3.8,-6.8,'E')\ntext(-3.925,3.7,'M'),text(3.7,-6.8,'E','color','w')\nif strcmp(str,'print')\n jprint(dirname,'deltamuplane')\nend\n%--------------------------------------------------------------------------\n%figure,cellplot(dec,muc)\n%figure,cellplot(dec0,muc0)\nomega=[-100:.1:-8.6 -8.5:.001:-1-0.005 -1-0.005:1e-7:-1+0.005 -1+0.005:0.001:8.5 8.6:.1:100]*fc;\n%omega=[-1e4:10:-1000 -1000:1:-100 -100:.1:-8.6 -8.5:.001:-1-0.005 -1-0.005:1e-7:-1+0.005 -1+0.005:0.001 :8.5 8.6:.1:100 100:1:1000 1000:10:1e4]*fc;\nG=nan*zeros(length(omega),length(ii),length(h));\n[Gm,Ge,Gminf,Geinf]=vzeros(length(omega),length(h));\n%G0=nan*zeros(length(omega),length(ii),length(h));\n%G1=nan*zeros(length(omega),length(ii),length(h));\nfor j=1:size(G,3)\n j\n Gm(:,j)=rho.*abs(fc).*windtrans(omega*24*3600,15,fc*24*3600,0,mui{j}(1),h(j));\n Ge(:,j)=rho.*abs(fc).*windtrans(omega*24*3600,15,fc*24*3600,dei{j}(end),0,h(j));\n parfor k=1:length(ii)\n k\n G(:,k,j)=rho.*abs(fc).*windtrans(omega*24*3600,15,fc*24*3600,dei{j}(ii(k)),mui{j}(ii(k)),h(j));\n %G1(:,k,j)=rho.*abs(fc).*windtrans(omega*24*3600,15,fc*24*3600,dei1{j}(ii(k)),mui1{j}(ii(k)),h(j));\n %G0(:,k,j)=rho.*abs(fc).*windtrans(omega*24*3600,0,fc*24*3600,dei0{j}(ii(k)),mui0{j}(ii(k)),h(j));\n end\nend\n%--------------------------------------------------------------------------\nfigure\nclf\n%[~,jj]=min(abs(omega));\nfor j=1:size(G,3)\n subplot(2,3,j)\n hl=plot(G(:,:,j));axis equal, axis square\n axis([-.3 1 -.65 .65]*1.05),vlines(0,'0.5k:'),hlines(0,'0.5k:')\n linestyle(hl,'0.5D')\n hl=plot(G(:,1,j));linestyle(hl,'2k--')\n hl=plot(G(:,end,j));linestyle(hl,'2k')\n hl=plot(Ge(:,j));linestyle(hl,'0.5w')\n hl=plot(Gm(:,j));linestyle(hl,'0.5k')\n text(0.9,0.59,['(' setstr(96+j) ')'])\n% xlabel('Real Part of Transfer Function (m^2s / kg)')%(Dimensionless)')\n% ylabel('Imaginary Part of Transfer Function (m^2s / kg)')% (Dimensionless)') \n xlabel('Real Part of $\\widetilde G(\\omega,15$ m$)$ (m$^{-1}$)','interpreter','latex')%(Dimensionless)')\n ylabel('Imaginary Part of $\\widetilde G(\\omega,15$ m$)$ (m$^{-1}$)','interpreter','latex')% (Dimensionless)')\n xtick([-.4:.2:1.2]),ytick([-.6:.2:.6])\n %plot(G(jj,:,j),'ko','markerfacecolor','k','markersize',4)\nend\npackfig(2,3)\nset(gcf,'paperposition',[1 1 9.4 6])\nfontsize 10 10 9 9\nif strcmp(str,'print')\n jprint(dirname,'similarflowers')\nend\n%%check invariance\n%figure,plot(G(:,:,1)),hold on,plot(G1(:,:,1)/10,'r')\n%figure,plot(G(:,:,end)),hold on,plot(G1(:,:,end)/10,'r')\n% %--------------------------------------------------------------------------\n% figure\n% clf\n% for j=1:size(Gf,3)\n% subplot(2,3,j)\n% hl=plot(omega./fc,abs(G(:,2:end-1,j)));hold on\n% axis([-1.99 0 1.001*1e-4 1.25]),ylog \n% linestyle(hl,'0.5D')\n% hl=plot(omega./fc,abs(G(:,1,j)));\n% linestyle(hl,'2k')\n% hl=plot(omega./fc,abs(G(:,end,j)));\n% linestyle(hl,'2k--')\n% ylabel('Log10 Magnitude of $G(\\omega,15$ m$)$','interpreter','latex')\n% xlabel('Nondimensional Frequency $\\omega/f$','interpreter','latex')\n% text(-.17,0.8,['(' setstr(96+j) ')'])\n% xtick([-2:.5:0])\n% vlines(-1,'0.5k:')\n% end\n% packfig(2,3)\n% set(gcf,'paperposition',[1 1 9*1.25 5*1.25])\n% jprint(dirname,'similarmagnitudes')\n% %--------------------------------------------------------------------------\n% figure\n% clf\n% for j=1:size(Gf,3)\n% subplot(2,3,j)\n% hl=plot(omega./fc,(360/2/pi)*unwrap(angle(G(:,2:end-1,j))));hold on\n% axis([-1.99 0 -179.9 180]),\n% linestyle(hl,'0.5D')\n% hl=plot(omega./fc,(360/2/pi)*unwrap(angle(G(:,1,j))));\n% linestyle(hl,'2k')\n% hl=plot(omega./fc,(360/2/pi)*unwrap(angle(G(:,end,j))));\n% linestyle(hl,'2k--')\n% ylabel('Angle of $G(\\omega,15$ m$) (degrees) $','interpreter','latex')\n% xlabel('Nondimensional Frequency $\\omega/f$','interpreter','latex')\n% %text(-.17,0.8,['(' setstr(96+j) ')'])\n% xtick([-2:.5:0])\n% vlines(-1,'0.5k:')\n% end\n% packfig(2,3)\n% set(gcf,'paperposition',[1 1 9*1.25 5*1.25])\n% jprint(dirname,'similarphases')\n%--------------------------------------------------------------------------\n% figure\n% clf\n% for j=1:size(Gf0,3)\n% subplot(2,3,j)\n% hl=plot(G0(:,2:end-1,j));axis equal, axis square\n% axis([-.05 1.05 -.505 .505]),vlines(0,'0.5k:'),hlines(0,'0.5k:')\n% linestyle(hl,'0.5D'),\n% hl=plot(G0(:,end,j)); linestyle(hl,'2k')\n% hl=plot(G0(:,1,j));linestyle(hl,'2k--')\n% text(0.9,0.44,['(' setstr(96+j) ')'])\n% xlabel('Real Part of $G(\\omega,0$ m$)$','interpreter','latex')%(Dimensionless)')\n% ylabel('Imaginary Part of $G(\\omega,0$ m$)$','interpreter','latex')% (Dimensionless)') \n% xtick([-.4:.2:1.2]),ytick([-.6:.2:.6])\n% end\n% packfig(2,3)\n% set(gcf,'paperposition',[1 1 9.4 6])\n% jprint(dirname,'similarflowers0')\nlnomega=logspace(2,100,10000);\nomega=[-fliplr(lnomega) -100:.1:-8.6 -8.5:.001:-1-0.005 -1-0.005:1e-7:-1+0.005 -1+0.005:0.001 :8.5 8.6:.1:100 lnomega]*fc;\nG0=vzeros(length(omega),length(ii));\nGm0=rho.*abs(fc).*windtrans(omega*24*3600,0,fc*24*3600,0,mui0{3}(1),h(3));\nGe0=rho.*abs(fc).*windtrans(omega*24*3600,0,fc*24*3600,dei0{3}(end),0,h(3));\n%Gm0=rho.*abs(fc).*windtrans(omega*24*3600,1e-10,fc*24*3600,0,mui0{3}(ii(end)),h(3));\n%Ge0=rho.*abs(fc).*windtrans(omega*24*3600,0,fc*24*3600,dei0{3}(ii(1)),0,h(3));\n%zeta=2*sqrt(2)*frac(zo,delta).*sqrt(abs(1+ommat./fc));\n\nfor k=1:length(ii)\n k\n G0(:,k)=rho.*abs(fc).*windtrans(omega*24*3600,0,fc*24*3600,dei0{3}(ii(k)),mui0{3}(ii(k)),h(3));\n % G1(:,k)=rho.*abs(fc).*windtrans(omega*24*3600,0,fc*24*3600,dei0{3}(ii(k)),mui0{3}(ii(k)),h(1));\nend\nfigure\nclf\nhl=plot(G0);axis equal, axis square\naxis([-.05 1.05 -.505 .505]),vlines(0,'0.5k:'),hlines(0,'0.5k:')\nlinestyle(hl,'0.5D'),\nhl=plot(G0(:,1)); linestyle(hl,'2k--')\nhl=plot(G0(:,end)); linestyle(hl,'2k')\nhl=plot(Ge0); linestyle(hl,'0.5w')\nhl=plot(Gm0);linestyle(hl,'0.5k')\n%text(0.9,0.44,['(' setstr(96+j) ')'])\nxlabel('Real Part of $\\widetilde G(\\omega,0$ m$)$ (m$^{-1}$)','interpreter','latex')%(Dimensionless)')\nylabel('Imaginary Part of $\\widetilde G(\\omega,0$ m$)$ (m$^{-1}$)','interpreter','latex')% (Dimensionless)')\nxtick([-.4:.2:1.2]),ytick([-.6:.2:.6])\nset(gcf,'paperposition',[1 1 4 4])\nplot(2*h(3)/squared(dei0{3}(end)),0,'wo','markerfacecolor','k')\nfontsize 10 10 9 9\nif strcmp(str,'print')\n jprint(dirname,'similarflowers0')\nend\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/jFigures/makefigs_transfer.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257653, "lm_q2_score": 0.6688802603710085, "lm_q1q2_score": 0.542113349580511}} {"text": "function T = EinsteinSum(varargin)\n% tensor multiplication according to Einstein summation convention\n%\n% Description\n% This function computes a tensor product according to Einstein summation\n% convention\n%\n% Syntax\n% % sumation against dimension 1 and 2\n% C = EinsteinSum(E,[1 -1 2 -2],v,-1,v,-2) \n%\n% eps = EinsteinSum(C,[-1 1 -2 2],sigma,[-1 -2])\n%\n% Input\n% T1,T2 - @tensor\n% dimT1 - vector of indices giving the summation order in tensor 1\n% dimT2 - vector of indices giving the summation order in tensor 2\n%\n% Output\n% T - @tensor\n%\n% See also\n%\n\n% TODO: check for correct symmetries !!!\n\nglobal useBSXFUN;\n\nM1 = 1; dimT1 = [];\nT = varargin{1};\n\n% for each tensor in varargin\niv = 1;\nwhile iv < length(varargin) && ~ischar(varargin{iv})\n\n % take new vector from varargin\n M2 = varargin{iv};\n dimT2 = varargin{iv+1};\n iv = iv+2;\n \n % convert to double\n if isa(M2,'tensor')\n M2 = M2.M;\n elseif isa(M2,'quaternion')\n M2 = matrix(M2);\n elseif isa(M2,'vector3d')\n M2 = double(M2);\n M2 = permute(M2,[3 1 2]);\n end\n \n %\n if length(dimT2) > 1 && sum(dimT2<0)>1 && max(accumarray(-dimT2(dimT2<0).',1)>1)\n [M2,dimT2] = innerSum(M2,dimT2);\n end\n \n % reorder T1 such that [-rDel ... -3 -2 -1 1 2 3 .. rOut x x x]\n rOut = max([0,dimT1,dimT2]);\n rDel = -min([0,dimT1,dimT2]);\n rExt = max([0,ndims(M1) - length(dimT1), ndims(M2) - length(dimT2)]);\n \n % new order of dimensions for tensor 1\n dimT1(dimT1>0) = dimT1(dimT1>0) - 1; % we should start with zero to avoid the cap\n exp1 = 1:rOut + rDel; exp1(dimT1 + rDel + 1) = []; % dimensions in reserve \n order1 = [dimT1 + rDel + 1,... the tensor components\n rOut + rDel + (1:rExt),... none tensor components \n exp1];\n \n % new order of dimensions for tensor 2\n dimT2(dimT2>0) = dimT2(dimT2>0) - 1; % we should start with zero to avoid the cap\n exp2 = 1:rOut + rDel; exp2(dimT2 + rDel + 1) = []; % dimensions in reserve \n order2 = [dimT2 + rDel + 1,... the tensor components\n rOut + rDel + (1:rExt),... none tensor components \n exp2];\n \n M1 = ipermute(M1,order1);\n M2 = ipermute(M2,order2);\n \n if useBSXFUN\n M1 = bsxfun(@times, M1, M2);\n else\n M1 = M1 .* M2;\n end\n \n % setup dimT1\n dimT1 = [-rDel:-1,1:rOut];\n \nend\n\n% sum over the dimensions to be removed\nif useBSXFUN\n for d = 1:rDel, M1 = sum(M1,d); end\nelse\n if rDel>0, M1 = sum(M1,1:rDel); end\nend\n\n% and remove these leading dimensions\ns = size(M1);\nM1 = reshape(M1,[s(rDel+1:end) 1 1]);\n\n% rank 0 tensor should become double\nif rOut == 0\n T = M1; \nelseif strcmp(class(T),'tensor') || check_option(varargin(iv:end),'keepClass')\n T.M = M1;\n T.rank = rOut;\nelse\n T = tensor(M1,T.CS,'noCheck','rank',rOut,varargin{iv:end});\nend\n\nend\n\n%%\nfunction [M,ind] = innerSum(M,ind)\n\n% find indices to be summed\n[a,b] = findDouble(ind);\n\nif isempty(a), return;end\n\nind([a,b]) = [];\n\n% remember size of matrix\nsM = size(M);\nsM([a,b]) = [];\n\n% make a,b the first two dimensions\norder = 1:max([ndims(M) a b]);\norder([a b]) = [];\norder = [a b order];\nM = permute(M,order);\n\n% reduces multiple remove dimensions to one\nM = reshape(M,3^numel(a),3^numel(b),[]);\n\n% sum along the diagonal of the first two dimensions\nN = zeros(1,1,size(M,3));\nfor l = 1:3^numel(a)\n N = N + M(l,l,:);\nend\n\n% reshape back\nM = reshape(N,[sM 1 1]);\n\nend\n\n%%\nfunction [a,b] = findDouble(x)\n\n%if length(x) <= 1 || all(x>=0) || sum(x<0)<2 || max(accumarray(-x(x<0).',1))<2\n% a = [];\n% b = [];\n% return;\n%end\n\nd = bsxfun(@minus,x,x') == 0 & bsxfun(@times,x<0,x'<0);\nd = d & ~tril(ones(size(d)));\n[a,b] = find(d);\na = a'; b = b';\n \nend\n", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/TensorAnalysis/@tensor/EinsteinSum.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5421114522209476}} {"text": "%+========================================================================+\n%| |\n%| This script uses 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%| francois.alouges@polytechnique.edu |\n%| WEBSITE : www.cmap.polytechnique.fr/~aussal/gypsilab      |\n%| |\n%| Please acknowledge the gypsilab toolbox in programs or publications in |\n%| which you use it. |\n%|________________________________________________________________________|\n%| '&` | |\n%| # | FILE : nrtDomRegularize2D.m |\n%| # | VERSION : 0.50 |\n%| _#_ | AUTHOR(S) : Matthieu Aussal |\n%| ( # ) | CREATION : 25.11.2018 |\n%| / 0 \\ | LAST MODIF : 25.11.2018 |\n%| ( === ) | SYNOPSIS : Singular kernel regularization (in debug mode)|\n%| `---' | |\n%+========================================================================+\n\n% Cleaning\nclear all\nclose all\nclc\n\n% Gypsilab path\nrun('../../addpathGypsilab.m')\n\n% Parameters\nN = 1e2;\ngss = 3;\n\n% Spherical mesh\ncircle = mshCircle(N,1);\n\n% Square mesh\nsquare = mshSquare(2*N,[3 3]);\n\n% Graphical representation\nfigure\nplot(circle)\nhold on\nplot(square,'w')\naxis equal\nalpha(0.5)\n\n% Domain\nsigma = dom(circle,gss); \n\n% Finite elements\nu = fem(circle,'P0');\nv = fem(circle,'P1');\n\n% Gren kernel\nGxy = @(X,Y) femGreenKernel(X,Y,'[log(r)]',[]);\ndyGxy{1} = @(X,Y) femGreenKernel(X,Y,'grady[log(r)]1',[]);\ndyGxy{2} = @(X,Y) femGreenKernel(X,Y,'grady[log(r)]2',[]);\ndyGxy{3} = @(X,Y) femGreenKernel(X,Y,'grady[log(r)]3',[]);\n\n% Single radiation P0\nM = integral(square.vtx,sigma,Gxy,u);\nMr = regularize(square.vtx,sigma,'[log(r)]',u);\nnorm(M+Mr,'inf')\n\n% Double radiation P0\nM = integral(square.vtx,sigma,dyGxy,ntimes(u));\nMr = regularize(square.vtx,sigma,'grady[log(r)]',ntimes(u));\nnorm(M+Mr,'inf')\n\n% Single radiation P1\nM = integral(square.vtx,sigma,Gxy,v);\nMr = regularize(square.vtx,sigma,'[log(r)]',v);\nnorm(M+Mr,'inf')\n\n% Single layer P0\nM = integral(sigma,sigma,u,Gxy,u);\nMr = regularize(sigma,sigma,u,'[log(r)]',u);\nnorm(M+Mr,'inf')\n\n% Double layer P0\nM = integral(sigma,sigma,u,dyGxy,ntimes(u));\nMr = regularize(sigma,sigma,u,'grady[log(r)]',ntimes(u));\nnorm(M+Mr,'inf')\n\n% Single layer P1\nM = integral(sigma,sigma,u,Gxy,v);\nMr = regularize(sigma,sigma,u,'[log(r)]',v);\nnorm(M+Mr,'inf')\n\n% Hypersingular P1\nM = integral(sigma,sigma,ntimes(u),Gxy,ntimes(v));\nMr = regularize(sigma,sigma,ntimes(u),'[log(r)]',ntimes(v));\nnorm(M+Mr,'inf')\n\nM = integral(sigma,sigma,nxgrad(u),Gxy,nxgrad(v));\nMr = regularize(sigma,sigma,nxgrad(u),'[log(r)]',nxgrad(v));\nnorm(M+Mr,'inf')\n\n\n\ndisp('~~> Michto gypsilab !')\n\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/domainQuadrature/nrtDomRegularize2D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511396138366, "lm_q2_score": 0.63341027059799, "lm_q1q2_score": 0.5421049019343984}} {"text": "function out = forces_moments_wing(x, delta, wind, ~, p_drone, p_physics)\n\n% FORCES_MOMENTS - Computes the forces and moments acting on the UAV.\n%\n% Inputs:\n% x - state variables\n% delta - actuators values (angles,...)\n% wind - wind parameters\n% P - general parameters\n% Outputs:\n% out\n% F - forces\n% M - moments\n% Va - airspeed\n% alpha - angle of attack\n% beta - sideslip angle\n% wind - wind vector in the inertial frame\n%\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Variables and Inputs\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% UAV velocity wrt inertial frame in body frame\nv_xyz = x(4:6);\n\n% Euler angles\nphi = x(7);\ntheta = x(8);\npsi = x(9);\n\n% Rotation rates\np = x(10);\nq = x(11);\nr = x(12);\n\n% Actuators fixed-wing\nde = delta(1); % delta elevator\nda = delta(2); % delta aileron\ndr = delta(3); % delta rudder\ndt = delta(4); % delta thrust\n\nRbi = Rb2i(phi,theta,psi);\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Wind computation\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nws_ned = wind(1:3); % steady wind in NED frame\nwg_xyz = wind(4:6); % gusts along body xyz axis\n\n% Gust in NED frame = Rib * gust in Body frame\nwg_ned = Rbi * wg_xyz;\n\n% Wind in NED = steady in NED + gust in NED\nw_ned = ws_ned + wg_ned;\nwn = w_ned(1);\nwe = w_ned(2);\nwd = w_ned(3);\n\n%Steady wind in body (xyz) frame\nRib = Rbi';\nws_xyz = Rib * ws_ned;\n\n% Wind in body frame\nw_xyz = ws_xyz + wg_xyz;\n\n% Compute air data wrt the inertial frame, in the body frame\nva_xyz = v_xyz - w_xyz;\nvax = va_xyz(1);\nvay = va_xyz(2);\nvaz = va_xyz(3);\n\n% Airspeed norm (=V_inifity)\nVa = norm(va_xyz);\n\nif vax ~= 0\n alpha = atan2(vaz, vax);\nelse\n alpha = 0;\nend\n\nif Va ~=0\n beta = asin(vay / Va);\nelse\n beta = 0;\nend\n\n% Relabel\nca = cos(alpha);\nsa = sin(alpha);\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Compute forces on fixed wing\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% Aerodynamic coefficients in function of alpha\n% Lift and Drag Coefficients\nCL = p_drone.CL0 + p_drone.CL_alpha * alpha;\nCD = p_drone.CD0 + p_drone.CD_alpha * alpha;\n\n% Lift and Drag expressed in body frame\nCx = - CD * ca + CL * sa;\nCx_q = - p_drone.CD_q * ca + p_drone.CL_q * sa;\nCx_de = - p_drone.CD_de * ca + p_drone.CL_de * sa;\nCz = - CD * sa - CL * ca;\nCz_q = - p_drone.CD_q * sa - p_drone.CL_q * ca;\nCz_de = - p_drone.CD_de * sa - p_drone.CL_de * ca;\n\n% Weight\nweight = p_drone.mass * p_physics.gravity * [-sin(theta);...\n cos(theta) * sin(phi);...\n cos(theta) * cos(phi)];\n\n% Aerodynamic forces\np_dyn = 0.5 * p_physics.rho * Va^2;\n\nif Va ~= 0\n kc = 0.5*p_drone.c/Va;\n kb = 0.5*p_drone.b/Va;\nelse\n kc = 0;\n kb = 0;\nend\n\nf_drag = p_dyn * p_drone.S_wing * ...\n [Cx + Cx_q*kc*q + Cx_de*de; ...\n p_drone.CY0 + p_drone.CY_beta*beta + p_drone.CY_p*kb*p + p_drone.CY_r*kb*r + p_drone.CY_da*da + p_drone.CY_dr*dr;...\n Cz + Cz_q*kc*q + Cz_de*de];\n\n% Thrust force\nf_thrust = 0.5*p_physics.rho*p_drone.S_prop*p_drone.C_prop*...\n [(p_drone.k_motor*dt)^2-Va^2; 0; 0];\n\n% Total force = Weight + Aerodynamic forces + Thrust force\nf_tot = weight + f_drag + f_thrust;\n\n% Compute torques on drone\ntorque_aerodyn = p_dyn * p_drone.S_wing * ...\n [p_drone.b*(p_drone.Cl0 + p_drone.Cl_beta*beta + p_drone.Cl_p*kb*p + p_drone.Cl_r*kb*r + p_drone.Cl_da*da + p_drone.Cl_dr*dr);...\n p_drone.c*(p_drone.Cm0 + p_drone.Cm_alpha*alpha + p_drone.Cm_q*kc*q + p_drone.Cm_de*de);...\n p_drone.b*(p_drone.Cn0 + p_drone.Cn_beta*beta + p_drone.Cn_p*kb*p + p_drone.Cn_r*kb*r + p_drone.Cn_da*da + p_drone.Cn_dr*dr)];\n\n% Thrust torque\n% Relabel thrust coefficients\ntorque_thrust = [-p_drone.k_TP*(p_drone.k_omega*dt)^2; 0; 0];\n\n% Total torque\ntorque_tot = torque_aerodyn + torque_thrust;\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Create output\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nout = [f_tot; torque_tot; Va; alpha; beta; wn; we; wd];\n\nend", "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/physics/forces_moments_wing.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5421049006695137}} {"text": "function pde = elli3DcircIntf3HM(am,ap,bm,bp,kappa,r1,r2,n1,n2)\n%% USAGE: polynomial solution for Poisson equation\n% Last Modified: 02/21/2020 by Xu Zhang\n\n%% PDE Structure\npde = struct('intf',@intf,...\n 'exactu1',@exactu1,'exactu2',@exactu2,'exactu3',@exactu3,...\n 'um1',@um1,'um2',@um2,'um3',@um3,'up1',@up1,'up2',@up2,'up3',@up3,...\n 'Dxu',@Dxu,'Dxum',@Dxum,'Dxup',@Dxup,'Dyu',@Dyu,...\n 'Dyum',@Dyum,'Dyup',@Dyup,'Dzu',@Dzu,'Dzum',@Dzum,'Dzup',@Dzup,...\n 'f1',@f1,'f2',@f2,'f3',@f3,...\n 'fm1',@fm1,'fm2',@fm2,'fm3',@fm3,...\n 'fp1',@fp1,'fp2',@fp2,'fp3',@fp3,...\n 'A',@A,'Am',@Am,'Ap',@Ap,'one',@one,...\n 'B',@B,'Bm',@Bm,'Bp',@Bp);\n\npde.am = am;\npde.ap = ap;\npde.bm = bm;\npde.bp = bp;\npde.kappa = kappa;\n%% interface function\n function u = intf(x,y,z)\n u = (x.^2 + y.^2 + z.^2).^(1/2)/r1-1;\n end\n\n%% exact solution\n function u = exactu1(x,y,z)\n u = um1(x,y,z);\n id = intf(x,y,z) > 0;\n u(id) = up1(x(id),y(id),z(id));\n end\n function u = exactu2(x,y,z)\n u = um2(x,y,z);\n id = intf(x,y,z) > 0;\n u(id) = up2(x(id),y(id),z(id));\n end\n function u = exactu3(x,y,z)\n u = um3(x,y,z);\n id = intf(x,y,z) > 0;\n u(id) = up3(x(id),y(id),z(id));\n end\n function u = um1(x,y,z)\n u = (x + n1*uker1(x,y,z).*(y-z))/am;\n end\n function u = um2(x,y,z)\n u = (y + n1*uker1(x,y,z).*(z-x))/am;\n end\n function u = um3(x,y,z)\n u = (z + n1*uker1(x,y,z).*(x-y))/am;\n end\n function u = up1(x,y,z)\n u = (x + n2*uker1(x,y,z).*uker2(x,y,z).*(y-z))/ap;\n end\n function u = up2(x,y,z)\n u = (y + n2*uker1(x,y,z).*uker2(x,y,z).*(z-x))/ap;\n end\n function u = up3(x,y,z)\n u = (z + n2*uker1(x,y,z).*uker2(x,y,z).*(x-y))/ap;\n end\n function u = uker1(x,y,z)\n u = r1^2 - (x.^2 + y.^2 + z.^2);\n end\n function u = uker2(x,y,z)\n u = r2^2 - (x.^2 + y.^2 + z.^2);\n end\n%% Boundary Function\n function u = gD1(x,y,z)\n u = exactu1(x,y,z);\n end\n function u = gD2(x,y,z)\n u = exactu2(x,y,z);\n end\n function u = gD3(x,y,z)\n u = exactu3(x,y,z);\n end\n%% Derivative of the exact solution\n function u = Dxu(x,y,z)\n u = Dxum(x,y,z);\n id = intf(x,y,z) > 0;\n u(id) = Dxup(x(id),y(id),z(id));\n end\n function u = Dyu(x,y,z)\n u = Dyum(x,y,z);\n id = intf(x,y,z) > 0;\n u(id) = Dyup(x(id),y(id),z(id));\n end\n function u = Dzu(x,y,z)\n u = Dzum(x,y,z);\n id = intf(x,y,z) > 0;\n u(id) = Dzup(x(id),y(id),z(id));\n end\n function u = Dxum(x,y,z)\n u = -2*n1/am*(x.*y+x.*z-y.^2-z.^2 + uker1(x,y,z));\n end\n function u = Dyum(x,y,z)\n u = -2*n1/am*(y.*z+x.*y-z.^2-x.^2 + uker1(x,y,z));\n end\n function u = Dzum(x,y,z)\n u = -2*n1/am*(x.*z+y.*z-x.^2-y.^2 + uker1(x,y,z));\n end\n function u = Dxup(x,y,z)\n u = -2*n2*uker2(x,y,z)./ap.*(x.*y+x.*z-y.^2-z.^2 + uker1(x,y,z)) - ...\n 2*n2*uker1(x,y,z).*(x.*y+x.*z - y.^2-z.^2)/ap;\n end\n function u = Dyup(x,y,z)\n u = -2*n2*uker2(x,y,z)./ap.*(y.*z+x.*y-z.^2-x.^2 + uker1(x,y,z)) - ...\n 2*n2*uker1(x,y,z).*(y.*z+x.*y - x.^2-z.^2)/ap;\n end\n function u = Dzup(x,y,z)\n u = -2*n2*uker2(x,y,z)./ap.*(x.*z+y.*z-x.^2-y.^2 + uker1(x,y,z)) - ...\n 2*n2*uker1(x,y,z).*(x.*z+y.*z - x.^2-y.^2)/ap;\n end\n\n%% right hand side function\n function u = f1(x,y,z)\n u = fm1(x,y,z);\n id = intf(x,y,z) > 0;\n u(id) = fp1(x(id),y(id),z(id));\n end\n function u = f2(x,y,z)\n u = fm2(x,y,z);\n id = intf(x,y,z) > 0;\n u(id) = fp2(x(id),y(id),z(id));\n end\n function u = f3(x,y,z)\n u = fm3(x,y,z);\n id = intf(x,y,z) > 0;\n u(id) = fp3(x(id),y(id),z(id));\n end\n\n function u = fm1(x,y,z)\n u = -10*n1*(z-y)- kappa*bm*um1(x,y,z);\n end\n function u = fm2(x,y,z)\n u = -10*n1*(x-z) - kappa*bm*um2(x,y,z);\n end\n function u = fm3(x,y,z)\n u = -10*n1*(y-x) - kappa*bm*um3(x,y,z);\n end\n function u = fp1(x,y,z)\n u = -10*n2*uker2(x,y,z).*(z-y) +8*n2*(z.^3-y.^3+z.*y.^2+z.*x.^2-y.*x.^2-y.*z.^2) -...\n 10*n2*uker1(x,y,z).*(z-y) - kappa*bp*up1(x,y,z);\n end\n function u = fp2(x,y,z)\n u = -10*n2*uker2(x,y,z).*(x-z) +8*n2*(x.^3-z.^3+x.*z.^2+x.*y.^2-z.*y.^2-z.*x.^2) -...\n 10*n2*uker1(x,y,z).*(x-z) - kappa*bp*up2(x,y,z);\n end\n function u = fp3(x,y,z)\n u = -10*n2*uker2(x,y,z).*(y-x) +8*n2*(y.^3-x.^3+y.*x.^2+y.*z.^2-x.*z.^2-x.*y.^2) -...\n 10*n2*uker1(x,y,z).*(y-x) - kappa*bp*up3(x,y,z);\n end\n\n%% Diffusion coefficient function\n function u = A(x,y,z)\n u = Am(x,y,z);\n id = intf(x,y,z) > 0;\n u(id) = Ap(x(id),y(id),z(id));\n end\n function u = Am(x,y,z)\n u = am*ones(size(x));\n end\n function u = Ap(x,y,z)\n u = ap*ones(size(x));\n end\n\n%% Mass coefficient function\n function u = B(x,y,z)\n u = Bm(x,y,z);\n id = intf(x,y,z) > 0;\n u(id) = Bp(x(id),y(id),z(id));\n end\n function u = Bm(x,y,z)\n u = bm*ones(size(x));\n end\n function u = Bp(x,y,z)\n u = bp*ones(size(x));\n end\n\n%% Other function\n function u = one(x,y,z)\n u = ones(size(x));\n end\nend", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/research/IVEM/ExampleFun/elli3DcircIntf3HM.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424528443251, "lm_q2_score": 0.640635861701035, "lm_q1q2_score": 0.5419410722274114}} {"text": "function LR_chi2=drxlr_get_lrt(y,mu)\n% compute the likelihood ratio test \n% written by Issam El Naqa\n%\n% Copyright 2010, Joseph O. Deasy, on behalf of the DREES development team.\n% \n% This file is part of the Dose Response Explorer System (DREES).\n% \n% DREES development has been led by: Issam El Naqa, Aditya Apte, Gita Suneja, and Joseph O. Deasy.\n% \n% DREES has been financially supported by the US National Institutes of Health under multiple grants.\n% \n% DREES is distributed under the terms of the Lesser GNU Public License. \n% \n% This version of DREES 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% DREES is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;\n% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n% See the GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with DREES. If not, see .\n\nseps = sqrt(eps);\nn=length(y);\nn1=sum(y); n0=sum(1-y);\nLs=n1*log(n1)+n0*log(n0)-n*log(n); % saturated\nL=sum(y.*log(mu+seps)+(1-y).*log(1-mu+seps)); % fitted\nLR_chi2=2*(L-Ls); % follows centered chi2 stats\nreturn", "meta": {"author": "mvallieres", "repo": "radiomics", "sha": "d3a61737730e1b2b46d04c9e22a3fcc390912f1a", "save_path": "github-repos/MATLAB/mvallieres-radiomics", "path": "github-repos/MATLAB/mvallieres-radiomics/radiomics-d3a61737730e1b2b46d04c9e22a3fcc390912f1a/MultivariableModeling/LogisticRegression/drxlr_get_lrt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085146, "lm_q2_score": 0.640635861701035, "lm_q1q2_score": 0.541941062274614}} {"text": "function [ ap, ipvt, info ] = chpfa ( ap, n )\n\n%*****************************************************************************80\n%\n%% CHPFA factors a complex hermitian packed matrix.\n%\n% Discussion:\n%\n% To solve A*X = B, follow CHPFA by CHPSL.\n%\n% To compute inverse(A)*C, follow CHPFA by CHPSL.\n%\n% To compute determinant(A), follow CHPFA by CHPDI.\n%\n% To compute inertia(A), follow CHPFA by CHPDI.\n%\n% To compute inverse(A), follow CHPFA by CHPDI.\n%\n% Packed storage:\n%\n% The following program segment will pack the upper\n% triangle of a hermitian matrix.\n%\n% k = 0\n% do j = 1, n\n% do i = 1, j\n% k = k + 1\n% ap(k) = a(i,j)\n% end\n% end\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 13 May 2007\n%\n% Author:\n%\n% MATLAB version by John Burkardt\n%\n% Reference:\n%\n% Jack Dongarra, Jim Bunch, Cleve Moler, Pete Stewart,\n% LINPACK User's Guide,\n% SIAM, 1979,\n% ISBN13: 978-0-898711-72-1,\n% LC: QA214.L56.\n%\n% Parameters:\n%\n% Input, complex AP(N*(N+1)/2); the packed form\n% of a hermitian matrix. The columns of the upper triangle are\n% stored sequentially in a one-dimensional array. \n%\n% Input, integer N, the order of the matrix.\n%\n% Output, complex AP(N*(N+1)/2); a block diagonal matrix and the \n% multipliers which were used to obtain it stored in packed form. \n% The factorization can be written A = U*D*hermitian(U) where U is a \n% product of permutation and unit upper triangular matrices, hermitian(U) \n% is the conjugate transpose of U, and D is block diagonal with 1 by 1\n% and 2 by 2 blocks.\n%\n% Output, integer IPVT(N), the pivot indices.\n%\n% Output, integer INFO.\n% 0, normal value.\n% K, if the K-th pivot block is singular. This is not an error condition\n% for this subroutine, but it does indicate that CHPSL or CHPDI may divide\n% by zero if called.\n%\n\n%\n% Initialize.\n%\n% ALPHA is used in choosing pivot block size.\n%\n alpha = ( 1.0 + sqrt ( 17.0 ) ) / 8.0;\n\n info = 0;\n%\n% Main loop on K, which goes from N to 1.\n%\n k = n;\n ik = ( n * ( n - 1 ) ) / 2;\n\n while ( 1 )\n%\n% Leave the loop if K = 0 or K = 1.\n%\n if ( k == 0 )\n break\n end\n\n if ( k == 1 )\n ipvt(1) = 1;\n if ( cabs1 ( ap(1) ) == 0.0 )\n info = 1;\n end\n break\n end\n%\n% This section of code determines the kind of\n% elimination to be performed. When it is completed,\n% KSTEP will be set to the size of the pivot block, and\n% SWAP will be set to TRUE if an interchange is\n% required.\n%\n km1 = k - 1;\n kk = ik + k;\n absakk = cabs1 ( ap(kk) );\n%\n% Determine the largest off-diagonal element in column K.\n%\n imax = icamax ( k-1, ap(ik+1:ik+k-1), 1 );\n imk = ik + imax;\n colmax = cabs1 ( ap(imk) );\n\n if ( alpha * colmax <= absakk )\n\n kstep = 1;\n swap = 0;\n%\n% Determine the largest off-diagonal element in row IMAX.\n%\n else\n\n rowmax = 0.0;\n im = ( imax * ( imax - 1 ) ) / 2;\n imj = im + 2 * imax;\n\n for j = imax + 1 : k\n rowmax = max ( rowmax, cabs1 ( ap(imj) ) );\n imj = imj + j;\n end\n\n if ( imax ~= 1 )\n jmax = icamax ( imax-1, ap(im+1:im+imax-1), 1 );\n jmim = jmax + im;\n rowmax = max ( rowmax, cabs1 ( ap(jmim) ) );\n end\n\n imim = imax + im;\n\n if ( alpha * rowmax <= cabs1 ( ap(imim) ) )\n kstep = 1;\n swap = 1;\n elseif ( alpha * colmax * ( colmax / rowmax ) <= absakk )\n kstep = 1;\n swap = 0;\n else\n kstep = 2;\n swap = ( imax ~= km1 );\n end\n\n end\n%\n% Column K is zero. Set INFO and iterate the loop.\n%\n if ( max ( absakk, colmax ) == 0.0 )\n ipvt(k) = k;\n info = k;\n ik = ik - ( k - 1 );\n if ( kstep == 2 )\n ik = ik - ( k - 2 );\n end\n k = k - kstep;\n continue\n end\n\n if ( kstep ~= 2 )\n%\n% 1 x 1 pivot block.\n%\n if ( swap )\n\n temp = ap(im+1:im+imax);\n ap(im+1:im+imax) = ap(ik+1:ik+imax);\n ap(ik+1:ik+imax) = temp;\n\n imj = ik + imax;\n\n for jj = imax : k\n j = k + imax - jj;\n jk = ik + j;\n t = conj ( ap(jk) );\n ap(jk) = conj ( ap(imj) );\n ap(imj) = t;\n imj = imj - ( j - 1 );\n end\n\n end\n%\n% Perform the elimination.\n%\n ij = ik - ( k - 1 );\n for jj = 1 : km1\n j = k - jj;\n jk = ik + j;\n mulk = -ap(jk) / ap(kk);\n t = conj ( mulk );\n ap(ij+1:ij+j) = ap(ij+1:ij+j) + t * ap(ik+1:ik+j);\n ijj = ij + j;\n ap(ijj) = real ( ap(ijj) );\n ap(jk) = mulk;\n ij = ij - ( j - 1 );\n end\n%\n% Set the pivot array.\n%\n if ( swap )\n ipvt(k) = imax;\n else\n ipvt(k) = k;\n end\n%\n% 2 x 2 pivot block.\n%\n else\n\n km1k = ik + k - 1;\n ikm1 = ik - ( k - 1 );\n\n if ( swap )\n\n temp = ap(im+1:im+imax);\n ap(im+1:im+imax) = ap(ikm1+1:ikm1+imax);\n ap(ikm1+1:ikm1+imax) = temp;\n\n imj = ikm1 + imax;\n\n for jj = imax : km1\n j = km1 + imax - jj;\n jkm1 = ikm1 + j;\n t = conj ( ap(jkm1) );\n ap(jkm1) = conj ( ap(imj) );\n ap(imj) = t;\n imj = imj - ( j - 1 );\n end\n\n t = ap(km1k);\n ap(km1k) = ap(imk);\n ap(imk) = t;\n\n end\n%\n% Perform the elimination.\n%\n km2 = k - 2;\n\n if ( km2 ~= 0 )\n\n ak = ap(kk) / ap(km1k);\n km1km1 = ikm1 + k - 1;\n akm1 = ap(km1km1) / conj ( ap(km1k) );\n denom = 1.0 - ak * akm1;\n ij = ik - ( k - 1 ) - ( k - 2 );\n\n for jj = 1 : km2\n j = km1 - jj;\n jk = ik + j;\n bk = ap(jk) / ap(km1k);\n jkm1 = ikm1 + j;\n bkm1 = ap(jkm1) / conj ( ap(km1k) );\n mulk = ( akm1 * bk - bkm1 ) / denom;\n mulkm1 = ( ak * bkm1 - bk ) / denom;\n t = conj ( mulk );\n ap(ij+1:ij+j) = ap(ij+1:ij+j) + t * ap(ik+1:ik+j);\n t = conj ( mulkm1 );\n ap(ij+1:ij+j) = ap(ij+1:ij+j) + t * ap(ikm1+1:ikm1+j);\n ap(jk) = mulk;\n ap(jkm1) = mulkm1;\n ijj = ij + j;\n ap(ijj) = real ( ap(ijj) );\n ij = ij - ( j - 1 );\n end\n\n end\n%\n% Set the pivot array.\n%\n if ( swap )\n ipvt(k) = -imax;\n else\n ipvt(k) = 1 - k;\n end\n\n ipvt(k-1) = ipvt(k);\n\n end\n\n ik = ik - ( k - 1 );\n if ( kstep == 2 )\n ik = ik - ( k - 2 );\n end\n\n k = k - kstep;\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/linpack_c/chpfa.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085145, "lm_q2_score": 0.640635861701035, "lm_q1q2_score": 0.541941062274614}} {"text": "function S=test(x)\n% Edgar & Himmelblau, 1988\n% x0 = [1, 2]'\n% xo = [0, 0]'\n% S(xo) = 0\n\nS=4*x(1).^2-2.*x(1).*x(2)+x(2).^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/15072-unconstrained-optimization-using-powell/test10.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8459424450764199, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5419410614468858}} {"text": "function pde = elli3DcircIntf2(am,ap,bm,bp,r,x0,y0,z0,a11,a12,a)\n%% USAGE: polynomial solution for Poisson equation\n% Last Modified: 02/21/2020 by Xu Zhang\n\n%% PDE Structure\npde = struct('intf',@intf,...\n 'exactu1',@exactu1,'exactu2',@exactu2,'exactu3',@exactu3,...\n 'um1',@um1,'um2',@um2,'um3',@um3,'up1',@up1,'up2',@up2,'up3',@up3,...\n 'Dxu',@Dxu,'Dxum',@Dxum,'Dxup',@Dxup,'Dyu',@Dyu,...\n 'Dyum',@Dyum,'Dyup',@Dyup,'Dzu',@Dzu,'Dzum',@Dzum,'Dzup',@Dzup,...\n 'f1',@f1,'f2',@f2,'f3',@f3,...\n 'fm1',@fm1,'fm2',@fm2,'fm3',@fm3,...\n 'fp1',@fp1,'fp2',@fp2,'fp3',@fp3,...\n 'A',@A,'Am',@Am,'Ap',@Ap,'one',@one,...\n 'B',@B,'Bm',@Bm,'Bp',@Bp);\n\npde.am = am;\npde.ap = ap;\npde.bm = bm;\npde.bp = bp;\n%% interface function\n function u = intf(x,y,z)\n u = ((x-x0).^2 + (y-y0).^2 + (z-z0).^2).^(1/2)/r-1;\n end\n\n%% exact solution\n function u = exactu1(x,y,z)\n u = um1(x,y,z);\n id = intf(x,y,z) > 0;\n u(id) = up1(x(id),y(id),z(id));\n end\n function u = exactu2(x,y,z)\n u = um2(x,y,z);\n id = intf(x,y,z) > 0;\n u(id) = up2(x(id),y(id),z(id));\n end\n function u = exactu3(x,y,z)\n u = um3(x,y,z);\n id = intf(x,y,z) > 0;\n u(id) = up3(x(id),y(id),z(id));\n end\n function u = um1(x,y,z)\n u1 = uker1(x,y,z).*(x-x0);\n u2 = uker2(x,y,z);\n u = (u1 + u2)/bm;\n end\n function u = um2(x,y,z)\n u1 = uker1(x,y,z).*(y-y0);\n u2 = uker2(x,y,z);\n u = (u1 + u2)/bm;\n end\n function u = um3(x,y,z)\n u1 = uker1(x,y,z).*(z-z0);\n u2 = uker2(x,y,z);\n u = (u1 + u2)/bm;\n end\n function u = up1(x,y,z)\n u1 = uker1(x,y,z).*(x-x0);\n u2 = uker2(x,y,z);\n u = (u1 + u2)/bp;\n end\n function u = up2(x,y,z)\n u1 = uker1(x,y,z).*(y-y0);\n u2 = uker2(x,y,z);\n u = (u1 + u2)/bp;\n end\n function u = up3(x,y,z)\n u1 = uker1(x,y,z).*(z-z0);\n u2 = uker2(x,y,z);\n u = (u1 + u2)/bp;\n end\n function u = uker1(x,y,z)\n u = nthroot((x-x0).^2 + (y-y0).^2 + (z-z0).^2 - r^2,a11);\n u = u.^a12;\n end\n function u = uker2(x,y,z)\n u = ((x-x0).^2 + (y-y0).^2 + (z-z0).^2 - r^2).^a;\n end\n%% Boundary Function\n function u = gD1(x,y,z)\n u = exactu1(x,y,z);\n end\n function u = gD2(x,y,z)\n u = exactu2(x,y,z);\n end\n function u = gD3(x,y,z)\n u = exactu3(x,y,z);\n end\n%% Derivative of the exact solution\n function u = Dxu(x,y,z)\n u = Dxum(x,y,z);\n id = intf(x,y,z) > 0;\n u(id) = Dxup(x(id),y(id),z(id));\n end\n function u = Dyu(x,y,z)\n u = Dyum(x,y,z);\n id = intf(x,y,z) > 0;\n u(id) = Dyup(x(id),y(id),z(id));\n end\n function u = Dzu(x,y,z)\n u = Dzum(x,y,z);\n id = intf(x,y,z) > 0;\n u(id) = Dzup(x(id),y(id),z(id));\n end\n function u = Dxum(x,y,z)\n u = (Duker(x,y,z).*(y-y0)*2 - Duker(x,y,z).*(z-z0)*2)/bm;\n end\n function u = Dyum(x,y,z)\n u = (Duker(x,y,z).*(z-z0)*2 - Duker(x,y,z).*(x-x0)*2)/bm;\n end\n function u = Dzum(x,y,z)\n u = (Duker(x,y,z).*(x-x0)*2 - Duker(x,y,z).*(y-y0)*2)/bm;\n end\n function u = Dxup(x,y,z)\n u = (Duker(x,y,z).*(y-y0)*2 - Duker(x,y,z).*(z-z0)*2)/bp;\n end\n function u = Dyup(x,y,z)\n u = (Duker(x,y,z).*(z-z0)*2 - Duker(x,y,z).*(x-x0)*2)/bp;\n end\n function u = Dzup(x,y,z)\n u = (Duker(x,y,z).*(x-x0)*2 - Duker(x,y,z).*(y-y0)*2)/bp;\n end\n\n function u = Duker(x,y,z)\n u = a*((x-x0).^2 + (y-y0).^2 + (z-z0).^2 - r^2).^(a-1);\n end\n\n%% right hand side function\n function u = f1(x,y,z)\n u = fm1(x,y,z);\n id = intf(x,y,z) > 0;\n u(id) = fp1(x(id),y(id),z(id));\n end\n function u = f2(x,y,z)\n u = fm2(x,y,z);\n id = intf(x,y,z) > 0;\n u(id) = fp2(x(id),y(id),z(id));\n end\n function u = f3(x,y,z)\n u = fm3(x,y,z);\n id = intf(x,y,z) > 0;\n u(id) = fp3(x(id),y(id),z(id));\n end\n\n function u = fm1(x,y,z)\n xh = x-x0; yh = y-y0; zh = z-z0;\n u = (-4*Duker(x,y,z) + DDuker(x,y,z).*(xh.*(yh+zh)-yh.^2-zh.^2)) + bm*um1(x,y,z);\n end\n function u = fm2(x,y,z)\n xh = x-x0; yh = y-y0; zh = z-z0;\n u = (-4*Duker(x,y,z) + DDuker(x,y,z).*(yh.*(xh+zh)-xh.^2-zh.^2)) + bm*um2(x,y,z);\n end\n function u = fm3(x,y,z)\n xh = x-x0; yh = y-y0; zh = z-z0;\n u = (-4*Duker(x,y,z) + DDuker(x,y,z).*(zh.*(xh+yh)-xh.^2-yh.^2)) + bm*um3(x,y,z);\n end\n function u = fp1(x,y,z)\n xh = x-x0; yh = y-y0; zh = z-z0;\n u = (-4*Duker(x,y,z) + DDuker(x,y,z).*(xh.*(yh+zh)-yh.^2-zh.^2)) + bp*up1(x,y,z);\n end\n function u = fp2(x,y,z)\n xh = x-x0; yh = y-y0; zh = z-z0;\n u = (-4*Duker(x,y,z) + DDuker(x,y,z).*(yh.*(xh+zh)-xh.^2-zh.^2)) + bp*up2(x,y,z);\n end\n function u = fp3(x,y,z)\n xh = x-x0; yh = y-y0; zh = z-z0;\n u = (-4*Duker(x,y,z) + DDuker(x,y,z).*(zh.*(xh+yh)-xh.^2-yh.^2)) + bp*up3(x,y,z);\n end\n\n function u = DDuker(x,y,z)\n u = a*(a-1)*((x-x0).^2 + (y-y0).^2 + (z-z0).^2 - r^2).^(a-2);\n end\n\n%% Diffusion coefficient function\n function u = A(x,y,z)\n u = Am(x,y,z);\n id = intf(x,y,z) > 0;\n u(id) = Ap(x(id),y(id),z(id));\n end\n function u = Am(x,y,z)\n u = am*ones(size(x));\n end\n function u = Ap(x,y,z)\n u = ap*ones(size(x));\n end\n\n%% Mass coefficient function\n function u = B(x,y,z)\n u = Bm(x,y,z);\n id = intf(x,y,z) > 0;\n u(id) = Bp(x(id),y(id),z(id));\n end\n function u = Bm(x,y,z)\n u = bm*ones(size(x));\n end\n function u = Bp(x,y,z)\n u = bp*ones(size(x));\n end\n\n%% Other function\n function u = one(x,y,z)\n u = ones(size(x));\n end\nend", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/research/IVEM/ExampleFun/elli3DcircIntf2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406087, "lm_q2_score": 0.640635847978761, "lm_q1q2_score": 0.5419410456899612}} {"text": "function [K] = ku1v1(x, y, xp, yp, hyp, i)\n\nlogsigma = hyp(1);\nlogthetax = hyp(2);\nlogthetay = hyp(3);\n\nn_x = size(x,1);\nn_y = size(y,1);\nn_xp = size(xp,1);\nn_yp = size(yp,1);\n\nx = repmat(x,1,n_xp);\ny = repmat(y,1,n_yp);\nxp = repmat(xp',n_x,1);\nyp = repmat(yp',n_y,1);\n\nswitch i\n\n\ncase 0\n\nK=exp(1).^(logsigma+(-1).*logthetax+(-1).*logthetay+(-1/2).*exp(1).^((-1) ...\n .*logthetax).*(x+(-1).*xp).^2+(-1/2).*exp(1).^((-1).*logthetay).*(y+(-1) ...\n .*yp).^2).*(x+(-1).*xp).*(y+(-1).*yp);\n\n\ncase 1 % logsigma\n\nK=exp(1).^(logsigma+(-1).*logthetax+(-1).*logthetay+(-1/2).*exp(1).^((-1) ...\n .*logthetax).*(x+(-1).*xp).^2+(-1/2).*exp(1).^((-1).*logthetay).*(y+(-1) ...\n .*yp).^2).*(x+(-1).*xp).*(y+(-1).*yp);\n\n\ncase 2 % logthetax\n\nK=exp(1).^(logsigma+(-1).*logthetax+(-1).*logthetay+(-1/2).*exp(1).^((-1) ...\n .*logthetax).*(x+(-1).*xp).^2+(-1/2).*exp(1).^((-1).*logthetay).*(y+(-1) ...\n .*yp).^2).*((-1)+(1/2).*exp(1).^((-1).*logthetax).*(x+(-1).*xp).^2).*(x+ ...\n (-1).*xp).*(y+(-1).*yp);\n\n\ncase 3 % logthetay\n\nK=exp(1).^(logsigma+(-1).*logthetax+(-1).*logthetay+(-1/2).*exp(1).^((-1) ...\n .*logthetax).*(x+(-1).*xp).^2+(-1/2).*exp(1).^((-1).*logthetay).*(y+(-1) ...\n .*yp).^2).*(x+(-1).*xp).*((-1)+(1/2).*exp(1).^((-1).*logthetay).*(y+(-1) ...\n .*yp).^2).*(y+(-1).*yp);\n\n\notherwise\n \n K = zeros(n_x, n_xp);\nend\n\nend\n", "meta": {"author": "maziarraissi", "repo": "HPM", "sha": "21a7429cceb55d5ab688256db75ac360e2d8a925", "save_path": "github-repos/MATLAB/maziarraissi-HPM", "path": "github-repos/MATLAB/maziarraissi-HPM/HPM-21a7429cceb55d5ab688256db75ac360e2d8a925/Kernels/Navier_Stokes/+k11/ku1v1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110454379297, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.5419207267627973}} {"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 : nrtFfmHelmholtzBWneu.m |\n%| # | VERSION : 0.61 |\n%| _#_ | AUTHOR(S) : Matthieu Aussal |\n%| ( # ) | CREATION : 14.03.2017 |\n%| / 0 \\ | LAST MODIF : 05.09.2019 |\n%| ( === ) | SYNOPSIS : Solve neumann scatering problem with |\n%| `---' | Brackage-Werner formulation |\n%+========================================================================+\n\n% Cleaning\nclear all\nclose all\nclc\n\n% Gypsilab path\nrun('../../addpathGypsilab.m')\n\n% Parameters\nN = 1e3\ntol = 1e-3\ntyp = 'P1'\ngss = 3\nX0 = [0 0 -1]\n\n% Spherical mesh\nsphere = mshSphere(N,1);\nsigma = dom(sphere,gss); \nfigure\nplot(sphere)\naxis equal\n\n% Radiative mesh\nsquare = mshSquare(5*N,[5 5]);\nsquare.vtx = [square.vtx(:,1) zeros(size(square.vtx,1),1) square.vtx(:,2)];\nhold on\nplot(square)\n\n% Frequency adjusted to maximum esge size\nstp = sphere.stp;\nk = 1/stp(2)\nf = (k*340)/(2*pi)\n\n% Incident wave\nPW = @(X) exp(1i*k*X*X0');\ngradxPW{1} = @(X) 1i*k*X0(1) .* PW(X);\ngradxPW{2} = @(X) 1i*k*X0(2) .* PW(X);\ngradxPW{3} = @(X) 1i*k*X0(3) .* PW(X);\n\n% Incident wave representation\nplot(sphere,real(PW(sphere.vtx)))\nplot(square,real(PW(square.vtx)))\ntitle('Incident wave')\nxlabel('X'); ylabel('Y'); zlabel('Z');\nhold off\nview(0,10)\n% camlight\n% material dull\n% lighting phong\n\n\n%%% PREPARE OPERATORS\ndisp('~~~~~~~~~~~~~ PREPARE OPERATORS ~~~~~~~~~~~~~')\n\n% Green kernel function --> G(x,y) = exp(ik|x-y|)/|x-y| \nGxy = '[exp(ikr)/r]';\ngradyGxy = {'grady[exp(ikr)/r]1','grady[exp(ikr)/r]2','grady[exp(ikr)/r]3'};\n\n% Finite elements\nu = fem(sphere,typ);\nv = fem(sphere,typ);\n\n% Coupling coeff\nbeta = 1i*k;\n\n% Finite element mass matrix --> \\int_Sx psi(x)' psi(x) dx\nId = integral(sigma,u,v);\n\n% Finite element boundary operator --> \n% k^2 * \\int_Sx \\int_Sy n.psi(x) G(x,y) n.psi(y) dx dy \n% - \\int_Sx \\int_Sy nxgrad(psi(x)) G(x,y) nxgrad(psi(y)) dx dy \ntic\nHr = 1/(4*pi) .* (k^2 * regularize(sigma,sigma,ntimes(u),'[1/r]',ntimes(v)) ...\n - regularize(sigma,sigma,nxgrad(u),'[1/r]',nxgrad(v)));\nH = 1/(4*pi) .* (k^2 * integral(sigma,sigma,ntimes(u),Gxy,k,ntimes(v),tol) ...\n - integral(sigma,sigma,nxgrad(u),Gxy,k,nxgrad(v),tol)) + Hr;\ntoc\n\n% Finite element boundary operator --> \\int_Sx \\int_Sy psi(x)' dny G(x,y) psi(y) dx dy \ntic\nDtr = 1/(4*pi) .* regularize(sigma,sigma,u,'grady[1/r]',ntimes(v)).';\nDt = 1/(4*pi) .* integral(sigma,sigma,u,gradyGxy,k,ntimes(v),tol).' + Dtr;\ntoc\n\n% Final operator [1i*k*beta*(-Id/2 + Dt) - H]\ntic\nLHS = beta.*(-0.5*Id + Dt) - H;\ntoc\n\n% Finite element incident wave trace --> \\int_Sx psi(x) dnx(pw(x)) dx\nRHS = - integral(sigma,ntimes(u),gradxPW);\n\n\n%%% SOLVE LINEAR PROBLEM\ndisp('~~~~~~~~~~~~~ SOLVE LINEAR PROBLEM ~~~~~~~~~~~~~')\n\n% Preconditionneur ILU\ntic\n[L,U] = ilu(beta.*(-0.5*Id + Dtr) - Hr);\ntoc\n\n% Solve linear system : [H + 1i*k*beta*(Id/2 - Dt)] = -dnP0\ntic\nmu = mgcr(@(V) LHS*V,RHS,[],tol,100,L,U);\ntoc\n\n% Jump for derivative\nlambda = beta * mu;\n\n\n%%% INFINITE SOLUTION\ndisp('~~~~~~~~~~~~~ INFINITE RADIATION ~~~~~~~~~~~~~')\n\n% Plane waves direction\ntheta = 2*pi/1e3 .* (1:1e3)';\nnu = [sin(theta),zeros(size(theta)),cos(theta)];\n\n% Green kernel function\nGinf = '[exp(-ikxy)]';\ngradxGinf = {'gradx[exp(-ikxy)]1','gradx[exp(-ikxy)]2','gradx[exp(-ikxy)]3'};\n\n% Finite element infinite operators\nSinf = 1/(4*pi) .* integral(nu,sigma,Ginf,k,v,tol);\nDinf = 1/(4*pi) .* integral(nu,sigma,gradxGinf,k,ntimes(v),tol);\n\n% Finite element radiation \nsol = Sinf*lambda - Dinf*mu;\n\n% Analytical solution\nref = sphereHelmholtz('inf','neu',1,k,nu); \nnorm(ref-sol,2)/norm(ref,2)\nnorm(ref-sol,'inf')/norm(ref,'inf')\n\n% Graphical representation\nfigure\nplot(theta,log(abs(sol)),'b',theta,log(abs(ref)),'--r')\n\n\n%%% DOMAIN SOLUTION\ndisp('~~~~~~~~~~~~~ RADIATION ~~~~~~~~~~~~~')\n\n% Finite element mass matrix --> \\int_Sx psi(x)' psi(x) dx\nId = integral(sigma,u,v);\n\n% Finite element boundary operator --> \\int_Sx \\int_Sy psi(x)' G(x,y) psi(y) dx dy \ntic\nSbnd = 1/(4*pi) .* (integral(sigma,sigma,u,Gxy,k,v,tol) + ...\n regularize(sigma,sigma,u,'[1/r]',v));\ntoc\n\n% Finite element boundary operator --> \\int_Sx \\int_Sy psi(x)' dny G(x,y) psi(y) dx dy \ntic\nDbnd = 1/(4*pi) .* (integral(sigma,sigma,u,gradyGxy,k,ntimes(v),tol) + ...\n regularize(sigma,sigma,u,'grady[1/r]',ntimes(v)));\ntoc\n\n% Boundary solution\nPsca = Id\\(Sbnd*lambda - (0.5*Id*mu + Dbnd*mu));\nPinc = PW(u.dof);\nPbnd = Pinc + Psca;\n\n% Finite element radiative operator --> \\int_Sy G(x,y) psi(y) dy \ntic\nSdom = 1/(4*pi) .* (integral(square.vtx,sigma,Gxy,k,v,tol) + ...\n regularize(square.vtx,sigma,'[1/r]',v));\ntoc\n\n% Finite element radiative operator --> \\int_Sx \\int_Sy psi(x)' grady(G(x,y)) ny.psi(y) dx dy \ntic\nDdom = 1/(4*pi) .* ( integral(square.vtx,sigma,gradyGxy,k,ntimes(v),tol) + ...\n regularize(square.vtx,sigma,'grady[1/r]',ntimes(v)) );\ntoc\n\n% Domain solution\nPsca = Sdom*lambda - Ddom*mu;\nPinc = PW(square.vtx);\nPdom = Pinc + Psca;\n\n% Annulation sphere interieure\nr = sqrt(sum(square.vtx.^2,2));\nPdom(r<=1.01) = Pinc(r<=1.01);\n\n% Graphical representation\nfigure\nplot(sphere,abs(Pbnd))\naxis equal;\nhold on\nplot(square,abs(Pdom))\ntitle('Total field solution')\ncolorbar\nhold off\nview(0,10)\n\n\n%%% ANAYTICAL SOLUTIONS FOR COMPARISONS\n% Analytical solution\nPbnd = sphereHelmholtz('dom','neu',1,k,1.001*sphere.vtx) + PW(sphere.vtx);\nPdom = sphereHelmholtz('dom','neu',1,k,square.vtx) + PW(square.vtx);\n\n% Solution representation\nfigure\nplot(sphere,abs(Pbnd))\naxis equal;\nhold on\nplot(square,abs(Pdom))\ntitle('Analytical solution')\ncolorbar\nhold off\nview(0,10)\n\n\n\ndisp('~~> Michto gypsilab !')\n", "meta": {"author": "SwanLab", "repo": "Swan", "sha": "f8355f3561bb1a1603f56b3676873147d22a511e", "save_path": "github-repos/MATLAB/SwanLab-Swan", "path": "github-repos/MATLAB/SwanLab-Swan/Swan-f8355f3561bb1a1603f56b3676873147d22a511e/gypsilabModified/nonRegressionTest/fastFreeMemory/nrtFfmHelmholtzBWneu.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757870046160258, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5419198625835316}} {"text": "function As = slsymgraph(A, symmethod)\n%SLSYMGRAPH Forces symmetry of the adjacency matrix of a graph\n%\n% $ Syntax $\n% - As = slsymgraph(A)\n% - As = slsymgraph(A, symmethod)\n%\n% $ Arguments $\n% - A: The adjacency matrix of the original graph\n% - symmethod: The method to symmetrize the graph\n% - As: The symmetry adjacency matrix\n% \n% $ Description $\n% - As = slsymgraph(A) makes a symmetry version of the adjacency matrix\n% A using default method.\n%\n% - As = slsymgraph(A, symmethod) symmetrizes the adjacency matrix by \n% using the specified method. \n% \\*\n% \\t Table. The method to symmetrizes adjacency matrix\n% \\h name & description \n% 'avgor' & Force symmetry using the following rule:\n% if both aij and aji are non-zeros, then \n% take their average\n% if only one of aij and aji is non-zero, then\n% take the non-zero one\n% if both aij and aji are zeros, then set zero\n% (for both logical and numeric)\n% 'avgand' & Force symmetry using the following rule:\n% if both aij and aji are non-zeros, then \n% take their average\n% if either one of aij and aji is zero, then\n% set zero\n% (for both logical and numeric)\n% 'or' & Use or-rule: d = aij | aji\n% (for only logical)\n% 'and' & Use and-rule: d = aij & aji\n% (for only logical)\n% 'simavg' & make simple average: always take (aij+aji)/2\n% (for only numeric)\n% \\*\n% The default method to use is 'avgor'. You can use your own function\n% handle. It should be like the following form:\n% v = f(v1, v2)\n% v1 and v2 are arrays of equal size with corresponding values. For\n% a reasonable function, it should satisfy that:\n% f(v, v) == v && f(v1, v2) = f(v2, v1)\n%\n% $ Remarks $\n% - A can be full matrix or sparse matrix, and As preserves the same \n% storage form.\n%\n% - A should be a square matrix.\n%\n% - When 'avgor' method is applied to logical, it is equivalent to 'or'\n% when 'avgand' method is applied to logical, it is equivalent to\n% 'and'.\n%\n% $ History $\n% - Created by Dahua Lin, on Sep 8, 2006\n%\n\n%% parse and verify input\n\nif ndims(A) ~= 2 || size(A,1) ~= size(A,2)\n error('sltoolbox:invalidarg', ...\n 'The A should be a square 2D matrix');\nend\nn = size(A, 1);\n\nif nargin < 2 || isempty(symmethod)\n symmethod = 'avgor';\nend\n\nif ischar(symmethod)\n switch symmethod\n case 'avgor'\n fcs = @compsym_avgor;\n case 'avgand'\n fcs = @compsym_avgand;\n case 'or'\n fcs = @compsym_or;\n if isnumeric(A)\n error('sltoolbox:rterror', ...\n 'The or method is not applicable to numerical matrix');\n end\n case 'and'\n fcs = @compsym_and;\n if isnumeric(A)\n error('sltoolbox:rterror', ...\n 'The and method is not applicable to numerical matrix');\n end\n otherwise\n error('sltoolbox:invalidarg', ...\n 'Invalid method for symmetrization: %s', method);\n end\nelseif isa(symmethod, 'function_handle')\n fcs = symmethod;\nelse\n error('sltoolbox:invalidarg', ...\n 'Invalid method for symmetrization.');\nend\n \n\n%% main skeleton\n\n% prepare all indices with aij or aji non-zero\n\n[I0, J0] = find(A);\n\n% single out diagonal ones\nis_diag = (I0 == J0);\nif any(is_diag)\n inds_diag = sub2ind([n, n], I0(is_diag), J0(is_diag));\nelse\n inds_diag = [];\nend\n\n% process the non-diagonal ones\nnot_diag = ~is_diag;\nclear is_diag;\n\nif any(not_diag)\n % filter indices \n I0 = I0(not_diag);\n J0 = J0(not_diag);\n clear not_diag;\n\n % merge to down triangular part\n I = I0;\n J = J0;\n idx_ut = find(I0 > J0);\n if ~isempty(idx_ut)\n I(idx_ut) = J0(idx_ut);\n J(idx_ut) = I0(idx_ut);\n end\n clear I0 J0 idx_ut;\n\n % unique and expand to up triangular part\n inds_dt = sub2ind([n, n], I, J);\n [inds_dt, si] = unique(inds_dt);\n I = I(si);\n J = J(si);\n inds_ut = sub2ind([n, n], J, I);\n clear I J si;\nelse\n inds_dt = [];\n inds_ut = [];\nend\n\n% get original values\n\nif ~isempty(inds_dt)\n v_dt = A(inds_dt);\n v_ut = A(inds_ut);\nelse\n v_dt = [];\n v_ut = [];\nend\n\n% compute the symmetrized value\n\nv = fcs(v_dt, v_ut);\nclear v_dt v_ut;\n\n% combine diagonal value and non-diagonal value\n\nif ~isempty(inds_diag)\n v_diag = A(inds_diag);\nelse\n v_diag = [];\nend\n\ns_inds = vertcat(inds_diag, inds_dt, inds_ut);\nclear inds_diag inds_dt inds_ut;\ns_vals = vertcat(v_diag, v, v);\nclear v_diag v;\n\n% create matrix\n\nAs = slmakeadjmat(n, n, s_inds, s_vals, islogical(A), issparse(A));\n \n\n%% symmetry value computation functions\n\nfunction vd = compsym_avgor(v1, v2)\n\nif isnumeric(v1) \n has_both = v1 & v2;\n only_v1 = v1 & ~v2;\n only_v2 = v2 & ~v1;\n \n vd = zeros(size(v1));\n vd(has_both) = (v1(has_both) + v2(has_both)) / 2;\n vd(only_v1) = v1(only_v1);\n vd(only_v2) = v2(only_v2); \nelse\n vd = v1 | v2; \nend\n\n\nfunction vd = compsym_avgand(v1, v2)\n\nif isnumeric(v1)\n has_both = v1 & v2;\n \n vd = zeros(size(v1));\n vd(has_both) = (v1(has_both) + v2(has_both)) / 2;\nelse\n vd = v1 & v2;\nend\n\n\nfunction vd = compsym_or(v1, v2)\n\nvd = v1 | v2;\n\n\nfunction vd = compsym_and(v1, v2)\n\nvd = v1 & v2;\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/graph/slsymgraph.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289836, "lm_q2_score": 0.7122321842389469, "lm_q1q2_score": 0.5417598835280522}} {"text": "function By = mfBy(yc,para,flag);\n\nif ~exist('flag','var'), flag = 'By'; end;\n\nOmega = para.Omega;\ndim = length(Omega);\nm = para.m;\nh = Omega./m;\na = sqrt(para.mu);\nb = sqrt(para.mu+para.lambda);\n\n% Bu for elastic-grad\n% yc -> [u1,u2,u3]\n%\n% dim == 3, dim == 2,\n% | d11 | \n% | d21 | \n% | d31 | | u1 | | d11 |\n% | d12 | | | | d21 | | u1 |\n% y= | d22 | * | u2 | y = | d12 | * | |\n% | d32 | | | | d22 | | u2 |\n% | d13 | | u3 | | d11 d22 |\n% | d23 |\n% | d33 |\n% | d11 d22 d33 |\n\nflag = ['elastic-stg-',flag,'-',int2str(dim)];\n\nswitch flag\n case 'elastic-stg-By-2'\n nc = m(1)*m(2);\n nn = (m(1)+1)*(m(2)+1);\n ns1 = (m(1)+1)*m(2);\n ns2 = m(1)*(m(2)+1);\n \n I11 = 1:nc; % d11 y1\n I21 = I11(end)+(1:nn-2*(m(1)+1)); % d21 y1\n I12 = I21(end)+(1:nn-2*(m(2)+1)); % d12 y2\n I22 = I12(end)+(1:nc); % d22 y2\n I00 = I22(end)+(1:nc); % div Y\n \n By = zeros(I00(end),1);\n \n y1 = reshape(yc(1:ns1),m(1)+1,m(2));\n y2 = reshape(yc(ns1+(1:ns2)),m(1),m(2)+1);\n\n %% d11 y1\n By(I11) = reshape(y1(2:end,:)-y1(1:end-1,:),length(I11),1)/h(1);\n\n %% d21 y1\n By(I21) = reshape(y1(:,2:end)-y1(:,1:end-1),length(I21),1)/h(2);\n\n %% d12 y2\n By(I12) = reshape(y2(2:end,:)-y2(1:end-1,:),length(I12),1)/h(1);\n \n %% d22 y2\n By(I22) = reshape(y2(:,2:end)-y2(:,1:end-1),length(I22),1)/h(2);\n \n %% d22 y2\n By(I00) = b*By(I11) + b*By(I22);\n By(1:I22(end)) = a*By(1:I22(end));\n \n\n case 'elastic-stg-By-3'\n\n n0 = m(1)*m(2)*m(3);\n n1 = (m(1)+1)*m(2)*m(3);\n n2 = m(1)*(m(2)+1)*m(3);\n n3 = m(1)*m(2)*(m(3)+1);\n \n j1 = m(1)*(m(2)+1)*(m(3)+1);\n j2 = (m(1)+1)*m(2)*(m(3)+1);\n j3 = (m(1)+1)*(m(2)+1)*m(3);\n \n p1 = n0 + j2 + j3;\n p2 = p1 + n0 + j1 + j3;\n p3 = p2 + n0 + j1 + j2;\n \n ly = 4*n0+2*(j1+j2+j3);\n\n% mfilename, keyboard\n [y1,y2,y3] = vec2array(yc,m,'stg');\n\n clear yc\n \n By = zeros(ly,1);\n\n % d11 y1 : n1 -> n0\n dummy = y1(2:end,:,:) - y1(1:end-1,:,:); \n By(1:n0) = reshape(dummy,n0,1)/h(1);\n \n % d21 y1 : n1 -> j3\n dummy = zeros(m(1)+1,m(2)+1,m(3));\n dummy(:,2:end-1,:) = y1(:,2:end,:) - y1(:,1:end-1,:); \n By(n0+(1:j3)) = reshape(dummy,j3,1)/h(2);\n \n % d31 y1 : n1 -> j2\n dummy = zeros(m(1)+1,m(2),m(3)+1);\n dummy(:,:,2:end-1) = y1(:,:,2:end) - y1(:,:,1:end-1);\n By(n0+j3+(1:j2)) = reshape(dummy,j2,1)/h(3);\n\n \n % d12 y2 : n2 -> j3\n dummy = zeros(m(1)+1,m(2)+1,m(3));\n dummy(2:end-1,:,:) = y2(2:end,:,:) - y2(1:end-1,:,:); \n By(p1+(1:j3)) = reshape(dummy,j3,1)/h(1);\n\n % d22 y2 : n2 -> n0\n dummy = y2(:,2:end,:) - y2(:,1:end-1,:); \n By(p1+j3+(1:n0)) = reshape(dummy,n0,1)/h(2); \n\n % d32 y2 : n2 -> j1\n dummy = zeros(m(1),m(2)+1,m(3)+1);\n dummy(:,:,2:end-1) = y2(:,:,2:end) - y2(:,:,1:end-1); \n By(p1+j3+n0+(1:j1)) = reshape(dummy,j1,1)/h(3);\n \n \n % d13 y3 : n3 -> j2\n dummy = zeros(m(1)+1,m(2),m(3)+1);\n dummy(2:end-1,:,:) = y3(2:end,:,:) - y3(1:end-1,:,:);\n By(p2+(1:j2)) = reshape(dummy,j2,1)/h(1);\n\n % d23 y3 : n3 -> j1\n dummy = zeros(m(1),m(2)+1,m(3)+1);\n dummy(:,2:end-1,:) = y3(:,2:end,:) - y3(:,1:end-1,:);\n By(p2+j2+(1:j1)) = reshape(dummy,j1,1)/h(2);\n \n % d33 y3 : n3 -> n0\n dummy = y3(:,:,2:end) - y3(:,:,1:end-1); \n By(p2+j2+j1+(1:n0)) = reshape(dummy,n0,1)/h(3); \n \n \n % div u\n By(end-n0+1:end) = By(1:n0)+By(p1+j3+(1:n0)) + By(p2+j2+j1+(1:n0));\n \n By(1:end-n0) = a*By(1:end-n0);\n By(end-n0+1:end) = b*By(end-n0+1:end);\n\n \n case 'elastic-stg-BTy-2'\n \n \n % the input yc is the result of B*y, therefore it can be splitted into 5\n % parts: d11u1, d21u1,d12u2,d22u2,Divy\n \n nc = m(1)*m(2);\n nn = (m(1)+1)*(m(2)+1);\n ns1 = (m(1)+1)*m(2);\n ns2 = m(1)*(m(2)+1);\n \n By = zeros(ns1+ns2,1);\n I11 = 1:nc; % d11 y1\n I21 = I11(end)+(1:nn-2*(m(1)+1)); % d21 y1\n I12 = I21(end)+(1:nn-2*(m(2)+1)); % d12 y2\n I22 = I12(end)+(1:nc); % d22 y2\n I00 = I22(end)+(1:nc); % div Y\n \n yd = reshape(yc(I11),m);\n zd = reshape([-yd(1,:);yd(1:end-1,:)-yd(2:end,:);yd(end,:)],ns1,1)/h(1);\n By(1:ns1) = a*zd;\n \n yd = reshape(yc(I21),m(1)+1,m(2)-1);\n zd = reshape([-yd(:,1),yd(:,1:end-1)-yd(:,2:end),yd(:,end)],ns1,1)/h(2);\n By(1:ns1) = By(1:ns1) + a*zd;\n\n yd = reshape(yc(I00),m);\n zd = reshape([-yd(1,:);yd(1:end-1,:)-yd(2:end,:);yd(end,:)],ns1,1)/h(1);\n By(1:ns1) = By(1:ns1) + b*zd;\n\n yd = reshape(yc(I12),m(1)-1,m(2)+1);\n zd = reshape([-yd(1,:);yd(1:end-1,:)-yd(2:end,:);yd(end,:)],ns2,1)/h(1);\n By(1+ns1:end) = a*zd;\n\n yd = reshape(yc(I22),m);\n zd = reshape([-yd(:,1),yd(:,1:end-1)-yd(:,2:end),yd(:,end)],ns2,1)/h(2);\n By(1+ns1:end) = By(1+ns1:end) + a*zd;\n\n yd = reshape(yc(I00),m);\n zd = reshape([-yd(:,1),yd(:,1:end-1)-yd(:,2:end),yd(:,end)],ns2,1)/h(2);\n By(1+ns1:end) = By(1+ns1:end) + b*zd;\n \n case 'elastic-stg-BTy-3'\n \n % the input yc is the result of B*y, therefore it can be splitted into 10\n % parts: d11y1, d21y1,d31y1,d12y2,d22y2,d32y2,d13y3,d23y3,u33y3,Divy\n \n n0 = m(1)*m(2)*m(3);\n n1 = (m(1)+1)*m(2)*m(3);\n n2 = m(1)*(m(2)+1)*m(3);\n n3 = m(1)*m(2)*(m(3)+1);\n \n j1 = m(1)*(m(2)+1)*(m(3)+1);\n j2 = (m(1)+1)*m(2)*(m(3)+1);\n j3 = (m(1)+1)*(m(2)+1)*m(3);\n \n p1 = n0 + j2 + j3;\n p2 = p1 + n0 + j1 + j3;\n p3 = p2 + n0 + j1 + j2;\n \n\n By = zeros(n1+n2+n3,1);\n\n % extract Divy\n Divy = reshape(yc(end-n0+1:end),m(1),m(2),m(3));\n\n % ---------------------------------- part 1 of u\n % extract D11y1, boundary condition for tangential derivative\n uu = reshape(yc(1:n0),m(1),m(2),m(3));\n dummy = zeros(m(1)+1,m(2),m(3));\n dummy(1,:,:) = -uu(1,:,:);\n dummy(end,:,:) = uu(end,:,:);\n dummy(2:end-1,:,:) = uu(1:end-1,:,:) - uu(2:end,:,:);\n By(1:n1) = a*reshape(dummy,n1,1)/h(1);\n\n % extract D21y1, boundary condition for normal derivative\n uu = reshape(yc(n0+(1:j3)),m(1)+1,m(2)+1,m(3));\n uu(:,[1,end],:) = 0;\n dummy = uu(:,1:end-1,:) - uu(:,2:end,:);\n By(1:n1) = By(1:n1) + a*reshape(dummy,n1,1)/h(2);\n \n % extract D31u1, boundary condition for normal derivative\n uu = reshape(yc(n0+j3+(1:j2)),m(1)+1,m(2),m(3)+1); \n uu(:,:,[1,end]) = 0;\n dummy = uu(:,:,1:end-1) - uu(:,:,2:end);\n By(1:n1) = By(1:n1) + a*reshape(dummy,n1,1)/h(3);\n \n % Divy, boundary condition for tangential derivative\n dummy = zeros(m(1)+1,m(2),m(3));\n dummy(1,:,:) = -Divy(1,:,:);\n dummy(end,:,:) = Divy(end,:,:);\n dummy(2:end-1,:,:) = Divy(1:end-1,:,:) - Divy(2:end,:,:);\n By(1:n1) = By(1:n1) + b*reshape(dummy,n1,1)/h(1);\n\n % ---------------------------------- part 2 of y\n % extract D12y2, boundary condition for normal derivative\n uu = reshape(yc(p1+(1:j3)),m(1)+1,m(2)+1,m(3));\n uu([1,end],:,:) = 0;\n dummy = uu(1:end-1,:,:) - uu(2:end,:,:);\n By(n1+(1:n2)) = a*reshape(dummy,n2,1)/h(1);\n \n % extract D22y2, boundary condition for tangential derivative\n uu = reshape(yc(p1+j3+(1:n0)),m(1),m(2),m(3));\n dummy = zeros(m(1),m(2)+1,m(3));\n dummy(:,1,:) = -uu(:,1,:);\n dummy(:,end,:) = uu(:,end,:);\n dummy(:,2:end-1,:) = uu(:,1:end-1,:) - uu(:,2:end,:);\n By(n1+(1:n2)) = By(n1+(1:n2)) + a*reshape(dummy,n2,1)/h(2);\n \n % extract D32y2, boundary condition for normal derivative\n uu = reshape(yc(p1+j3+n0+(1:j1)),m(1),m(2)+1,m(3)+1);\n uu(:,:,[1,end]) = 0;\n dummy = uu(:,:,1:end-1) - uu(:,:,2:end);\n By(n1+(1:n2)) = By(n1+(1:n2)) + a*reshape(dummy,n2,1)/h(3);\n \n % Divy, boundary condition for tangential derivative\n dummy = zeros(m(1),m(2)+1,m(3));\n dummy(:,1,:) = -Divy(:,1,:);\n dummy(:,end,:) = Divy(:,end,:);\n dummy(:,2:end-1,:) = Divy(:,1:end-1,:) - Divy(:,2:end,:);\n By(n1+(1:n2)) = By(n1+(1:n2)) + b*reshape(dummy,n2,1)/h(2);\n \n % ---------------------------------- part 3 of y\n % extract D13y3, boundary condition for normal derivative\n uu = reshape(yc(p2+(1:j2)),m(1)+1,m(2),m(3)+1); \n uu([1,end],:,:) = 0;\n dummy = uu(1:end-1,:,:) - uu(2:end,:,:);\n By(n1+n2+(1:n3)) = a*reshape(dummy,n3,1)/h(1);\n \n % extract D23y3, boundary condition for normal derivative\n uu = reshape(yc(p2+j2+(1:j1)),m(1),m(2)+1,m(3)+1);\n uu(:,[1,end],:) = 0;\n dummy = uu(:,1:end-1,:) - uu(:,2:end,:);\n By(n1+n2+(1:n3)) = By(n1+n2+(1:n3)) + a*reshape(dummy,n3,1)/h(2);\n \n % extract D32y2, boundary condition for tangential derivative\n uu = reshape(yc(p2+j2+j1+(1:n0)),m(1),m(2),m(3));\n dummy = zeros(m(1),m(2),m(3)+1);\n dummy(:,:,1) = -uu(:,:,1);\n dummy(:,:,end) = uu(:,:,end);\n dummy(:,:,2:end-1) = uu(:,:,1:end-1) - uu(:,:,2:end);\n By(n1+n2+(1:n3)) = By(n1+n2+(1:n3)) + a*reshape(dummy,n3,1)/h(3);\n \n % Divy, boundary condition for tangential derivative \n dummy = zeros(m(1),m(2),m(3)+1);\n dummy(:,:,1) = -Divy(:,:,1);\n dummy(:,:,end) = Divy(:,:,end);\n dummy(:,:,2:end-1) = Divy(:,:,1:end-1) - Divy(:,:,2:end);\n By(n1+n2+(1:n3)) = By(n1+n2+(1:n3)) + b*reshape(dummy,n3,1)/h(3);\n \n \n otherwise, jmerror(flag)\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/mrBOLD/Analysis/RetinotopyModelFit/Version10/solvers/mfBy.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240895276223, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.5417377211735904}} {"text": "function feasible = checkfeasiblefast(p,x,tol)\n\nfeasible = 0;\nif isempty(x)\n return\nend\nif ~(all(x < p.ub+tol) && all(x > p.lb-tol))\n return\nend\n\nif ~isempty(p.F_struc)\n vecres = p.F_struc*[1;x];\n\n if any(p.K.f)\n if any(-abs(vecres(1:p.K.f)) < - tol)\n return\n end\n end\n\n if any(p.K.l)\n if any(vecres(p.K.f+1:p.K.f+p.K.l) <-tol)\n return\n end\n end\n\n if any(p.K.q)\n top = startofSOCPCone(p.K);\n for i = 1:length(p.K.q)\n n = p.K.q(i);\n X = vecres(top:top+n-1);top = top+n;\n if X(1)-norm(full(X(2:end))) < -tol\n return\n end\n end\n end\n \n if any(p.K.e)\n top = startofEXPCone(p.K);\n for i = 1:p.K.e ;\n X = vecres(top:top+2);top = top+3;\n if X(2)==0 && X(3) < -tol\n return\n elseif X(3) - X(2)*exp(X(1)/X(2)) < -tol\n return\n end\n end\n end\n \n if any(p.K.p)\n top = startofPOWCone(p.K);\n for i = 1:length(p.K.p)\n X = vecres(top:top+p.K.p(i)-1);\n a = X(end);\n top = top+p.K.p(i);\n if X(1)^a*X(2)^(1-a) - norm(X(3:end-1)) < -tol\n return\n end\n end\n end\n\n if any(p.K.s)\n top = startofSDPCone(p.K);\n for i = 1:length(p.K.s)\n n = p.K.s(i);\n X = reshape(vecres(top:top+n^2-1),n,n);top = top+n^2;\n X = (X+X')/2 + tol*eye(n);\n [~,fail] = chol(X);\n if fail\n return\n end\n end\n end\nend\nfeasible = 1;", "meta": {"author": "yalmip", "repo": "YALMIP", "sha": "f6d5a6d4222a4d722de30bffb43cae4b3e13b860", "save_path": "github-repos/MATLAB/yalmip-YALMIP", "path": "github-repos/MATLAB/yalmip-YALMIP/YALMIP-f6d5a6d4222a4d722de30bffb43cae4b3e13b860/extras/checkfeasiblefast.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770433, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.5417377168216648}} {"text": "function [surf, labels] = imSurfaceArea(img, varargin)\n% Surface area of the regions within a 3D binary or label image.\n%\n% S = imSurfaceArea(IMG)\n% Estimates the surface area of the 3D binary structure represented by\n% IMG.\n%\n% S = imSurfaceArea(IMG, NDIRS)\n% Specifies the number of directions used for estimating surface area.\n% NDIRS can be either 3 or 13, default is 13.\n%\n% S = imSurfaceArea(..., SPACING)\n% Specifies the spatial calibration of the image. SPACING is a 1-by-3 row\n% vector containing the voxel size in the X, Y and Z directions, in that\n% orders. \n%\n% S = imSurfaceArea(LBL)\n% [S, L] = imSurface(LBL)\n% When LBL is a label image, returns the surface area of each label in\n% the 3D array, and eventually returns the indices of processed labels.\n%\n% S = imSurfaceArea(..., LABELS)\n% In the case of a label image, specifies the labels of the region to\n% analyse.\n%\n%\n% Example\n% % Create a binary image of a ball\n% [x y z] = meshgrid(1:100, 1:100, 1:100);\n% img = sqrt( (x-50.12).^2 + (y-50.23).^2 + (z-50.34).^2) < 40;\n% % compute surface area of the ball\n% S = imSurfaceArea(img)\n% S =\n% 2.0103e+04\n% % compare with theoretical value\n% Sth = 4*pi*40^2;\n% 100 * (S - Sth) / Sth\n% ans = \n% -0.0167\n%\n% % compute surface area of several regions in a label image\n% img = uint8(zeros(10, 10, 10));\n% img(2:3, 2:3, 2:3) = 1;\n% img(5:8, 2:3, 2:3) = 2;\n% img(5:8, 5:8, 2:3) = 4;\n% img(2:3, 5:8, 2:3) = 3;\n% img(5:8, 5:8, 5:8) = 8;\n% [surfs, labels] = imSurfaceArea(img)\n% surfs =\n% 16.4774\n% 29.1661\n% 29.1661\n% 49.2678\n% 76.7824\n% labels =\n% 1\n% 2\n% 3\n% 4\n% 8\n%\n%\n% See also\n% imVolume, imMeanBreadth, imSurfaceAreaDensity, imJointSurfaceArea\n%\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%% Parse input arguments\n\n% check image dimension\nif ndims(img) ~= 3\n error('first argument should be a 3D image');\nend\n\n% the labels to compute\nlabels = [];\n\n% default number of directions\nnDirs = 13;\n\n% default image calibration\ndelta = [1 1 1];\n\n% methods to compute direction weights. Can be {'Voronoi'}, 'isotropic'.\ndirectionWeights = 'voronoi';\n\n\n% Process user input arguments\nwhile ~isempty(varargin)\n var1 = varargin{1};\n \n if isnumeric(var1)\n % option is either connectivity or resolution\n if isscalar(var1)\n nDirs = var1;\n elseif all(size(var1) == [1 3])\n delta = var1;\n elseif size(var1, 2) == 1\n labels = var1;\n end\n varargin(1) = [];\n \n elseif ischar(var1)\n if length(varargin) < 2\n error('optional named argument require a second argument as value');\n end\n if strcmpi(var1, 'directionweights')\n directionWeights = varargin{2};\n end\n varargin(1:2) = [];\n \n else\n error('option should be numeric');\n end\n \nend\n\n\n%% Process label image\n\n% in case of a label image, return a vector with a set of results\nif ~islogical(img)\n % extract labels if necessary (considers 0 as background)\n if isempty(labels)\n labels = imFindLabels(img);\n end\n \n % allocate result array\n nLabels = length(labels);\n surf = zeros(nLabels, 1);\n\n % compute bounding box of each region\n boxes = imBoundingBox(img, labels);\n \n % Compute surface area of each region considered as binary image\n % The computation is performed on a subset of the image for reducing\n % memory footprint.\n for i = 1:nLabels\n label = labels(i);\n \n % convert bounding box to image extent, in x, y and z directions\n box = boxes(i,:);\n i0 = ceil(box([3 1 5]));\n i1 = floor(box([4 2 6]));\n \n % crop image of current label\n bin = img(i0(1):i1(1), i0(2):i1(2), i0(3):i1(3)) == label;\n surf(i) = imSurfaceArea(bin, nDirs, delta, 'directionWeights', directionWeights);\n end\n \n return;\nend\n\n\n\n%% Process binary images\n\n% in case of binary image, compute only one label...\nlabels = 1;\n\n% distances between a pixel and its neighbours.\nd1 = delta(1); % x\nd2 = delta(2); % y\nd3 = delta(3); % z\n\n% volume of a voxel (used for computing line densities)\nvol = d1 * d2 * d3;\n\n\n%% Main processing for 3 directions\n\n% number of voxels\nnv = sum(img(:));\n\n% number of connected components along the 3 main directions\n% (Use Graph-based formula: chi = nVertices - nEdges)\nn1 = nv - sum(sum(sum(img(:,1:end-1,:) & img(:,2:end,:)))); % x\nn2 = nv - sum(sum(sum(img(1:end-1,:,:) & img(2:end,:,:)))); % y\nn3 = nv - sum(sum(sum(img(:,:,1:end-1) & img(:,:,2:end)))); % z\n\nif nDirs == 3\n % compute surface area by averaging over the 3 main directions\n surf = 4/3 * (n1/d1 + n2/d2 + n3/d3) * vol;\n return;\nend\n\n\n%% Additional processing for 13 directions\n\n% Number of connected components along diagonals contained in the three\n% main planes\n% XY planes\nn4 = nv - sum(sum(sum(img(2:end,1:end-1,:) & img(1:end-1,2:end,:))));\nn5 = nv - sum(sum(sum(img(1:end-1,1:end-1,:) & img(2:end,2:end,:))));\n% XZ planes\nn6 = nv - sum(sum(sum(img(:,2:end,1:end-1) & img(:,1:end-1,2:end))));\nn7 = nv - sum(sum(sum(img(:,1:end-1,1:end-1) & img(:,2:end,2:end))));\n% YZ planes\nn8 = nv - sum(sum(sum(img(2:end,:,1:end-1) & img(1:end-1,:,2:end))));\nn9 = nv - sum(sum(sum(img(1:end-1,:,1:end-1) & img(2:end,:,2:end))));\n\n%TODO: add the case of 9 directions ?\n\n% Number of connected components along lines corresponding to diagonals of\n% the unit cube\nn10 = nv - sum(sum(sum(img(1:end-1,1:end-1,1:end-1) & img(2:end,2:end,2:end))));\nn11 = nv - sum(sum(sum(img(2:end,1:end-1,1:end-1) & img(1:end-1,2:end,2:end))));\nn12 = nv - sum(sum(sum(img(1:end-1,2:end,1:end-1) & img(2:end,1:end-1,2:end))));\nn13 = nv - sum(sum(sum(img(2:end,2:end,1:end-1) & img(1:end-1,1:end-1,2:end))));\n\n% space between 2 voxels in each direction\nd12 = hypot(d1, d2);\nd13 = hypot(d1, d3);\nd23 = hypot(d2, d3);\nd123 = sqrt(d1^2 + d2^2 + d3^2);\n\n% Compute weights corresponding to surface fraction of spherical caps\n% For isotropic case, weights correspond to:\n% c1 = 0.04577789120476 * 2; % Ox\n% c2 = 0.04577789120476 * 2; % Oy\n% c3 = 0.04577789120476 * 2; % Oz\n% c4 = 0.03698062787608 * 2; % Oxy\n% c6 = 0.03698062787608 * 2; % Oxz\n% c8 = 0.03698062787608 * 2; % Oyz\n% c10 = 0.03519563978232 * 2; % Oxyz\nif strcmp(directionWeights, 'isotropic')\n c = zeros(13,1);\n c(1) = 0.04577789120476 * 2; % Ox\n c(2) = 0.04577789120476 * 2; % Oy\n c(3) = 0.04577789120476 * 2; % Oz\n c(4:5) = 0.03698062787608 * 2; % Oxy\n c(6:7) = 0.03698062787608 * 2; % Oxz\n c(8:9) = 0.03698062787608 * 2; % Oyz\n c(10:13) = 0.03519563978232 * 2; % Oxyz\n \nelse\n c = computeDirectionWeights3d13(delta);\nend\n\n\n% compute the weighted sum of each direction\n% intersection count * direction weight / line density\nsurf = 4 * vol * (...\n n1*c(1)/d1 + n2*c(2)/d2 + n3*c(3)/d3 + ...\n (n4+n5)*c(4)/d12 + (n6+n7)*c(6)/d13 + (n8+n9)*c(8)/d23 + ...\n (n10 + n11 + n12 + n13)*c(10)/d123 );\n\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/imSurfaceArea.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833737577158, "lm_q2_score": 0.6992544273261176, "lm_q1q2_score": 0.5416308534332837}} {"text": "function [xo,Ot,nS]=buscarnd(S,x0,ip,nOt,samples,Lb,Ub,problem,tol,mxit,R,red,mem)\n% Unconstrained global optimization using adaptive random search.\n%\n% [xo,Ot,nS]=buscarnd(S,x0,ip,nOt,samples,Lb,Ub,problem,tol,mxit,R,red,mem)\n%\n% S: objective function\n% x0: initial point\n% ip: (0): no plot (default), (>0) plot figure ip with pause, (<0) plot figure ip\n% nOt: maximum number of optimal points (default = 1)\n% samples: number of samples per stage (default = 3*size(x0(:),1))\n% Lb, Ub: lower and upper bound vectors to plot (default = x0*(1+/-2))\n% problem: (-1): minimum (default), (1): maximum\n% tol: tolerance (default = 1e-4)\n% mxit: maximum number of stages (default = 50*(1+4*~(ip>0)))\n% R: axis vector of the hyperellipse centered in x0 (default = max(0.1*abs(x0+~x0),1))\n% red: factor to reduce the size of the axis vector (0,1) (default = 0.2)\n% mem: number of stored points during the exploration phase [0, min(18,samples-1)]\n% xo: matrix of optimal points (column vectors)\n% Ot: vector of optimal values of S\n% nS: number of objective function evaluations\n\n% Copyright (c) 2001 by LASIM-DEQUI-UFRGS\n% $Revision: 1.0 $ $Date: 2001/07/10 19:40:05 $\n% Argimiro R. Secchi (arge@enq.ufrgs.br)\n%\n% Based on the algorithm of the same author written in C\n% for constrained global optimization in 1989/09/29 and published as:\n% A.R. Secchi and C.A. Perlingeiro, \"Busca Aleatoria Adaptativa\",\n% in Proc. of XII Congresso Nacional de Matematica Aplicada e\n% Computacional, Sao Jose do Rio Preto, SP, pp. 49-52 (1989).\n%\n% Modified by Giovani Tonel(giovani.tonel@ufrgs.br) on September 2006\n\n\n\nrand('state',sum(100*clock)); \t%rand('state',sum(100*clock)) resets it to \n\t\t\t\t\t\t\t\t\t\t\t\t\t%\t\t a different state each time.\n\n\n\nif nargin < 2,\n error('buscarnd requires two input arguments');\n end\n if nargin < 3 | isempty(ip),\n ip=0;\n end\n if nargin < 4 | isempty(nOt),\n nOt=1;\n end\n if nargin < 5 | isempty(samples),\n samples=3*size(x0(:),1);\n end\n if nargin < 6 | isempty(Lb),\n Lb=-x0-~x0;\n end\n if nargin < 7 | isempty(Ub),\n Ub=2*x0+~x0;\n end\n if nargin < 8 | isempty(problem),\n problem=-1;\n end\n if nargin < 9 | isempty(tol),\n tol=1e-4;\n end\n if nargin < 10 | isempty(mxit),\n mxit=50*(1+4*~(ip>0));\n end\n if nargin < 11 | isempty(R),\n R=max(0.1*abs(x0+~x0),1);\n end\n if nargin < 12 | isempty(red) | red <= 0 | red >= 1,\n red=0.2;\n end\n if nargin < 13 | isempty(mem),\n mem=min(18,samples-1);\n end\n if mem >= samples,\n mem=samples-1;\n end\n % initialization \n x0=x0(:);\n R=abs(R(:));\n n=size(x0,1);\n distrib=1; % distr = 1 --> exploration phase\n % distr > 1 --> progression phase\n asym1=-1*ones(n,1); % asym1 = 1 --> asymmetric distribution to reduce xo\n % asym1 = -1 --> asymmetric distribution to increase xo\n asym2=2*ones(n,1); % asym2 = 2 --> symmetric distribution\n % asym2 = 1.5 --> asymmetric distribution\n metric=0.5*norm(R);\n a0=0.5*metric;\n a2=0.1*metric;\n a3=10*tol;\n n3=1;\n holdm=floor(1/red+0.5)*n;\n nhold=0; % counter to keep distribution constant during holdm times\n\n top=0;\n if mem > 0,\n n4=10*mem;\n idx=[1:n4+1];\n last=n4;\n first=0;\n idx(last+1)=first;\n mem_x=zeros(n,n4);\n mem_S=-ones(1,n4)*inf;\n end\n\n% Criterion of axis vector reduction\n%\n% R_red = R*0.5^(distrib-1)\n%\n% or norm(R_red) = norm(R)*0.5^(distrib-1)\n%\n% then if the criterion is norm(R_red) < tol = 10^(-asc)\n%\n% the distrib is limited by\n%\n% distrib = 1 + (asc + log10(norm(R))) / log10(2)\n\n lim_distrib=floor(0.5*(1+log10(metric/tol)/log10(2.0)));\n\n if ip & n == 2,\n figure(abs(ip));\n [X1,X2]=meshgrid(Lb(1):(Ub(1)-Lb(1))/20:Ub(1),Lb(2):(Ub(2)-Lb(2))/20:Ub(2));\n [n1,n2]=size(X1);\n f=zeros(n1,n2);\n for i=1:n1,\n for j=1:n2,\n f(i,j)=feval(S,[X1(i,j);X2(i,j)]);\n end\n end\n mxf=max(max(f));\n mnf=min(min(f));\n df=mnf+(mxf-mnf)*(2.^(([0:10]/10).^2)-1);\n [v,h]=contour(X1,X2,f,df); hold on;\n% clabel(v,h);\n h1=plot(x0(1),x0(2),'ro');\n legend(h1,'start point');\n\n if ip > 0,\n disp('Pause: hit any key to continue...'); pause;\n end\n end\n\n xOt=[];\n Ot=[];\n xo=x0;\n yo=feval(S,x0)*problem;\n nS=1;\n it=0;\n opt=0;\n x=zeros(n,samples);\n y=zeros(1,samples);\n \n while it < mxit & opt < nOt,\n l3=0;\n it=it+1;\n for j=1:samples, % sampling\n a=min(max(rand(n,1),0.05),0.95);\n x(:,j)=xo+(R.*asym1.*(asym2.*a-1).^distrib)/distrib;\n y(j)=feval(S,x(:,j))*problem;\n nS=nS+1;\n end\n\n l4=mem & distrib == 1; % sorting the samples\n if samples > 1,\n if ~l4, \n [y(1),i]=max(y);\n x(:,1)=x(:,i);\n else\n [y,i]=sort(-y); y=-y;\n x=x(:,i);\n end\n end\n\n if l4, % memorize samples\n n2=top;\n l1=0;\n for j=1:samples,\n n1=0;\n if opt,\n for i=1:opt\n if norm(xOt(:,i)-x(:,j)) < a2,\n n1=1;\n if j == 1,\n l1=1;\n end\n break;\n end\n end\n end\n \n if ~n1, \n\tfor i=1:j-1\n\t if norm(x(:,j)-x(:,i)) < metric,\n\t n1=1;\n\t break;\n\t end\n\tend\n\t\n\tif ~n1,\n\t k=idx(1);\n\t for i=1:top\n if norm(mem_x(:,k)-x(:,j)) < metric,\n n1=1;\n break;\n else\n k=idx(k+1);\n end\n end\n \n\t if ~n1,\n first=idx(first+1);\n if ~first, % expand memory\n mem_x=[mem_x,zeros(n,n4)];\n mem_S=[mem_S,-ones(1,n4)*inf];\n idx=[idx,[n2+1:n2+n4+1]];\n first=n2;\n idx(last+1)=first;\n last=n2+n4;\n idx(last+1)=0;\n end\n k=first;\n n2=n2+1;\n end \n\n if ~n1 | y(j) > mem_S(k),\n mem_x(:,k)=x(:,j);\n mem_S(:,k)=y(j);\n end\n \n\t if l1,\n l1=0;\n x(:,1)=x(:,j);\n y(1)=y(j);\n end \n end \n end\n \n if n2-top == mem,\n break;\n end\n end\n top=n2;\n end\n % analysis of best sampled point\n a1=norm(x(:,1)-xo)/(0.1+norm(xo))+abs(y(1)-yo)/(0.1+abs(yo));\n l1=y(1) > yo;\n if l1,\n if norm(x(:,1)-xo) > a0,\n nhold=0;\n n3=1;\n end\n \n z=xo; xo=x(:,1); x(:,1)=z;\n a4=yo; yo=y(1); y(1)=a4;\n \n if ip & n == 2,\n plot([x(1) xo(1)],[x(2) xo(2)],'r');\n if ip > 0,\n disp('Pause: hit any key to continue...'); pause;\n end\n end\n end\n\n if a1 < tol & distrib >= lim_distrib,\n l2=1;\n if opt,\n for i=1:opt,\n if norm(xOt(:,i)-xo) < a3,\n l2=0;\n break;\n end\n end\n end\n\n if l2,\n opt=opt+1;\n Ot=[Ot,yo];\n xOt=[xOt,xo];\n if ip & n == 2,\n h2=plot(xo(1,:),xo(2,:),'r*');\n if opt == 1,\n legend([h1,h2],'start point','optimum');\n end\n end\n end\n\n % rescue another point from memory\n if ~top,\n if opt,\n xo=xOt;\n yo=Ot;\n end\n break;\n end\n \n if l2 & ~l1,\n n2=0;\n for j=1:top,\n k=idx(n2+1);\n if norm(mem_x(:,k)-xo) < a2,\n top=top-1;\n idx(last+1)=k;\n last=k;\n idx(n2+1)=idx(k+1);\n idx(k+1)=0;\n if k == first,\n first=n2;\n end\n else\n n2=k;\n end\n end\n end\n\n if ~top,\n if opt,\n xo=xOt;\n yo=Ot;\n end\n break;\n end\t\n \n k=idx(1);\n xo=mem_x(:,k);\n yo=mem_S(k);\n idx(last+1)=k;\n last=k;\n idx(1)=idx(k+1);\n idx(k+1)=1;\n top=top-1;\n \n if k == first,\n first=1;\n end\n \n l3=1;\n\n if ip & n == 2 & opt < nOt,\n plot(xo(1),xo(2),'ro');\n end\n elseif opt & (~l1 | (l1 & ~l4))\n n1=0;\n\tfor i=1:opt,\n if norm(xOt(:,i)-xo) < a2,\n n1=1;\n break;\n end\n end\n\t\n\tif n1,\n if ~top,\n xo=xOt;\n yo=Ot;\n break;\n end\t\n \n k=idx(1);\n xo=mem_x(:,k);\n yo=mem_S(k);\n idx(last+1)=k;\n last=k;\n idx(1)=idx(k+1);\n idx(k+1)=1;\n top=top-1;\n\n if k == first,\n first=1;\n end\n\n\t l3=1;\n\t \n if ip & n == 2 & opt < nOt,\n plot(xo(1),xo(2),'ro');\n end\n end\n end\n % adjust search direction and criterion\n if l3,\n n3=1;\n distrib=1;\n nhold=0;\n elseif (a1 < a2 | ~l1) & (nhold+n3 > holdm),\n n3 = n3+~mod(distrib,3);\n distrib=distrib+2;\n\tnhold=0;\n else\n nhold=nhold+n3;\n end\n \n for i=1:n,\n if l3 | (~l3 & x(i,1) == xo(i)),\n asym2(i)=2;\n else\n asym2(i)=1.5;\n if x(i,1) < xo(i),\n asym1(i)=1;\n else\n asym1(i)=-1;\n end\n end\n end\n end\n \n if it == mxit,\n %disp('Warning Buscarnd: reached maximum number of stages!');\n if opt,\n yo=Ot;\n xo=xOt;\n end\n end\n\n if opt == nOt,\n yo=Ot;\n xo=xOt;\n end\n \n if opt > 1,\n [yo,i]=sort(-yo); yo=-yo;\n xo=xo(:,i);\n end\n \n Ot=yo*problem;\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/12776-ramdomic-search/buscarnd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.6992544147913993, "lm_q1q2_score": 0.5416308510013851}} {"text": "% @author: Maziar Raissi\n\nfunction params = Fractional_Levy()\n\nclc; close all;\n\nplt = 1;\nplt_pred = 0;\nsave_plt = 1;\n\naddpath ..\naddpath ../Utilities\naddpath ../Kernels/Fractional_Levy\naddpath ../Utilities/export_fig\n\nfunction CleanupFun()\n rmpath ..\n rmpath ../Utilities\n rmpath ../Kernels/Fractional_Levy\n rmpath ../Utilities/export_fig\nend\n\nfinishup = onCleanup(@() CleanupFun());\n\nrng('default')\n\nset(0,'defaulttextinterpreter','latex')\n\n%% Load Data\n[t_star, x_star, u_star, pos] = gen_data(10^6, 0.01, 5, 100);\n% u_star --> 100x5\n% t_star --> 5x1\n% x_star --> 100x1\nN_star = size(x_star,1);\nnsteps = size(t_star,1)-1;\n \n%% Setup\nN0 = 100;\nN1 = 100;\n%% Clean Data\ni = 4;\ndt = t_star(i+1) - t_star(i);\n\nidx0 = randsample(N_star, N0);\nx0 = x_star(idx0,:);\nu0 = u_star(idx0,i);\n\nidx1 = randsample(N_star,N1);\nx1 = x_star(idx1,:);\nu1 = u_star(idx1,i+1);\n \nhyp = [log([1.0 0.1]) 1.1 0.0];\nmodel = HPM(x1, u1, x0, u0, dt, hyp);\nmodel = model.train(1500);\n \nhyp = model.hyp;\nparams = hyp(3);\n \n[pred_n_star, var_n_star] = model.predict(x_star);\nvar_n_star = abs(diag(var_n_star));\n \nerror = norm(pred_n_star - u_star(:,i+1))/norm(u_star(:,i+1));\n \nfprintf(1,'=========================\\n');\nfprintf(1,'Step: %d, Time = %.2f\\n\\nNLML = %.2f, Error = %.2e\\n\\n', i, ...\n t_star(i+1), model.NLML, error);\n\nstr = sprintf('%.2f ', params);\nfprintf('Parameters: %s\\n\\n', str)\nfprintf(1,'=========================\\n\\n');\n \nif plt_pred == 1\n figure();\n plot_prediction_1D(x_star, u_star(:,i+1), pred_n_star, var_n_star, ...\n '$x$', '$u(t,x)$', 'Prediction');\n \n drawnow;\nend\n\n\n%% Plot Results\n\nif plt == 1\n fig = figure();\n set(fig,'units','normalized','outerposition',[0 0 1 .5])\n subplot(3,2,1:2)\n plot(pos, 'b', 'LineWidth', 2);\n xlabel('Time')\n ylabel('Position')\n axis tight\n set(gca,'FontSize',14);\n set(gcf, 'Color', 'w');\n \n subplot(3,2,3);\n tit = sprintf('$t = $ %.2f\\n%d training data\\n', t_star(i), N0);\n bar(x_star, u_star(:,i),'m');\n xlabel('$x$')\n ylabel('$u(t,x)$')\n axis tight\n set(gca,'FontSize',14);\n set(gcf, 'Color', 'w');\n title(tit);\n \n subplot(3,2,4);\n tit = sprintf('$t = $ %.2f\\n%d training data\\n', t_star(i+1), N1);\n bar(x_star, u_star(:,i+1),'m');\n xlabel('$x$')\n ylabel('$u(t,x)$')\n axis tight\n set(gca,'FontSize',14);\n set(gcf, 'Color', 'w');\n title(tit);\n \n subplot(3,2,5:6);\n\n s = '$\\begin{tabular}{|c|c|}';\n s = strcat(s, ' \\hline');\n s = strcat(s, ' Correct PDE & $u_t + (-\\nabla^{\\sqrt{2}}_x) u = 0$ \\\\');\n s = strcat(s, ' \\hline');\n s = strcat(s, ' Identified PDE & $u_t + (-\\nabla^{', sprintf('%.3f',params(1)), '}_x) u = 0$ \\\\');\n s = strcat(s, ' \\hline');\n s = strcat(s, ' \\end{tabular}$'); \n text(0.25,0.8,s,'interpreter','latex','FontSize',18)\n axis off\n \n if save_plt == 1\n export_fig ../Figures/Fractional_Levy.png -r300\n end\n \n drawnow();\nend\n\nend\n\nfunction [t_star, x_star, u_star, pos] = gen_data(N,dt,m,n)\n \n alpha = sqrt(2);\n r = stblrnd(alpha, 0, 1, 0, N, 1);\n pos = cumsum(dt^(1/alpha)*r);\n\n M = 0.35;\n\n P = zeros(length(pos)-m,m);\n for i = 1:length(pos)-m\n y = pos(i+1:i+m) - pos(i);\n P(i,:) = y;\n end\n \n bins = linspace(-M,M,n+1);\n x_star = linspace(M*(1/n-1), M*(1-1/n), n)';\n t_star = dt*(1:1:m)';\n u_star = zeros(n,m);\n \n f = figure();\n clf\n hold\n for i = 1:m\n h = histogram(P(:,i), bins, 'Normalization', 'pdf');\n u_star(:,i) = h.Values;\n end\n \n close(f)\n\nend", "meta": {"author": "maziarraissi", "repo": "HPM", "sha": "21a7429cceb55d5ab688256db75ac360e2d8a925", "save_path": "github-repos/MATLAB/maziarraissi-HPM", "path": "github-repos/MATLAB/maziarraissi-HPM/HPM-21a7429cceb55d5ab688256db75ac360e2d8a925/Examples/Fractional_Levy.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.6992544085240401, "lm_q1q2_score": 0.5416308461467928}} {"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% For details and license info see \n% - https://github.com/C4IR/FAIR.m/tree/master/add-ons/LagLDDMM%\n% 2D Multilevel LDDMM Example using stationary velocity field and\n% diffusion regularizer.The example is described in detail in\n% Section 4.2 of the paper:\n%\n% @article{MangRuthotto2017,\n% Title = {A {L}agrangian {G}auss--{N}ewton--{K}rylov solver for mass- and intensity-preserving diffeomorphic image registration},\n% Year = {2017},\n% Journal = {SIAM Journal on Scientific Computing},\n% Author = {A. Mang, L. Ruthotto},\n% }\n% =========================================================================\n\nclose all; clear all; clc;\nsetup2Ddisc2CData\n\n%% run affine pre-registration\nimgModel('reset','imgModel','splineInterMex','regularizer','moments','theta',.1);\n\nalpha = [4e2 0];\nparametric = 0;\npad = .5;\nN = 3;\nmV = @(m) ceil(1*m);\nminLevel = 5;\nmaxLevel = 7;\n\n%% run multilevel LDDMM registration\n\n% 1) setup grid for velocities (padded)\nomegaV = omega; omegaV(1:2:end) = omegaV(1:2:end)-pad; omegaV(2:2:end) = omega(2:2:end)+pad;\n\n% 2) setup regularizer\nregularizer('reset','regularizer','mbDiffusionCC','nt',0,'alpha',alpha,'HessianShift',1e-2);\n\nNPIRpara = optPara('NPIR-GN');\nNPIRpara.maxIter = 40;\nNPIRpara.scheme = @GaussNewtonLDDMM;\n[vc,~,wc,his] = MLLDDMM(ML,'minLevel',minLevel,'maxLevel',maxLevel,...\n 'omegaV',omegaV,'mV',mV,'N',N,'parametric',parametric,'NPIRpara',NPIRpara,'plots',1);\n\n%% show results\nyc = getTrafoFromVelocityRK4(vc,getNodalGrid(omega,m),'omega',omegaV,'m',m,'tspan',[1,0],'N',N);\nTopt = linearInterMex(dataT,omega,center(yc,m));\nJac = geometry(yc,m,'Jac','omega',omega);\nD0 = distance(dataT(:),dataR(:),omega,m);\nDOpt = distance(Topt(:),dataR(:),omega,m);\n\nfig = figure(); clf;\nfig.Name = sprintf('LDDMM Results: %s',mfilename);\n\nsubplot(2,3,1);\nviewImage(dataR,omega,m);\ntitle('reference');\n\nsubplot(2,3,4);\nviewImage(dataT,omega,m);\nhold on;\nplotGrid(yc,omega,m,'spacing',4)\ntitle('template');\n\nsubplot(2,3,2);\nviewImage(Topt,omega,m);\ntitle('T(yc)')\n\nsubplot(2,3,3);\nviewImage(dataT(:)-dataR(:),omega,m);\ntitle('init. residual, SSD=100%');\n\nsubplot(2,3,5);\nviewImage2Dsc(Jac,omega,m);\ntitle(sprintf('Jac, min=%1.2f max=%1.2f',min(Jac(:)),max(Jac(:))));\n\nsubplot(2,3,6);\nviewImage(Topt(:)-dataR(:),omega,m);\ntitle(sprintf('opt residual, SSD=%1.2f%%',100*DOpt/D0));\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/examples/ELDDMM_2Ddisc2C_mbDiffusionCC.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8499711680567799, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.5414578084726297}} {"text": "function [k, rbfPart, n2] = sqexpKernCompute(kern, x, x2)\n\n\n% SQEXPKERNCOMPUTE Compute the SQEXP kernel given the parameters and X.\n% FORMAT\n% DESC computes the kernel parameters for the pre-built compound squared exponential\n% kernel given inputs associated with rows and columns.\n% ARG kern : the kernel structure for which the matrix is computed.\n% ARG x : the input matrix associated with the rows of the kernel.\n% ARG x2 : the input matrix associated with the columns of the kernel.\n% RETURN k : the kernel matrix computed at the given points.\n%\n% FORMAT\n% DESC computes the kernel matrix for the pre-built compound squared exponential\n% kernel given a design matrix of inputs.\n% ARG kern : the kernel structure for which the matrix is computed.\n% ARG x : input data matrix in the form of a design matrix.\n% RETURN k : the kernel matrix computed at the given points.\n%\n% SEEALSO : sqexpKernParamInit, kernCompute, kernCreate, sqexpKernDiagCompute\n%\n% COPYRIGHT : Neil D. Lawrence, 2004\n\n% KERN\n\n\nif nargin < 3\n n2 = dist2(x, x);\n wi2 = (.5 .* kern.inverseWidth);\n rbfPart = kern.rbfVariance*exp(-n2*wi2);\n k = rbfPart + kern.whiteVariance*eye(size(x, 1));\nelse\n n2 = dist2(x, x2);\n wi2 = (.5 .* kern.inverseWidth);\n rbfPart = kern.rbfVariance*exp(-n2*wi2);\n k = rbfPart;\nend\nk = k + kern.biasVariance;\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/kern/sqexpKernCompute.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.849971175657575, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.5414578016003196}} {"text": "function [C, S] = QLiftDec2MinMin(X, N)\n%-----------------------------------------------------------------------------\n% QLiftDec2MinMin\n% Multilevel 2-D decomposition by the lifting scheme and using quincunx grids\n%\n% The MinMin scheme has been proposed by Heijmans and Goutsias, see e.g.\n% H.J.A.M. Heijmans, J. Goutsias,\n% Multiresolution signal decomposition schemes.\n% Part 2: morphological wavelets.\n% CWI Report PNA-R9905, Amsterdam, 1999.\n% http://repository.cwi.nl:8888/cwi_repository/docs/IV/04/04625D.pdf\n%\n% Calls for: QLmaxlev,\n% storeQ1001, storeR,\n% getcolor01, getcolor10, getcolor00, getcolor11,\n% putcolor01, putcolor10, putcolor00, putcolor11. \n% See also: QLiftRec2MaxMin\n%\n% Design and implementation by:\n% Dr. Paul M. de Zeeuw http://homepages.cwi.nl/~pauldz/\n% Last Revision: February 3, 2003.\n% (c) 1999-2003 Stichting CWI, Amsterdam\n%-----------------------------------------------------------------------------\n%Firstly, check input data\n%\nif isempty(X)\n error(' QLiftDec2MinMin - empty matrix ');\nelse\n if mod(N, 2) == 1\n error(' QLiftDec2MinMin - only an even number of levels is accepted ');\n end\n if QLmaxlev(size(X), 'minmin') < N \n error(' QLiftDec2MinMin - too many levels requested ');\n end\n if N < 2\n disp([' QLiftDec2MinMin - WARNING too few levels requested ' ...\n '-> empty decomposition ']);\n end\nend\n%\n%Secondly, start decomposition\n%\nO = X; % For the sake of efficient use of memory this could be improved upon.\n% We descend to coarser grids, integer lev indicates number of scale.\nC = []; S = [];\n\nfor lev=1:2:N\n%\n [nO, mO] = size(O);\n if ( nO < 3 ) || ( mO < 3)\n error(' QLiftDec2MinMin - too many levels ');\n end\n minO = min(min(O));\n maxO = max(max(O));\n% cmin = minO-(maxO-minO);\n cmax = maxO+(maxO-minO);\n%\n% The Lifting Scheme proceeds from a rectangular grid\n% towards a quincunx grid.\n%\n% Stage: predict\n A00 =getcolor00(O);\n A11 =getcolor11(O);\n% Quincunx grid Q0011 is the union of the values at .00 and .11: \"even slots\"\n% Quincunx grid Q1001 is the union of the values at .10 and .01: \"odd slots\"\n Q1001D01 = getcolor01(O) - synA01min(A11, A00, cmax); % Y1\n Q1001D10 = getcolor10(O) - synA10min(A11, A00, cmax); % Y1\n% At this point the union (quincunx) of Q1001D01 & Q1001D10\n% contains the DETAILS of O.\n%\n% For the inverse transform Q1001D01 and Q1001D10 have to be stored:\n [C, S] = storeQ1001( Q1001D10, Q1001D01, lev, 'd', C, S);\n%\n% Stage: update\n Q0011A00 = A00 + ...\n min(zeros(size(A00)), synA00min(Q1001D10, Q1001D01, cmax)); % X1\n clear A00;\n Q0011A11 = A11 + ...\n min(zeros(size(A11)), synA11min(Q1001D10, Q1001D01, cmax)); % X1\n clear A11 Q1001D10 Q1001D01; \n% At this point the union (quincunx) of Q0011A00 & Q0011A11\n% contains the updated APPROXIMATION of O, the DETAILS of O\n% were in the union (quincunx) of Q1001D01 & Q1001D10 (see above).\n%\n% The Lifting Scheme proceeds by a subsequent step from quincunx\n% to rectangular grid.\n%\n% Q0011 is split into the 11 colour with the \"odd slots\" and \n% the 00 colour with the \"even slots\".\n%\n% Stage: predict\n DETAIL11 = Q0011A11 - synA11Qmin(Q0011A00, size(Q0011A11), cmax); % Y2\n clear Q0011A11;\n% Stage: update\n APPROX00 = Q0011A00 + ...\n min(zeros(size(Q0011A00)), synA00Qmin(DETAIL11, size(Q0011A00), cmax));% X2\n%\n% DETAIL11 presents the detail gridfunction w.r.t. Q0011\n% APPROX00 now represents the updated version of the approximation of Q0011\n%\n% For the inverse transform DETAIL11 has to be stored:\n [C, S] = storeR( DETAIL11, lev+1, 'd', C, S);\n clear Q0011A00 DETAIL11; \n% \n% At this point gridfunction DETAIL11 containing the DETAILS has been stored,\n% gridfunction APPROX00 contains the updated APPROXIMATION, on the (down-\n% sampled) rectangular grid and has to be stored as well if at the highest\n% scale.\n% Note that APPROX00 is downsampled onto a rectangular grid with dimensions of \n% half size of the original O.\n if lev+1 >= N\n [C, S] = storeR(APPROX00, lev+1, 'a', C, S);\n% It is obligatory that at least at one scale the Approximation has to be\n% stored or else the scheme cannot be inverted.\n clear APPROX00;\n% In the Lifting Scheme all scales have now been processed!\n else\n% We proceed to the next scale.\n O = APPROX00; clear APPROX00;\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/13507-lisq-a-toolbox-for-the-lifting-scheme-on-2d-quincunx-grids/LISQ/QLiftDec2MinMin.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84997116805678, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.5414577967583792}} {"text": "function [psd, ft] = gsp_jtv_estimate_psd(G, X, param)\n%GSP_JTV_ESTIMATE_PSD Estimate the PSD of a time vertex process\n% Usage: psd = gsp_jtv_estimate_psd(G, X)\n% psd = gsp_jtv_estimate_psd(G, X, param)\n%\n% Input parameters:\n% G : Graph\n% X : Signal(s) (matrix of NxTxR)\n% param : Optional parameters\n% Output parameters:\n% psd : PSD matrix\n% ft : Filter type\n%\n% This function estimates the PSD for vertex time processes. It is a\n% generalization of the Bartlett method.\n%\n% Additional parameters\n% ---------------------\n%\n% * *param.estimator* : Method used for the estimation. By default 'TA'\n% - 'TA': Average over the time domain.\n% - 'FC': Fourier convolution a trick used to reduce the computation. \n% - 'VA': Average over the vertex domain\n% - 'TVA': Average over the time and the vertex domain\n% - 'FA' : Average on multiple realization in the joint spectral domain\n% * *param.L* : Length of the window for the 'GSTFT' method\n% * *param.kernel* : Kernel for the convolution for 'FC' method.\n%\n%\n% References: perraudin2016stationary\n\n% Author : Nathanael Perraudin\n% Date: 6 January 2016\n% Testing: test_gsp_estimate_vertex_time_psd\n\nif nargin<3\n param = struct;\nend\nif ~isfield(param,'estimator')\n param.estimator = 'FA';\nend\n\n% number of realizations\n[N, T, R] = size(X);\n\nswitch param.estimator\n \n % This method compute the Fourier transform of the signals and average\n % the modulus\n case 'FA'\n if ~isfield(param, 'L') \n param.L = compute_default_L(X,T,R);\n end\n Xhat = gsp_jft(G,reshape(X,N,param.L,R*T/param.L));\n psd = mean(abs(Xhat).^2,3);\n ft = 'js';\n \n \n % This method splits time in windows, and takes an average of the psd\n % over each time window. The size of each window (L) should be \n % equal to the maximum correlation distance in the process \n case 'TA'\n \n if ~gsp_check_fourier(G)\n error('The Fourier basis is needed the Fourier basis')\n %G = gsp_compute_fourier_basis(G);\n end\n\n if ~isfield(param, 'L') \n param.L = compute_default_L(X,T,R);\n end \n if ~isfield(param, 'a'), param.a = round(param.L/2); end\n if ~isfield(param, 'M'), param.M = G.jtv.T; end\n if ~isfield(param,'win_type'), param.win_type = 'itersine'; end\n \n if round(T/param.L) - (T/param.L) ~= 0\n warning('Optimally the length of the signal should be divisible by param.L.') \n while round(T/param.L) - (T/param.L) ~= 0\n param.L = param.L + 1;\n end\n end\n\n % Compute a Gabor window\n w = gabwin(param.win_type, param.a, param.L);\n\n % estimate the psd as the average over each realization\n psd = zeros(G.N, G.jtv.T);\n for r = 1:R\n \n % do a windowed JFT\n coeff = gsp_jtwgft(G, w, X(:,:,r), param);\n\n % compute the psd for each window\n psd_win = abs(coeff(:, 1:end-1, :)).^2;\n \n % average all windows to obtain an estimate of the psd\n psd_est = squeeze(mean(psd_win, 2));\n \n % average over realizations\n psd = psd + transpose(psd_est);\n end\n\n psd = psd / R;\n \n % normalize energy\n psd = psd * (norm(X(:), 'fro')^2/R / sum(psd(:)));\n \n % Go to the joint frequency domain and smooth out the PSD with a kernel. \n ft = 'js';\n\n case 'FC'\n if ~isfield(param, 'kernel')\n param.kernel = exp(-(-20:20).^2/3);\n end\n h = param.kernel;\n \n if ~gsp_check_fourier(G)\n G = gsp_compute_fourier_basis(G);\n end\n \n Xhat2 = abs(gsp_jft(G,X)).^2;\n \n\n psd = conv2(h', h', mean(Xhat2,3), 'same') / norm(h, 1)^2;\n% psd = conv2(mean(Xhat2,3), param.kernel, 'same') / norm(param.kernel, 1);\n\n\n % normalize energy\n psd = psd * (norm(X(:), 'fro')^2/R / sum(psd(:)));\n ft = 'js';\n\n % For scalability, \n case 'VA'\n\n if ~isfield(G,'boundary'); param.boundary = 'periodic'; end\n\n switch param.boundary\n \n case 'periodic'\n Xhat = fft(X,[],2)/sqrt(T);\n \n case 'reflecting'\n error('Sorry. Not implemented yet...')\n \n otherwise\n error('Unknown boundary condition');\n end\n \n if ~isfield(G,'lmax')\n G = gsp_estimate_lmax(G);\n \n warning(['GSP_PSD_ESTIMATION: 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 \n if ~isfield(param,'Nfilt'), param.Nfilt = 50; end\n if ~isfield(param,'Nrandom'), param.Nrandom = max(10, R); end\n if ~isfield(param,'g0')\n sigma = sqrt(2*G.lmax/param.Nfilt^2 * (param.Nfilt + 1));\n param.g0 = @(x) exp(-x.^2/sigma^2);\n end\n \n % Design the frame\n [ g , mu ] = gsp_design_translates(G, param.g0, param.Nfilt);\n %[ g , mu ] = gsp_design_itersine(G,Nfilt );\n \n % Estimate the energy of the window\n if gsp_check_fourier(G)\n mu_y2 = sum(abs(gsp_filter_evaluate(g,G.e)).^2,1)';\n else\n w = randn(N, param.Nrandom);\n x_filt2 = gsp_vec2mat( gsp_filter(G,g,w,param), param.Nfilt);\n n2_x_filt2 = sum(abs(x_filt2).^2,1);\n mu_y2 = reshape(mean(n2_x_filt2,3),[],1);\n end\n \n psd = cell(1,T);\n \n for ii = 1:T\n % Perform the filtering\n x_filt = gsp_vec2mat( ...\n gsp_filter(G, g, squeeze(Xhat(:,ii,:)), param), ...\n param.Nfilt);\n % estimate the points\n n2_x_filt = sum(abs(x_filt).^2,1);\n mu_y = reshape(mean(n2_x_filt,3),[],1);\n \n % Interpolate to obtain a nice filter.\n psd{ii} = @(s) max(spline(mu,mu_y./mu_y2,s), 0);\n end\n ft = 'js-array';\n\n \n case 'TVA'\n\n if ~isfield(param, 'L') \n \n threshold = 0.05;\n \n % compute the average correlation distance\n C_T = zeros(T); Toep = toeplitz(0:(T-1)); Tmax = round(0.5*T);\n\n for r = 1:R, C_T = C_T + abs(X(:,:,r)'*X(:,:,r)) / R; end\n cor = zeros(Tmax,1);\n for t = 1:Tmax, cor(t) = mean( vec(C_T(Toep == t-1)) ); end\n cor = normalize_data(cor, 0, 1);\n \n % select the window length conservatively\n param.L = min(4*find(cor>=threshold, 1, 'last' ), T);\n\n % visualize the correlation \n % figure; plot(0:(Tmax-1), cor, '-o', [1 1]*param.L, [0 1],\n % 'r-'); xlabel('correlation distance'); \n \n % param.L = round(T/4);\n end \n \n % Make sure that the length of the signal should be divisible by param.L \n if round(T/param.L) - (T/param.L) ~= 0\n % warning('Ideally the length of the signal should be divisible by param.L.') \n while (round(T/param.L) - (T/param.L) ~= 0) || (round(param.L/2) - (param.L/2) ~= 0)\n param.L = param.L + 1; \n end\n end\n \n if ~isfield(param, 'a'), param.a = round(param.L/2); end\n if ~isfield(param, 'M'), param.M = G.jtv.T; end\n if ~isfield(param,'win_type'), param.win_type = 'itersine'; end\n if ~isfield(G,'boundary'); param.boundary = 'periodic'; end\n \n \n % Compute a Gabor window\n w = gabwin(param.win_type, param.a, param.L);\n\n switch param.boundary\n \n case 'periodic'\n S = zeros(N, param.M, ceil(T/param.a), R);\n for r = 1:R\n % do a discrete gabore transform\n X_gabore = dgt(transpose(X(:,:,r)), w, param.a, param.M);\n S(:,:,:,r) = permute( X_gabore, [3,1,2]);\n end \n case 'reflecting'\n error('Sorry. Not implemented yet...')\n otherwise\n error('Unknown boundary condition');\n end\n \n if ~isfield(G,'lmax')\n G = gsp_estimate_lmax(G);\n \n warning(['GSP_PSD_ESTIMATION: 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 \n if ~isfield(param,'Nfilt'), param.Nfilt = 50; end\n if ~isfield(param,'Nrandom'), param.Nrandom = max(10,R); end\n if ~isfield(param,'g0')\n sigma = sqrt(2*G.lmax/param.Nfilt^2 * (param.Nfilt + 1));\n param.g0 = @(x) exp(-x.^2/sigma^2);\n end\n \n % Design the frame\n [ g , mu ] = gsp_design_translates(G, param.g0, param.Nfilt);\n %[ g , mu ] = gsp_design_itersine(G,Nfilt );\n \n % Estimate the energy of the window\n if gsp_check_fourier(G)\n mu_y2 = sum(abs(gsp_filter_evaluate(g, G.e)).^2, 1)';\n else\n w = randn(N, param.Nrandom);\n x_filt2 = gsp_vec2mat( gsp_filter_analysis(G,g,w,param), param.Nfilt);\n n2_x_filt2 = sum(abs(x_filt2).^2, 1);\n mu_y2 = reshape(mean(n2_x_filt2,3), [], 1);\n end\n \n psd = cell(1, param.M);\n \n% if gsp_check_fourier(G) && param.use_fast\n% warning('This may use a lot of ram!')\n% [N, T, Nt, Ns ] = size(S);\n% Nf = numel(g);\n% ShatG = gsp_gft(G,S);\n% filt_eval = gsp_filter_evaluate(g, G.e);\n% filt_eval = repmat(reshape(filt_eval,[N,1,1,1,Nf]), 1,T,Nt,Ns ,1);\n% % Perform the filtering\n% S_filt = gsp_igft(G, repmat(ShatG,[1,1,1,1,Nf]) .* filt_eval);\n% n2_S_filt = squeeze(mean(mean(sum(abs(S_filt).^2,1),3),4));\n% for ii = 1:param.M \n% \n% % Interpolate to obtain a nice filter.\n% psd{ii} = @(s) max(spline(mu,reshape(n2_S_filt(ii,:),[],1)./mu_y2,s), 0);\n% end\n% else\n for ii = 1:param.M\n \n % Perform the filtering\n x_filt = gsp_vec2mat( ...\n gsp_filter(G, g, reshape(S(:,ii,:,:),N,[]), param), ...\n param.Nfilt);\n \n % estimate the points\n n2_x_filt = sum(abs(x_filt).^2,1);\n mu_y = reshape(mean(n2_x_filt,3),[],1);\n \n % Interpolate to obtain a nice filter.\n psd{ii} = @(s) max(spline(mu,mu_y./mu_y2,s), 0);\n end\n% end\n\n \n ft = 'js-array';\n\n \n\n otherwise\n error('Unknown method')\nend\n\n\n\nend\n\n\nfunction [x] = normalize_data(x, xmin, xmax)\n%NORMALIZE_VECTOR Normalize x between xmin and xmax\n% x might be a scalar, vector, or matrix.\n\n%normalize to [0,1]\nx = (x - min(min(x))) ./ (max(max(x)) - min(min(x)));\n\nif exist('xmax', 'var') && exist('xmin', 'var')\n x = x .* (xmax - xmin) + xmin; \nend\n\nend\n\nfunction L = compute_default_L(X,T,R)\n% compute the correlation distance\nC_T = zeros(T);\nfor r = 1:R\n C_T = C_T + abs(X(:,:,r)'*X(:,:,r)) / R;\nend\nToep = toeplitz(0:(T-1));\nTmax = round(0.5*T);\ncor = zeros(Tmax,1);\nfor t = 1:Tmax\n cor(t) = mean( vec(C_T(Toep == t-1)) ); \nend\ncor = normalize_data(cor, 0, 1);\nthreshold = 0.05;\nL = min(2*find(cor>=threshold, 1, 'last'), T);\n\n%L = round(T/4);\n%figure; plot(0:(Tmax-1), cor, '-o', [1 1]*param.L, [0 1], 'r-');\n\nend", "meta": {"author": "epfl-lts2", "repo": "gspbox", "sha": "a7d9aac5e239f1bcb37a9bb09998cc161be2732f", "save_path": "github-repos/MATLAB/epfl-lts2-gspbox", "path": "github-repos/MATLAB/epfl-lts2-gspbox/gspbox-a7d9aac5e239f1bcb37a9bb09998cc161be2732f/stationarity/gsp_jtv_estimate_psd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.6548947155710234, "lm_q1q2_score": 0.5414091796450267}} {"text": "function [X,Y,vals,labI]=mp_azim(optn,varargin)\n% MP_AZIM Azimuthal projections\n% This function should not be used directly; instead it is\n% is accessed by various high-level functions named M_*.\n\n\n% Rich Pawlowicz (rich@ocgy.ubc.ca) 2/Apr/1997\n%\n% 13/5/97 - Added satellite perspective\n% 1/6/97 - Another stab at removing some /0 errors.\n% 10/8/00 - Rotation for projections?\n%\n% This software is provided \"as is\" without warranty of any kind. But\n% it's mine, so you can't sell it.\n%\n% Mathematical formulas for the projections and their inverses are taken from\n%\n% Snyder, John P., Map Projections used by the US Geological Survey, \n% Geol. Surv. Bull. 1532, 2nd Edition, USGPO, Washington D.C., 1983.\n%\n% These are azimuthal projections, best suited for circular areas. The\n% stereographic is commonly used for polar regions.\n% Stereographic - conformal\n% Orthographic - neither conformal nor equal-area, but looks like globe\n% with viewpoint at infinity.\n% Azimuthal Equal-area - equal area, but not conformal (by Lambert)\n% Azimuthal Equidistant - distance and direction from center are true \n% Gnomonic - all great circles are straight lines.\n% Satellite - a perspective view from a finite distance\n\nglobal MAP_PROJECTION MAP_VAR_LIST\n\nname={'Stereographic','Orthographic','Azimuthal Equal-area','Azimuthal Equidistant','Gnomonic','Satellite'};\n\npi180=pi/180;\n\n\nswitch optn\n\n case 'name'\n X=name;\n\n case {'usage','set'}\n X=char({[' ''' varargin{1} ''''],...\n ' <,''lon'',center_long>',...\n ' <,''lat'', center_lat>',...\n ' <,''rad'', ( degrees | [longitude latitude] ) | ''alt'', alt_frac >',...\n ' <,''rec'', ( ''on'' | ''off'' | ''circle'' )>',...\n\t ' <,''rot'', degrees CCW>'});\n\n case 'get'\n\n X=char([' Projection: ' MAP_PROJECTION.name ' (function: ' MAP_PROJECTION.routine ')'],...\n [' center longitude: ' num2str(MAP_VAR_LIST.ulong) ],...\n [' center latitude: ' num2str(MAP_VAR_LIST.ulat) ],...\n [' radius/altitude : ' num2str(MAP_VAR_LIST.uradius) ],...\n [' Rectangular border: ' MAP_VAR_LIST.rectbox ],...\n\t [' Rotation angle: ' num2str(MAP_VAR_LIST.rotang) ]);\n\n case 'initialize'\n\n MAP_VAR_LIST=[];\n MAP_PROJECTION.name=varargin{1};\n MAP_VAR_LIST.ulong=0;\n MAP_VAR_LIST.ulat=60;\n MAP_VAR_LIST.rectbox='circle';\n MAP_VAR_LIST.uradius=90;\n MAP_VAR_LIST.rotang=0;\n MAP_VAR_LIST.ellipsoid='normal';\n k=2;\n while k0 for points on the other side of the\n % globe whereas c does not!\n \n % Also, we clip on rho even if we later clip on X/Y because in some projections (e.g. the \n % orthographic) the X/Y locations wrap back. \n if ~strcmp(varargin{4},'off')\n vals = vals | cosc<=MAP_VAR_LIST.cosradius+eps*10;\n [rho,Az]=mu_util('clip',varargin{4},rho,MAP_VAR_LIST.rhomax,cosc=MAP_VAR_LIST.xlims(2)-eps*10 | ...\n Y<=MAP_VAR_LIST.ylims(1)+eps*10 | Y>=MAP_VAR_LIST.ylims(2)-eps*10;\n [X,Y]=mu_util('clip',varargin{4},X,MAP_VAR_LIST.xlims(1),XMAP_VAR_LIST.xlims(2) | isnan(X),Y);\n [Y,X]=mu_util('clip',varargin{4},Y,MAP_VAR_LIST.ylims(1),YMAP_VAR_LIST.ylims(2) | isnan(Y),X);\n end\n\n case 'xy2ll'\n\n\n rho=sqrt(varargin{1}.^2+varargin{2}.^2);\n Z=exp(i*(atan2(varargin{2},varargin{1})-MAP_VAR_LIST.rotang*pi180));\n V1=rho.*real(Z);\n V2=rho.*imag(Z);\n \n ir=rho==0; % To prevent /0 warnings when rho is 0\n rho(ir)=eps;\n\n switch MAP_PROJECTION.name\n case name(1)\n c=2*atan(rho/2);\n case name(2)\n c=asin(rho);\n c(abs(rho)>1.0)=NaN; % points outside the map\n case name(3)\n c=2*asin(rho/2);\n c(abs(rho)>2.0)=NaN; % points outside the map\n case name(4)\n c=rho;\n case name(5)\n c=atan(rho);\n case name(6)\n arg1=(MAP_VAR_LIST.uradius+1)./sqrt(1+(MAP_VAR_LIST.uradius./rho).^2);\n c=asin(arg1) - atan(rho/MAP_VAR_LIST.uradius);\n c(arg1>1.0)=NaN;\n end\n c(ir)=eps; % we offset this slightly so that the correct limit is achieved in the\n % division below:\n\n% Y=(asin(cos(c)*sin(MAP_VAR_LIST.rlat) + ...\n% cos(MAP_VAR_LIST.rlat)*sin(c).*varargin{2}./rho))/pi180;\n%\n% switch MAP_VAR_LIST.ulat,\n% case 90,\n% X=(MAP_VAR_LIST.rlong+atan2(varargin{1},-varargin{2}))/pi180;\n% case -90,\n% X=(MAP_VAR_LIST.rlong+atan2(varargin{1},varargin{2}))/pi180;\n% otherwise\n% X=(MAP_VAR_LIST.rlong+atan2( varargin{1}.*sin(c), ...\n% cos(MAP_VAR_LIST.rlat)*cos(c).*rho - sin(MAP_VAR_LIST.rlat)*varargin{2}.*sin(c) ) )/pi180; \n% end;\n\n % Can be problem if the argument is slightly larger than 1 - then the asin\n % returns a complex number.\n arg=cos(c)*sin(MAP_VAR_LIST.rlat) + ...\n cos(MAP_VAR_LIST.rlat)*sin(c).*V2./rho;\n arg=min(max(arg,-1),1);\n \n Y=(asin(arg))/pi180;\n\n switch MAP_VAR_LIST.ulat\n case 90\n X=(MAP_VAR_LIST.rlong+atan2(V1,-V2))/pi180;\n case -90\n X=(MAP_VAR_LIST.rlong+atan2(V1,V2))/pi180;\n otherwise\n X=(MAP_VAR_LIST.rlong+atan2( V1.*sin(c), ...\n cos(MAP_VAR_LIST.rlat)*cos(c).*rho - sin(MAP_VAR_LIST.rlat)*V2.*sin(c) ) )/pi180; \n end\n\n case 'xgrid'\n \n [X,Y,vals,labI]=mu_util('xgrid',MAP_VAR_LIST.longs,MAP_VAR_LIST.lats,varargin{1},31,varargin{2:3});\n\n case 'ygrid'\n\n [X,Y,vals,labI]=mu_util('ygrid',MAP_VAR_LIST.lats,MAP_VAR_LIST.longs,varargin{1},91,varargin{2:3});\n\n case 'box'\n\n [X,Y]=mu_util('box',31);\n\nend\n\n\n\n", "meta": {"author": "goGPS-Project", "repo": "goGPS_MATLAB", "sha": "30644df61d2459e3347ac5f3e31b71d9f69f4b01", "save_path": "github-repos/MATLAB/goGPS-Project-goGPS_MATLAB", "path": "github-repos/MATLAB/goGPS-Project-goGPS_MATLAB/goGPS_MATLAB-30644df61d2459e3347ac5f3e31b71d9f69f4b01/source/utility/thirdParty/m_map/private/mp_azim.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8596637612961505, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.5413944077700845}} {"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 [Jc,para,dJ,H] = PIRBFGSobjFctn(T,Rc,omega,m,beta,M,wRef,xc,wc)\n%\n% Objective Function for Parametric Image Registration with lBFGS\n%\n% computes J(wC) = D(T(Y(wc)),R) + S(wc), where\n%\n% yc = y(wc,xc) = trafo(wc,xc)\n% Tc = T(yc) = inter(T,omega,yc), \n% D(Tc,Rc) = distance(Tc,Rc,omega,m)\n% S(wc) = 0.5*(wc-wRef)'*M*(wc-wRef);\n% \n% Input:\n% T coefficients for template image\n% Rc sampled reference image\n% omega spatial domain\n% m number of discretization points\n% beta adding beta*I to approximation of Hessian \n% xc discretization of Omega\n% wc current parameters\n% Output:\n% Jc current function value J(wc)\n% para struct {Tc=T(y(wc)), Rc, omega, m, yc=y(wc,xc), Jc}, for plots\n% dJ gradient of J\n% H approximation to Hessian of J\n%==============================================================================\n\nfunction [Jc,para,dJ,H] = PIRBFGSobjFctn(T,Rc,omega,m,beta,M,wRef,xc,wc)\n\nif nargin == 0,\n\n help(mfilename)\n runMinimalExample;\n Jc = 'endMinimalExample';\n return\n\nelseif ~exist('wc','var') || isempty(wc),\n\n % if wc is not an input argument, reports status\n if nargout == 1, Jc = 'PIR'; return; end;\n\n % report current settings\n dimstr = @(m) sprintf('[%s]',sprintf(' %d',m));\n wc = trafo('w0');\n\n FAIRmessage('Parametric Image Registration with BFGS','-');\n fprintf('J(wc)=D(T(y(wc)),R) + (wc-wRef)''*M*(wc-wRef) != 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','length(wc)',num2str(length(wc)));\n fprintf('%-20s : %s\\n','REGULARIZATION',...\n sprintf('M is %d-by-%d, beta=%s',size(M),num2str(beta))); \n FAIRmessage('-');\n\n return;\nend;\n\n\n% do the work ------------------------------------------------------------\ndoDerivative = (nargout>2); % flag for necessity of derivatives\n\n% compute transformation, distance, and regularization and combine these\n[yc,dy] = trafo(wc,center(xc,m),'doDerivative',doDerivative);\n[Tc,dT] = imgModel(T,omega,yc,'doDerivative',doDerivative);\n[Dc,rc,dD] = distance(Tc,Rc,omega,m,'doDerivative',doDerivative);\n\n% add regularization\nif isempty(M) || (all(size(M)==1) && (M==0)),\n Sc = 0;\n dS = 0;\n M = 0;\nelse\n dS = (wc-wRef)'*M;\n Sc = 0.5*dS*(wc-wRef);\nend;\n\nJc = Dc + Sc; \n\n% collect variables for plots\npara = struct('Tc',Tc,'Rc',Rc,'omega',omega,'m',m,'yc',yc,'Jc',Jc);\n\nif ~doDerivative, return; end;\ndD = dD * dT; % multiply outer and inner derivatives\nif size(dD,2) == size(dy,1), % generic case, dy comes complete\n dJ = dD*dy + dS; \nelse % tricky case, dy comes sparse\n n = size(dy{1},1);\n dJ = reshape(dy{1}'*reshape(dD*dT,n,[]),1,[]) + dS;\n% dr = [dr(:,1:n)*dy{1},dr(:,n+1:2*n)*dy{1},dr(:,2*n+1:3*n)*dy{1}];\nend;\nif nargout<4, return; end;\n\n% approximation to Hessian\nif M == 0,\n H = 1;\nelse\n H = M;\nend;\n\n%------------------------------------------------------------------------------\n\nfunction runMinimalExample\n\nsetup2DhandData;\n\n% extract data of level 4\nlevel = 4; \nomega = ML{level}.omega; \nm = ML{level}.m; \n\nimgModel('reset','imgModel','linearInter'); \n[T,R] = imgModel('coefficients',ML{level}.T,ML{level}.R,omega);\nxc = getCellCenteredGrid(omega,m); \nRc = imgModel(R,omega,xc);\n\n% initialize distance measure\ndistance('reset','distance','SSD'); \n\n% initialize the transformation and a starting guess\n% trafo('reset','trafo','affine3Dsparse');\ntrafo('reset','trafo','affine2D');\nw0 = trafo('w0');\n\n%------------------------------------------------------------------------------\n% build objective function\n% note: T is data for template image\n% Rc is sampled reference image\n% optional Tikhonov-regularization is disabled by setting m = [], wRef = []\n% beta = 0, M = [], wRef = []: \n% disables additional regularization of Hessian approximation\nbeta = 0; M = []; wRef = [];\nfctn = @(wc) PIRobjFctn(T,Rc,omega,m,beta,M,wRef,xc,wc); \nfctn([]); % report status\ncheckDerivative(fctn,w0+rand(size(w0)));\n\n% setup plots and initialize\nFAIRplots('reset','mode','PIR-objective','omega',omega,'m',m,'fig',1,'plots',1);\nFAIRplots('init',struct('Tc',T,'Rc',R,'omega',omega,'m',m)); \n\n%% -- solve the optimization problem on one level\nOPTpara = FAIRcell2struct(optPara('lBFGS','solver',''));\n[wc,his] = lBFGS(fctn,w0,OPTpara{:}); \nreturn;\n\n% %------------------------------------------------------------------------------\n% %% finally: run the MultiLevel Non-Parametric Image Registration\n% [wc,his] = MLPIR(ML);\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/numerics/PIRBFGSobjFctn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.5413690674558859}} {"text": "function Y = as_l(tr,X)\n%\n% Solves linear systems with the real, symmetric, negative definite matrix A, \n% i.e., Y = inv(A)*X.\n%\n% The Cholesky factor of -A is provided as global data. This data must \n% be generated by calling 'as_l_i' before calling this routine!\n%\n% Calling sequence:\n%\n% Y = as_l(tr,X)\n%\n% Input:\n%\n% tr is not referenced;\n% X matrix of proper size.\n%\n% Output:\n%\n% Y the solution matrix. \n%\n% \n% LYAPACK 1.0 (Thilo Penzl, May 1999)\n\nif nargin~=2\n error('Wrong number of input arguments.');\nend\n\nglobal LP_U\n\nif ~length(LP_U)\n error('This routine needs global data which must be generated by calling ''as_l_i'' first.');\nend \n\nY = -LP_U\\(LP_U'\\X); % Note the minus!\n\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/21-lyapack/lyapack/usfs/as_l.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8311430645886583, "lm_q2_score": 0.6513548511303338, "lm_q1q2_score": 0.5413690671031549}} {"text": "function [C] = slerp(A,B,t)\n % SLERP Spherically interpolate between to unit vectors. If not unit then\n % this will normalize, slerp and then lerp magnitudes.\n %\n % [C] = slerp(A,B,t)\n %\n % Inputs:\n % A #A by 3 list of unit vectors\n % B #A by 3 list of unit vectors\n % t #t list of values between 0 and 1\n % Outputs:\n % C #A by 3 list of interpolated unit vectors\n %\n\n assert(size(A,1)==size(B,1),'#A != #B');\n if numel(t) == 1\n t = repmat(t,size(A,1),1);\n end\n assert(size(A,1)==numel(t),'#A != #T');\n\n % Original magnitudes\n Amag = sqrt(sum(A.^2,2));\n Bmag = sqrt(sum(B.^2,2));\n % normalize a and b and keep 0's\n A = bsxfun(@rdivide,A,Amag);\n B = bsxfun(@rdivide,B,Bmag);\n Omega = acos( sum(A.*B,2) );\n Omega(abs(Omega-pi)<1e-8) = pi-10*1e-8;\n sinOmega = sin(Omega);\n C = bsxfun(@times,A,sin((1-t).*Omega)./sinOmega) + ...\n bsxfun(@times,B,sin(t.*Omega)./sinOmega);\n % coincident\n co = abs(Omega)= 1 & ii(:) <= nb;\nif any(~good), warning 'FOV too small', end\n\nii = ii + [0:na-1]' * nb * ones(1,np);\n\n%np = sum(mask(:));\n%nc = np;\tjj = 1:np;\t\t% compact G\nnc = nx * ny;\tjj = find(mask(:))';\t% all-column G\njj = jj(ones(1,na),:);\n\nG = sparse(ii(good), jj(good), ones(sum(good),1), nb*na, nc);\n\nif 0\n%\tsubplot(121), im(embed(sum(G)', mask))\t\t% for compact\n\tsubplot(121), im(reshape(sum(G), nx, ny))\t% for all-column\n\tsubplot(122), im(reshape(sum(G'), nb, 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/Gnearest.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.541079311335515}} {"text": "classdef HaloOrbitApproximator < matlab.mixin.SetGet\n %HaloOrbitApproximator Summary of this class goes here\n % Detailed explanation goes here\n \n properties\n gm1(1,1) double\n gm2(1,1) double\n sma2(1,1) double\n radius1(1,1) double\n radius2(1,1) double\n AzUnscaled(1,1) double\n LPt(1,1) string = \"L1\"\n side(1,1) string = \"northern\"\n \n %diff corr options\n diffCorAlpha(1,1) double = 0.01;\n adjustIndEnum(1,1) HaloCoordAdjustEnum = HaloCoordAdjustEnum.Z;\n end\n \n properties(Access=public, Dependent)\n T2(1,1) double\n LU(1,1) double\n TU(1,1) double\n VU(1,1) double\n mu(1,1) double\n gL(1,1) double\n AzScaled(1,1) double\n end\n \n properties(Transient)\n corrSol\n manifoldLine(1,1)\n rVectCR3BP_Prim_Manifold(3,1) double\n vVectCR3BP_Prim_Manifold(3,1) double\n end\n \n events\n UpdateCalcWaitbar\n end\n \n methods\n function obj = HaloOrbitApproximator(gm1, gm2, sma2, radius1, radius2, AzUnscaled, LPt, side)\n obj.gm1 = gm1;\n obj.gm2 = gm2;\n obj.sma2 = sma2;\n obj.radius1 = radius1;\n obj.radius2 = radius2;\n obj.AzUnscaled = AzUnscaled;\n obj.LPt = string(upper(LPt));\n obj.side = string(lower(side));\n end\n \n function val = getT2(obj)\n val = computePeriod(obj.sma2, obj.gm1);\n end\n \n function val = get.LU(obj)\n val = obj.sma2;\n end\n \n function val = get.TU(obj)\n val = 1/sqrt((obj.gm1 + obj.gm2)/obj.sma2^3);\n end\n \n function val = get.VU(obj)\n val = obj.LU / obj.TU;\n end\n \n function val = get.mu(obj)\n val = obj.gm2/(obj.gm1 + obj.gm2);\n end\n \n function val = get.gL(obj)\n LP = HaloOrbitApproximator.lagrangePoints(obj.mu);\n \n switch obj.LPt\n case \"L1\"\n val = abs(1 - obj.mu - LP(1,1));\n case \"L2\"\n val = abs(LP(2,1) - 1 + obj.mu);\n otherwise\n error('Unknown Lagrange point.');\n end\n end\n \n function val = get.AzScaled(obj)\n val = (obj.AzUnscaled/obj.LU)/obj.gL;\n end\n \n function computeManifold(obj, tFrac, whichManifold, propDurDimensioned, hAx)\n sol = obj.corrSol;\n if(not(isempty(sol))) \n T = sol.x';\n Y = sol.y';\n \n stateF_Monodromy = reshape(Y(end,7:end),6,6);\n [V,D] = eig(stateF_Monodromy);\n eigvalues = diag(D,0);\n [~, IMaxEig] = max(real(eigvalues));\n [~, IMinEig] = min(real(eigvalues));\n \n Vs = V(:, IMinEig);\n Vu = V(:, IMaxEig);\n \n tFracActual = tFrac * (T(end) - T(1));\n Ynd_corr_Tfrac = deval(sol,tFracActual)';\n stateF_STM = reshape(Ynd_corr_Tfrac(1,7:end),6,6);\n \n Vs_i = stateF_STM * Vs;\n Vu_i = stateF_STM * Vu;\n \n epsilson = [0; 0; 0; 1E-4; 1E-4; 1E-4];\n Xi = Ynd_corr_Tfrac(1,1:6);\n XiS = Xi(:) + epsilson .* normVector(Vs_i);\n XiU = Xi(:) + epsilson .* normVector(Vu_i);\n \n propDur = propDurDimensioned / obj.TU;\n if(propDur > 0)\n switch whichManifold\n case HaloArriveDepartManifoldEnum.Arrive\n [T_manifold, Y_manifold] = obj.simulateOrbit(XiU(:)', propDur, false);\n \n case HaloArriveDepartManifoldEnum.Depart\n [T_manifold, Y_manifold] = obj.simulateOrbit(XiS(:)', -propDur, false);\n \n otherwise\n error('Unknown manifold type.');\n end\n \n else\n T_manifold = 0;\n Y_manifold = XiS(:)';\n end\n \n Y_manifold_Pos_Dim = Y_manifold(:,1:3) * obj.LU;\n if(isempty(obj.manifoldLine) || not(isgraphics(obj.manifoldLine, 'Line')))\n obj.manifoldLine = plot3(hAx, Y_manifold_Pos_Dim(:,1), Y_manifold_Pos_Dim(:,2), Y_manifold_Pos_Dim(:,3));\n obj.manifoldLine.DisplayName = 'Arrival/Departure Orbit';\n else\n obj.manifoldLine.XData = Y_manifold_Pos_Dim(:,1);\n obj.manifoldLine.YData = Y_manifold_Pos_Dim(:,2);\n obj.manifoldLine.ZData = Y_manifold_Pos_Dim(:,3);\n end\n \n primary = [-obj.mu, 0, 0];\n\n obj.rVectCR3BP_Prim_Manifold = (Y_manifold(1,1:3)-primary)' * obj.LU;\n obj.vVectCR3BP_Prim_Manifold = Y_manifold(1,4:6)' * obj.VU;\n end\n end\n \n function [rVectCR3BP_Prim, vVectCR3BP_Prim, period, approxAzAchieved, corrAzAchieved] = computeCorrectedInitialState(obj, hAx, dispPrimBody, dispSecBody)\n [~,~,~,~,~,~, statesND_approx, ~, Tapprox] = obj.getApproxHaloOrbitInitState(0);\n state0ND_diffCor = obj.differentialCorrector(statesND_approx(1,:), Tapprox);\n \n [Tnd_uncorr,Ynd_uncorr] = obj.simulateOrbit(statesND_approx(1,:), Tapprox, false);\n [Tnd_corr,Ynd_corr, ~,~,~, sol_corr] = obj.simulateOrbit(state0ND_diffCor, 2*Tapprox, false);\n obj.corrSol = sol_corr;\n \n approxAzAchieved = max(abs(statesND_approx(:,3))*obj.LU);\n corrAzAchieved = max(abs(Ynd_corr(:,3))*obj.LU);\n \n fprintf('Approx Az Achieved: %0.3f km\\n', approxAzAchieved);\n fprintf('Corrected Az Achieved: %0.3f km\\n', corrAzAchieved);\n \n if(isempty(hAx))\n hAx = axes(figure());\n else\n cla(hAx);\n end\n \n [hTrajApprox, hLPts] = obj.plotHaloOrbit(hAx, statesND_approx);\n [hTrajUnCorr, ~] = obj.plotHaloOrbit(hAx, Ynd_uncorr);\n [hTrajCorr, ~] = obj.plotHaloOrbit(hAx, Ynd_corr);\n \n legendObjs = [hTrajApprox, hTrajUnCorr, hTrajCorr];\n \n hTrajApprox.DisplayName = 'Approx Halo';\n hTrajUnCorr.DisplayName = 'Uncorrected Halo';\n hTrajCorr.DisplayName = 'Corrected Halo';\n hLPts.DisplayName = 'L Points';\n \n axis(hAx,'equal');\n hold(hAx,'on');\n \n %Plot secondary\n if(dispSecBody)\n dRad = obj.radius2;\n [X,Y,Z] = sphere(30);\n X = dRad*X + (1-obj.mu)*obj.LU;\n CData = getCDataForSphereWithColormap(Z, 'gray');\n legendObjs(end+1) = surf(hAx, X,dRad*Y,dRad*Z, 'CData',CData, 'BackFaceLighting','lit', 'FaceLighting','gouraud', 'EdgeLighting','gouraud', 'LineWidth',0.1, 'EdgeAlpha',0.1, 'DisplayName','Primary Body');\n end\n \n %Plot primary\n if(dispPrimBody)\n dRad = obj.radius1;\n [X,Y,Z] = sphere(30);\n X = dRad*X + (-obj.mu)*obj.LU;\n CData = getCDataForSphereWithColormap(Z, 'gray');\n legendObjs(end+1) = surf(hAx, X,dRad*Y,dRad*Z, 'CData',CData, 'BackFaceLighting','lit', 'FaceLighting','gouraud', 'EdgeLighting','gouraud', 'LineWidth',0.1, 'EdgeAlpha',0.1, 'DisplayName','Primary Body');\n end\n \n% {'Approx Halo', 'Uncorrected Halo', 'Corrected Halo', 'Primary Body', 'Secondary Body', 'L Points'};\n legend(legendObjs, 'Location','best');\n \n primary = [-obj.mu, 0, 0];\n \n rVectCR3BP_Prim = (Ynd_corr(1,1:3)-primary)' * obj.LU;\n vVectCR3BP_Prim = Ynd_corr(1,4:6)' * obj.VU;\n period = Tapprox * obj.TU;\n end\n \n function state0ND_approx = differentialCorrector(obj, state0ND_approx, Tapprox)\n MU = obj.mu;\n adjustInd = obj.adjustIndEnum.adjustInd;\n \n deltaXDot = Inf;\n deltaZDot = Inf;\n tol = 1E-12;\n while(abs(deltaXDot) > tol || ...\n abs(deltaZDot) > tol)\n % 1. Propagate the initial state vector using an ODE solver, such as ode45 in Matlab,\n % until the position in y is equal to zero again (T/2).\n [Tnd_uncorr,Ynd_uncorr, te,ye,ie] = obj.simulateOrbit(state0ND_approx, 10*Tapprox, true);\n stateF = Ynd_uncorr(end,:);\n \n % 2. Find the error in x and z velocities at T/2 (\u000ex_ and \u000ez_).\n deltaXDot = -stateF(4);\n deltaZDot = -stateF(6);\n deltaVect = [deltaXDot;\n deltaZDot];\n \n % 3. Calculate the change in the initial state required to reduce the error. It is only\n % necessary to change two of the initial states. Since all the zero terms are correct\n % those are left alone, and x and y_ are the only terms that will need to be altered.\n % The initial position in z will remain xed. \u000ex0 and \u000ey_0 are the values that will\n %be used to change the initial state.\n stateF_kinematic = stateF(1:6);\n stateF_STM = stateF(7:end);\n stateF_STM = reshape(stateF_STM,6,6);\n \n A = [stateF_STM(4,adjustInd), stateF_STM(4,5);\n stateF_STM(6,adjustInd), stateF_STM(6,5)];\n \n b = [stateF_STM(2,adjustInd), stateF_STM(2,5)];\n \n accelVec = HaloOrbitApproximator.cr3bpODE(Tnd_uncorr(end),stateF_kinematic,MU);\n accelVec = [accelVec(4); accelVec(6)];\n \n vy = stateF_kinematic(5);\n \n RHS = (A - (1/vy)*accelVec*b);\n deltas = RHS \\ deltaVect;\n deltas = deltas * obj.diffCorAlpha;\n \n % 4. Now, a new initial state is calculated by adding \u000ex0 and \u000ey_0 to the original\n %initial state as in Equation 3.59 and Equation 3.60.\n r0_new = state0ND_approx(adjustInd) + deltas(1);\n ydot0_new = state0ND_approx(5) + deltas(2);\n \n % 5. The new estimate for the initial state vector is now:\n state0ND_approx(adjustInd) = r0_new;\n state0ND_approx(5) = ydot0_new;\n \n curVal = log10(max(abs(deltaVect)));\n evtData = matlab.ui.eventdata.ValueChangedData(curVal, log10(tol));\n notify(obj, 'UpdateCalcWaitbar', evtData);\n end\n end\n \n function [x,y,z,xdot,ydot,zdot, statesND, statesDim, Tapprox] = getApproxHaloOrbitInitState(obj, phi0)\n [k, wp, nu, ...\n a21, a22, a23, a24, a31, a32, ...\n b21, b22, b31, b32, ...\n d21, d31, d32, Ax, Az] = obj.getRichardsonConstants();\n \n if(obj.side == \"northern\")\n m = 1;\n elseif(obj.side == \"southern\")\n m = 3;\n else\n error('Unknown side parameter');\n end\n \n Tapprox = (2*pi)/(wp*nu);\n tau = linspace(0,Tapprox,100);\n \n deltaM = 2 - m;\n tau1 = wp .* tau + phi0;\n \n g = obj.gL;\n \n x = g*(a21*Ax^2 + a22*Az - Ax*cos(tau1) + (a23*Ax^2 - a24*Az^2)*cos(2*tau1) + ...\n (a31*Ax^3 - a32*Ax*(Az^2)*cos(3*tau1)));\n \n y = g*(k*Ax*sin(tau1) + (b21*Ax^2 - b22*Az^2)*sin(2*tau1) + (b31*Ax^3 - b32*Ax*Az^2)*sin(3*tau1));\n \n z = g*(deltaM*Az*cos(tau1) + deltaM*d21*Ax*Az*(cos(2*tau1) - 3) + deltaM*(d32*Az*Ax^2 - d31*Az^3)*cos(3*tau1));\n \n xdot = g*(wp*nu*Ax*sin(tau1) - 2*wp*nu*(a23*Ax^2 - a24*Az^2)*sin(2*tau1) - 3*wp*nu*(a31*Ax^3 - a32*Ax*Az^2)*sin(3*tau1));\n \n ydot = g*(wp*nu*k*Ax*cos(tau1) + 2*wp*nu*(b21*Ax^2 - b22*Az^2)*cos(2*tau1) + 3*wp*nu*(b31*Ax^3 - b32*Ax*Az^2)*cos(3*tau1));\n \n zdot = g*(-wp*nu*deltaM*Az*sin(tau1) - 2*wp*nu*deltaM*d21*Ax*Az*sin(2*tau1) - 3*wp*nu*deltaM*(d32*Az*Ax^2 - d31*Az^2)*sin(3*tau1));\n \n LP = HaloOrbitApproximator.lagrangePoints(obj.mu);\n switch obj.LPt\n case \"L1\"\n deltaX = LP(1,1);\n case \"L2\"\n deltaX = LP(2,1);\n otherwise\n error('Unknown Lagrange point.');\n end\n \n x = x + deltaX; %need to move the x-coords back to the barycenter for integration in the synodic frame\n \n statesND = [x(:), y(:), z(:), xdot(:), ydot(:), zdot(:)];\n statesDim = [x(:)*obj.LU, ...\n y(:)*obj.LU, ...\n z(:)*obj.LU, ...\n xdot(:)*obj.VU, ...\n ydot(:)*obj.VU, ...\n zdot(:)*obj.VU];\n end\n \n function [hTraj, hLPts] = plotHaloOrbit(obj, hAx, statesND)\n LP = HaloOrbitApproximator.lagrangePoints(obj.mu);\n LP = LP * obj.LU;\n \n statesDim = statesND * obj.LU;\n \n hold(hAx, 'on');\n hTraj = plot3(hAx, statesDim(:,1), statesDim(:,2), statesDim(:,3));\n grid(hAx, 'off');\n grid(hAx, 'minor');\n % plot3(-obj.mu, 0, 0, 'ko');\n % hSecBody = plot3(hAx, (1-obj.mu)*obj.LU, 0, 0, 'ko');\n % hSecBody = obj.plotBody(hAx);\n hLPts = plot3(hAx, LP(1:2,1), LP(1:2,2), LP(1:2,3), 'bo');\n % axis(hAx,'equal');\n hold(hAx, 'off');\n xlabel(hAx,'X [km]');\n ylabel(hAx,'Y [km]');\n zlabel(hAx,'Z [km]');\n end\n \n function hCBodySurf = plotBody(obj, hAx)\n dRad = obj.radius2 / obj.LU;\n [X,Y,Z] = sphere(50);\n \n CData = getCDataForSphereWithColormap(Z, 'gray');\n hCBodySurf = surf(hAx, dRad*X,dRad*Y,dRad*Z, 'CData',CData, 'BackFaceLighting','lit', 'FaceLighting','gouraud', 'EdgeLighting','gouraud', 'LineWidth',0.1, 'EdgeAlpha',0.1);\n material(hCBodySurf,'dull');\n end\n \n function [T,Y, te,ye,ie, sol] = simulateOrbit(obj, y0, tf, stopOnYCrossing)\n tspan=[0 tf];\n \n if(numel(y0) == 6)\n y0 = [y0(:)', reshape(eye(6),1,36)];\n end\n \n odefun = @(t,y) HaloOrbitApproximator.stateTransMatrixODE(t,y,obj.mu);\n \n evtFcn = @(t,y) HaloOrbitApproximator.odeEvents(t,y, stopOnYCrossing);\n options=odeset('RelTol',1e-12,'AbsTol',1e-12,'Events',evtFcn);\n \n sol = ode113(odefun, tspan, y0, options);\n \n T = sol.x';\n Y = sol.y';\n te = sol.xe';\n ye = sol.ye';\n ie = sol.ie';\n end\n end\n \n methods(Access=private)\n function f = correctedHaloOrbitObjFun(obj, x, state0ND_approx, Tapprox)\n xNew = x(1);\n zNew = x(2);\n ydotNew = x(3);\n state0ND_approx([1,3,5]) = [xNew, zNew, ydotNew];\n \n [~,Ynd, ~,~,~] = obj.simulateOrbit(state0ND_approx, 10*Tapprox, true);\n aZAchieved = max(abs(Ynd(:,3))*obj.LU);\n \n f = abs((aZAchieved - obj.AzUnscaled)/abs(obj.AzUnscaled));\n end\n \n function [c, ceq] = correctedHaloOrbitNonlcon(obj, x, state0ND_approx, Tapprox)\n xNew = x(1);\n zNew = x(2);\n ydotNew = x(3);\n state0ND_approx([1,3,5]) = [xNew, zNew, ydotNew];\n \n [~,Ynd, ~,~,~] = obj.simulateOrbit(state0ND_approx, 10*Tapprox, true);\n \n c = [];\n ceq(1) = Ynd(end,2); %y=0\n ceq(2) = Ynd(end,3); %xdot = 0\n ceq(3) = Ynd(end,5); %zdot = 0\n end\n \n function [k, wp, nu, ...\n a21, a22, a23, a24, a31, a32, ...\n b21, b22, b31, b32, ...\n d21, d31, d32, Ax, Az] = getRichardsonConstants(obj)\n \n % c2 = (1/obj.gL^3) * (obj.mu + ((1-obj.mu)*obj.gL^3)/(1-obj.gL)^3);\n % c3 = (1/obj.gL^3) * (obj.mu - ((1-obj.mu)*obj.gL^4)/(1-obj.gL)^4);\n % c4 = (1/obj.gL^3) * (obj.mu + ((1-obj.mu)*obj.gL^5)/(1-obj.gL)^5);\n \n [~, c2, c3, c4] = obj.computeCCoeff();\n \n wp = sqrt(2 - c2 + ((9*c2^2 - 8*c2)/2)^(1/2));\n k = (wp^2 + 1 + 2*c2)/(2*wp);\n \n d1 = ((3*wp^2)/k) * (k*(6*wp^2-1)-2*wp);\n d2 = ((8*wp^2)/k) * (k*(11*wp^2-1)-2*wp);\n \n a21 = (3*c3*(k^2-2))/(4*(1+2*c2));\n a22 = (3*c3)/(4*(1+2*c2));\n a23 = ((-3*c3*wp)/(4*k*d1))*(3*(k^3)*wp - 6*k*(k-wp) + 4);\n a24 = ((-3*c3*wp)/(4*k*d1))*(2+3*k*wp);\n \n d21 = -c3/(2*wp^2);\n d31 = (3/(64*wp^2)) * (4*c3*a24 + c4);\n d32 = (3/(64*wp^2)) * (4*c3*(a23 - d21) + c4*(4+k^2));\n \n b21 = ((-3*c3*wp)/(2*d1))*(3*k*wp - 4);\n b22 = (3*c3*wp)/d1;\n b31 = (3/(8*d2)) * (8*wp*(3*c3*(k*b21 - 2*a23) - c4*(2+3*k^2)) + ...\n (9*wp^2 + 1 + 2*c2)*(4*c3*(k*a23-b21)+(k*c4*(4+k^2))));\n b32 = (1/d2) * (9*wp*(c3*(k*b22 + d21 - 2*a24) - c4) + ...\n (3/8)*(9*wp^2 + 1 + 2*c2)*(4*c3*(k*a24-b22)+(k*c4)));\n \n a31 = (-9*wp/(4*d2)) * (4*c3*(k*a23 - b21) + k*c4*(4+k^2)) + ...\n ((9*wp^2 + 1 - c2)/(2*d2))*(3*c3*(2*a23-k*b21)+(c4*(2+3*k^2)));\n a32 = (-1/d2) * ((9/4)*wp*(4*c3*(k*a24 - b22) + k*c4) + ...\n (3/2)*(9*wp^2 + 1 - c2)*(c3*(k*b22 + d21 - 2*a24) - c4));\n \n s1 = (1/(2*wp*(wp*(1+k^2)-2*k))) * ((3/2)*c3*(2*a21*(k^2-2) - a23*(k^2+2) - 2*k*b21) - ...\n (3/8)*c4*(3*k^4 - 8*k^2 + 8));\n s2 = (1/(2*wp*(wp*(1+k^2)-2*k))) * ((3/2)*c3*(2*a22*(k^2-2) + a24*(k^2+2) + 2*k*b22 + 5*d21) + ...\n (3/8)*c4*(12 - k^2));\n \n a1 = (-3/2)*c3*(2*a21 + a23 + 5*d21) - (3/8)*c4*(12-k^2);\n a2 = (3/2)*c3*(a24 - 2*a22) + (9/8)*c4;\n \n l1 = a1 + 2*(wp^2)*s1;\n l2 = a2 + 2*(wp^2)*s2;\n \n delta = wp^2 - c2;\n \n Az = obj.AzScaled;\n Ax = sqrt((-l2 * Az^2 - delta)/l1);\n \n nu = 1 + s1*Ax^2 + s2*Az^2;\n end\n \n function [c1, c2, c3, c4] = computeCCoeff(obj)\n g = obj.gL;\n m = obj.mu;\n \n switch obj.LPt\n case \"L1\"\n Ceqn = @(n) (1/((g^3)*(1-g^(n+1)))) * (m + ((-1)^n)*(1 - m)*g^(n+1));\n case \"L2\"\n Ceqn = @(n) (1/((g^3)*(1+g^(n+1)))) * (((-1)^n)*m + ((-1)^n)*(1 - m)*g^(n+1));\n otherwise\n error('Unknown Lagrange point.');\n end\n \n c = NaN(4,1);\n for(n=1:4)\n c(n) = Ceqn(n);\n end\n \n c1 = c(1);\n c2 = c(2);\n c3 = c(3);\n c4 = c(4);\n end\n end\n \n methods(Static)\n function [value,isterminal,direction] = odeEvents(~,y, stopOnYCrossing)\n value = y(2); %when y=0\n direction = 0;\n \n if(stopOnYCrossing)\n isterminal = 1;\n else\n isterminal = 0;\n end\n end\n \n function LP = lagrangePoints(mu)\n %For a given value of mu, this function computes the location\n %of all five libration points for the circular restricted three\n %body problem. It returns them as equilibrium points in R^3\n %space. Then the output is five points each with three components.\n %Each point is a column in a matrix with three rows. The first column is\n %L1, the second L2, and so on to the last which is L5.\n \n \n %Compute the location of the libration points\n l=1-mu;\n \n LP = zeros(5,3);\n \n %L1\n p_L1=[1, 2*(mu-l), l^2-4*l*mu+mu^2, 2*mu*l*(l-mu)+mu-l, mu^2*l^2+2*(l^2+mu^2), mu^3-l^3];\n L1roots=roots(p_L1);\n %initialize L1 for loop\n L1=0;\n for i=1:5\n if (L1roots(i) > -mu) && (L1roots(i) < l)\n L1=L1roots(i);\n end\n end\n LP(1,1) = L1;\n \n \n %L2\n p_L2=[1, 2*(mu-l), l^2-4*l*mu+mu^2, 2*mu*l*(l-mu)-(mu+l), mu^2*l^2+2*(l^2-mu^2), -(mu^3+l^3)];\n L2roots=roots(p_L2);\n %initialize L2 for loop\n L2=0;\n for i=1:5\n if (L2roots(i) > -mu) && (L2roots(i) > l)\n L2=L2roots(i);\n end\n end\n LP(2,1) = L2;\n \n \n %L3\n p_L3=[1, 2*(mu-l), l^2-4*mu*l+mu^2, 2*mu*l*(l-mu)+(l+mu), mu^2*l^2+2*(mu^2-l^2), l^3+mu^3];\n L3roots=roots(p_L3);\n %initialize L3 for loop\n L3=0;\n for i=1:5\n if L3roots(i) < -mu\n L3=L3roots(i);\n end\n end\n LP(3,1) = L3;\n \n \n %L4\n LP(4,1) = 0.5 - mu;\n LP(4,2) = sqrt(3)/2;\n \n \n %L5\n LP(5,1) = 0.5 - mu;\n LP(5,2) = -sqrt(3)/2;\n end\n \n function xdot = stateTransMatrixODE(t,xinput,mu)\n xstate = xinput(1:6);\n xstatedot = HaloOrbitApproximator.cr3bpODE(t,xstate,mu);\n \n PHI = reshape(xinput(7:6*6+6),6,6);\n \n x=xstate(1);\n y=xstate(2);\n z=xstate(3);\n \n x1 = -mu;\n x2 = 1-mu;\n \n r1 = sqrt((x-x1)^2 + y^2 + z^2);\n r2 = sqrt((x-x2)^2 + y^2 + z^2);\n \n OMEGA_XX = 1 + (1-mu)*((3*(x-x1)^2/r1^5) - 1/r1^3) ...\n + mu*((3*(x-x2)^2/r2^5) - 1/r2^3);\n \n OMEGA_YY = 1 + (1-mu)*((3*y^2/r1^5) - 1/r1^3) ...\n + mu*((3*y^2/r2^5) - 1/r2^3);\n \n OMEGA_XY = 3*(1-mu)*(x-x1)*y/r1^5 + 3*mu*(x-x2)*y/r2^5;\n \n OMEGA_XZ = 3*(1-mu)*z*(x-x1)/r1^5 + 3*mu*z*(x-x2)/r2^5;\n \n OMEGA_YZ = 3*(1-mu)*y*z/r1^5 + 3*mu*y*z/r2^5;\n \n OMEGA_ZZ = 3*(1-mu)*z^2/r1^5 - (1-mu)/r1^3 + 3*mu*z^2/r2^5 - mu/r2^3;\n \n A = [0 0 0 1 0 0;\n 0 0 0 0 1 0;\n 0 0 0 0 0 1;\n OMEGA_XX OMEGA_XY OMEGA_XZ 0 2 0;\n OMEGA_XY OMEGA_YY OMEGA_YZ -2 0 0;\n OMEGA_XZ OMEGA_YZ OMEGA_ZZ 0 0 0];\n PHIdot = A * PHI;\n \n xdot = [xstatedot;reshape(PHIdot,6*6,1)];\n end\n \n function ydot = cr3bpODE(t,y, mu)\n %Define the distances from 1 and 2 to the s/c\n r1 = sqrt((y(1)+mu)^2 + y(2)^2 + y(3)^2);\n r2 = sqrt((y(1)-(1-mu))^2 + y(2)^2 + y(3)^2);\n \n %the deriative functions here\n %velocities\n ydot(1) = y(4);\n ydot(2) = y(5);\n ydot(3) = y(6);\n \n %accelerations\n ydot(4) = 2*y(5) + y(1) - ((1-mu)*(y(1)+mu))/r1^3 - (mu*(y(1)-1+mu))/r2^3;\n ydot(5) = -2*y(4) + y(2) - ((1-mu)*y(2))/r1^3 - mu*y(2)/r2^3;\n ydot(6) = (-(1-mu)*y(3))/r1^3 - (mu*y(3))/r2^3;\n \n ydot=ydot';\n end\n end\nend\n\n\n% function [k, lambda, omega, ...\n% a21, a22, a23, a24, a31, a32, ...\n% b21, b22, b31, b32, ...\n% d21, d31, d32, Ax, Ay, Az] = getRichardsonConstants(obj)\n%\n% c2 = (1/obj.gL^3) * (obj.mu + ((1-obj.mu)*obj.gL^3)/(1-obj.gL)^3);\n% c3 = (1/obj.gL^3) * (obj.mu - ((1-obj.mu)*obj.gL^4)/(1-obj.gL)^4);\n% c4 = (1/obj.gL^3) * (obj.mu + ((1-obj.mu)*obj.gL^5)/(1-obj.gL)^5);\n%\n% p = [1, 0, (c2-2), 0, -(c2-1)*(1+2*c2)];\n% p_roots = roots(p);\n% lambda = real(p_roots(real(p_roots) > 0 & imag(p_roots) == 0));\n%\n% k = 2*lambda/(lambda^2 + 1 - c2);\n%\n% d1 = ((3*lambda^2)/k) * (k*(6*lambda^2-1)-2*lambda);\n% d2 = ((8*lambda^2)/k) * (k*(11*lambda^2-1)-2*lambda);\n%\n% a21 = (3*c3*(k^2-2))/(4*(1+2*c2));\n% a22 = (3*c3)/(4*(1+2*c2));\n% a23 = ((-3*c3*lambda)/(4*k*d1))*(3*(k^3)*lambda - 6*k*(k-lambda) + 4);\n% a24 = ((-3*c3*lambda)/(4*k*d1))*(2+3*k*lambda);\n%\n% d21 = -c3/(2*lambda^2);\n% d31 = (3/(64*lambda^2)) * (4*c3*a24 + c4);\n% d32 = (3/(64*lambda^2)) * (4*c3*(a23 - d21) + c4*(4+k^2));\n%\n% b21 = ((-3*c3*lambda)/(2*d1))*(3*k*lambda - 4);\n% b22 = (3*c3*lambda)/d1;\n% b31 = (3/(8*d2)) * (8*lambda*(3*c3*(k*b21 - 2*a23) - c4*(2+3*k^2)) + ...\n% (9*lambda^2 + 1 + 2*c2)*(4*c3*(k*a23-b21)+(k*c4*(4+k^2))));\n% b32 = (1/d2) * (9*lambda*(c3*(k*b22 + d21 - 2*a24) - c4) + ...\n% (3/8)*(9*lambda^2 + 1 + 2*c2)*(4*c3*(k*a24-b22)+(k*c4)));\n%\n% a31 = (-9*lambda/(4*d2)) * (4*c3*(k*a23 - b21) + k*c4*(4+k^2)) + ...\n% ((9*lambda^2 + 1 - c2)/(2*d2))*(3*c3*(2*a23-k*b21)+(c4*(2+3*k^2)));\n% a32 = (-1/d2) * ((9/4)*lambda*(4*c3*(k*a24 - b22) + k*c4) + ...\n% (3/2)*(9*lambda^2 + 1 - c2)*(c3*(k*b22 + d21 - 2*a24) - c4));\n%\n% s1 = (1/(2*lambda*(lambda*(1+k^2)-2*k))) * ((3/2)*c3*(2*a21*(k^2-2) - a23*(k^2+2) - 2*k*b21) - ...\n% (3/8)*c4*(3*k^4 - 8*k^2 + 8));\n% s2 = (1/(2*lambda*(lambda*(1+k^2)-2*k))) * ((3/2)*c3*(2*a22*(k^2-2) + a24*(k^2+2) + 2*k*b22 + 5*d21) + ...\n% (3/8)*c4*(12 - k^2));\n%\n% a1 = (-3/2)*c3*(2*a21 + a23 + 5*d21) - (3/8)*c4*(12-k^2);\n% a2 = (3/2)*c3*(a24 - 2*a22) + (9/8)*c4;\n%\n% l1 = a1 + 2*(lambda^2)*s1;\n% l2 = a2 + 2*(lambda^2)*s2;\n%\n% delta = lambda^2 - c2;\n%\n% Az = (obj.AzUnscaled/obj.LU)*obj.gL;\n% Ay = Az/obj.gL;\n% Ax = sqrt((-l2 * Az^2 - delta)/l1);\n%\n% omega = 1 + s1*Ax^2 + s2*Az^2;\n% end", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/ksptot_lvd/classes/Misc/astrodynamics/@HaloOrbitApproximator/HaloOrbitApproximator.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942377652497, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.5409990186043898}} {"text": "%this is an example, demonstrating a Radial Basis Function method of vector\n%acoustic tomography, using acoustic time-of-flight tomography as an\n%example.\n%This involves sending a sonic signal across a measurement area and timing\n%how long it takes to travel. A number of transducers are situated around\n%the measurement area to achieve this. Since the absolute sonic speed is\n%effected by temperature and wind speed, so is the time of flight. It is\n%possible to reconstruct the temperature and wind velocity from the\n%collection of time-of-flight data.\n%For more information, please see ref [1] or http://blog.nutaksas.com\n%\n%References\n%Wiens, Travis \"Sensing of Turbulent Flows Using Real-Time Acoustic \n%Tomography.\" X1Xth Biennial Conference of the NewZealand Acoustical \n%Society, 2008.\n\n% Copyright Travis Wiens 2008\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% If you would like to request that this software be licensed under a less\n% restrictive license (i.e. for commercial closed-source use) please\n% contact Travis at travis.mlfx@nutaksas.com\n\nN_xd=16;%number of transducers\nsig_dt=1e-6;%(s) std of error to add to dt\nN_r=25;%number of radial basis functions\n \nrecalculate=true;%set this to false to skip recalculating\nrbf_data_fname='gerris_rbf_data.mat';\nif recalculate\n \n fprintf('Calculating forward problem...')\n gerris_fname='simsave-5.0.gfs';\n %this data was calculated using the Gerris Flow Solver\n %(http:gfs.sourceforge.net), from the Karman vortex street example\n \n %since Gerris data is not regular, we'll fit a RBF to the temperature\n %and velocity data, then use that to calculate the flight times\n data=load(gerris_fname);%load [x y z u v]\n\n N_rbf_f=300;%number of rbf centers for forward problem\n X_scale=10;%rescale data\n Sc_G=[3 3]*X_scale;%scale factor for gerris\n OS_G=[1 0];%(m) offset for gerris data\n\n X_limits=[-2 2;-2 2]*X_scale;%limits for training\n Xc_fu=[X_limits(1,1)+diff(X_limits(1,:))*rand(1,N_rbf_f);X_limits(2,1)+diff(X_limits(2,:))*rand(1,N_rbf_f)]';%model rbf centres\n Xc_fv=[X_limits(1,1)+diff(X_limits(1,:))*rand(1,N_rbf_f);X_limits(2,1)+diff(X_limits(2,:))*rand(1,N_rbf_f)]';\n Xc_fT=[X_limits(1,1)+diff(X_limits(1,:))*rand(1,N_rbf_f);X_limits(2,1)+diff(X_limits(2,:))*rand(1,N_rbf_f)]';\n\n x_G=(data(:,1)-OS_G(1))*Sc_G(1);%x for Gerris data\n y_G=(data(:,2)-OS_G(2))*Sc_G(2);%x for Gerris data\n U_idx=find((x_G>X_limits(1,1))&(x_GX_limits(2,1))&(y_G fr + c1*t*gtd || ~isLegal(f_new)\n\n temp = t;\n if LS == 0 || ~isLegal(f_new)\n % Backtrack w/ fixed backtracking rate\n if debug\n fprintf('Fixed BT\\n');\n end\n t = 0.5*t;\n elseif LS == 2 && isLegal(g_new)\n % Backtracking w/ cubic interpolation w/ derivative\n if debug\n fprintf('Grad-Cubic BT\\n');\n end\n t = polyinterp([0 f gtd; t f_new g_new'*d],doPlot);\n elseif funEvals < 2 || ~isLegal(f_prev)\n % Backtracking w/ quadratic interpolation (no derivative at new point)\n if debug\n fprintf('Quad BT\\n');\n end\n t = polyinterp([0 f gtd; t f_new sqrt(-1)],doPlot);\n else%if LS == 1\n % Backtracking w/ cubic interpolation (no derivatives at new points)\n if debug\n fprintf('Cubic BT\\n');\n end\n t = polyinterp([0 f gtd; t f_new sqrt(-1); t_prev f_prev sqrt(-1)],doPlot);\n end\n\n % Adjust if change in t is too small/large\n\n if t < temp*1e-3\n if debug\n fprintf('Interpolated Value Too Small, Adjusting\\n');\n end\n t = temp*1e-3;\n elseif t > temp*0.6\n if debug\n fprintf('Interpolated Value Too Large, Adjusting\\n');\n end\n t = temp*0.6;\n end\n\n f_prev = f_new;\n t_prev = temp;\n if ~saveHessianComp && nargout == 6\n [f_new,g_new,H] = feval(funObj, x + t*d, varargin{:}); \n else\n [f_new,g_new] = feval(funObj, x + t*d, varargin{:}); \n end\n funEvals = funEvals+1;\n\n % Check whether step size has become too small\n if sum(abs(t*d)) <= tolX\n if debug\n fprintf('Backtracking Line Search Failed\\n');\n end\n t = 0;\n f_new = f;\n g_new = g;\n break;\n end\nend\n\n% Evaluate Hessian at new point\nif nargout == 6 && funEvals > 1 && saveHessianComp\n [f_new,g_new,H] = feval(funObj, x + t*d, varargin{:}); \n funEvals = funEvals+1;\nend\n\nx_new = x + t*d;\n\nend\n", "meta": {"author": "singaxiong", "repo": "SignalGraph", "sha": "e86d973556ae8796a05ee2adbd665f47c8525a21", "save_path": "github-repos/MATLAB/singaxiong-SignalGraph", "path": "github-repos/MATLAB/singaxiong-SignalGraph/SignalGraph-e86d973556ae8796a05ee2adbd665f47c8525a21/tools/minFunc/ArmijoBacktrack.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.695958331339634, "lm_q1q2_score": 0.5409683143336672}} {"text": "function [Pj closest] = P_r2j(Pr, Pj, closest)\n%P_R2J Change reference frame of projection matrices \n%\n% [Pk I] = P_r2j(Pr, Pj, closest)\n%\n% Tranforms the coordinate frame of a set of projection matrices such that\n% a reference projection matrix becomes the identity matrix eye(3, 4). Can\n% also select input matrices based on camera centre proximity to the\n% reference frame.\n%\n%IN:\n% Pr - 3x4 projection matrix of the reference frame.\n% Pj - 3x4xN array of input projection matrices.\n% closest - 1xP indices of matrices of Pj to output, once arranged in\n% order of proximity of camera centre to Pr. Default: 1:N.\n%\n%OUT:\n% Pk - 3x4x(min(N,P)) array of transformed projection matrices.\n% I - 1x(min(N,P)) indices of matrices of Pj that make up Pk, such\n% that Pk = T(Pj(:,:,I)), T() being the coordinate transformation.\n\n% $Id: P_r2j.m,v 1.2 2007/12/10 10:58:31 ojw Exp $\n\nif nargin > 2\n % Determine which Pj matrices are required based on distance of optical\n % centres from that of Pr.\n T = zeros(3, size(Pj, 3));\n for a = 1:size(Pj, 3)\n T(:,a) = -Pj(:,1:3,a) \\ Pj(:,4,a);\n end\n order = ojw_bsxfun(@minus, T, -Pr(:,1:3) \\ Pr(:,4));\n [T order] = sort(sum(order .^ 2));\n closest = order(closest);\n Pj = Pj(:,:,closest);\nend\n\n% Calculate Pj relative to Pr\n% Assume projection matrices make 0,0 the top left corner of the top left\n% pixel. Convert to Matlab form, i.e. 0.5,0.5 is the top left corner of the\n% top left pixel.\nT = [1 0 0.5; 0 1 0.5; 0 0 1];\nPr = inv([T * Pr; 0 0 0 1]);\nfor a = 1:size(Pj, 3)\n Pj(:,:,a) = T * Pj(:,:,a) * Pr;\nend\nreturn\n ", "meta": {"author": "jbhuang0604", "repo": "SelfExSR", "sha": "8f6dd8c1d20cb7e8792a7177b4f6fd677633f598", "save_path": "github-repos/MATLAB/jbhuang0604-SelfExSR", "path": "github-repos/MATLAB/jbhuang0604-SelfExSR/SelfExSR-8f6dd8c1d20cb7e8792a7177b4f6fd677633f598/external/imrender/ojw/P_r2j.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.6654105454764747, "lm_q1q2_score": 0.5408904853622987}} {"text": "function [xdot] = nldetect_anex1_v1_eom(t,x); % ,junk\n% Note: Include ',junk' before eom if this is to be called as an m-file,\n% i.e. [T,Y] = ode45('nldetec_anex1_v1_eom',...)\n% Exlude ',junk' if this is to be called as:\n% sol = ode45(@nldetect_anex1_v1_eom, ...)\n\n% State Space representation:\n% x = [q; qdot], xdot = [qdot; qdoubledot]\nglobal eom % more efficient to treat as global than to pass in every time.\n\n% Define nonlinear force:\nif strcmp(eom.NLType,'bang');\n % Bang (Contact Nonlinearity)\n % Assumes that stiffness of contacted parts is k4mult times higher.\n % Damping is also assumed higher by a factor of c4mult\n del4 = (x(eom.at_ns(1))-x(eom.at_ns(2)));\n if del4 < eom.delcont % No Contact Occurs\n Fnl = eom.kat*del4 ...\n + eom.cfactk*eom.kat*(x(eom.at_ns(1)+eom.Ntot)-x(eom.at_ns(2)+eom.Ntot)); % Add damping terms\n else % Contact Occurs\n Fnl = eom.kat*eom.k4mult*del4 ...\n + eom.c4mult*eom.cfactk*eom.kat*(x(eom.at_ns(1)+eom.Ntot)-x(eom.at_ns(2)+eom.Ntot)); % Add damping terms\n end\nelseif strcmp(eom.NLType,'cubic');\n % Cubic Spring\n del4 = (x(eom.at_ns(1))-x(eom.at_ns(2)));\n Fnl = eom.kat*del4*(1 + eom.katnl*del4^2) ...\n + eom.cfactk*eom.kat*(x(eom.at_ns(1)+eom.Ntot)-x(eom.at_ns(2)+eom.Ntot)); % Add damping terms\nelse\n error('NLType not recognized');\nend\n\n% Define input force - normalized to have unit area (energy) * Afnl\n% This is applied to mass 5 below\nif t <= eom.tfp\n fext = eom.Afnl*(2*eom.tfp/pi)*sin((pi/eom.tfp)*t);\nelse\n fext = 0;\nend\n\n% Equations of Motion\nxdot(eom.dnodes,1) = x(eom.vnodes);\nxdot(eom.vnodes,1) = (-eom.Ctot*x(eom.vnodes) - eom.Ktot*x(eom.dnodes) + fext*eom.fext_vec + ...\n Fnl*eom.fnl_vec)./diag(eom.Mtot);", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/24292-nonlinearity-detection-using-zeroed-early-time-ffts/nldt_bng_cub_v2_eom.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633915959134572, "lm_q2_score": 0.6261241702517975, "lm_q1q2_score": 0.5405903465936885}} {"text": " function [cost, fit, reg] = pwls_cost(xs, A, W, yi, R, mask)\n%function [cost, fit, reg] = pwls_cost(xs, A, W, yi, R, mask)\n%|\n%| compute PWLS cost for each column of xs\n%|\n%| in\n%|\txs\t[np niter]\titerates\n%|\tA\t[nd np]\t\tsystem matrix\n%|\tW\t[nd nd]\t\tdata weighting matrix, usually diag_sp(wi)\n%|\tyi\t[nd 1]\t\tdata\n%|\tR\t\t\tpenalty object (see Reg1.m or Robject.m)\n%|\t\t\t\twith penalty cost method: R.penal(R, x)\n%|\t\t\t\tor just *sparse* C matrix (quadratic only)\n%|\tmask\t[nx ny ...]\toptional mask, iff xs is [nx ny ... niter]\n%|\n%| out\n%|\tcost\t[niter 1]\tcost\n%|\tfit\t[niter 1]\t(y-A*x)'W(y-Ax)/2\n%|\treg\t[niter 1]\tR(x)\n%|\n%| Copyright 2002-2-12, Jeff Fessler, University of Michigan\n\nif nargin < 4, ir_usage, end\n\nif ~isvar('R'), R = []; end\n\nif isvar('mask') && ~isempty(mask)\n\txs = reshapee(xs, numel(mask), []);\t% [(*N) niter]\n\txs = xs(mask(:), :);\t\t\t% [np niter]\nend\n\nniter = size(xs,2);\nreg = zeros(niter,1);\n\nif isempty(R)\n\twarning 'empty R means no penalty'\n\nelseif issparse(R) || isa(R, 'Fatrix')\n\tC = R; % trick!\n\tif size(C,2) == size(C,1)\n\t\twarning 'square C is quite unusual!?'\n\tend\n\tfor ii=1:niter\n\t\treg(ii) = sum(abs(C * xs(:,ii)).^2)/2;\n\tend\n\nelseif isstruct(R) || isa(R, 'strum')\n\tfor ii=1:niter\n\t\treg(ii) = R.penal(R, xs(:,ii));\n\tend\n\nelse\n\tkeyboard\n\terror 'bad R'\nend\n\nfit = zeros(niter,1);\nfor ii=1:niter\n\tresid = yi - A * xs(:,ii); % predicted measurements\n\tfit(ii) = resid' * (W * resid) / 2;\nend\n\ncost = fit + reg;\ncost = reale(cost, 'warn'); % trick: x'*W*x is not always real for complex values\n\nif ~nargout\n\tpr fit\n\tpr reg\n\tpr cost\nend\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/wls/pwls_cost.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5405002081984477}} {"text": "%SerialLink.coriolis Coriolis matrix\n%\n% C = R.coriolis(Q, QD) is the Coriolis/centripetal matrix (NxN) for\n% the robot in configuration Q and velocity QD, where N is the number of\n% joints. The product C*QD is the vector of joint force/torque due to velocity\n% coupling. The diagonal elements are due to centripetal effects and the \n% off-diagonal elements are due to Coriolis effects. This matrix is also \n% known as the velocity coupling matrix, since it describes the disturbance forces\n% on any joint due to velocity of all other joints.\n%\n% If Q and QD are matrices (KxN), each row is interpretted as a joint state \n% vector, and the result (NxNxK) is a 3d-matrix where each plane corresponds\n% to a row of Q and QD.\n%\n% C = R.coriolis( QQD) as above but the matrix QQD (1x2N) is [Q QD].\n%\n% Notes::\n% - Joint viscous friction is also a joint force proportional to velocity but it is\n% eliminated in the computation of this value.\n% - Computationally slow, involves N^2/2 invocations of RNE.\n%\n% See also SerialLink.rne.\n\n\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 C = coriolis(robot, q, qd)\n\n n = robot.n;\n\n if nargin == 2\n % coriolis( [q qd] )\n if numcols(q) ~= 2*n\n error('RTB:coriolis:badarg', 'arg must have %d columns', 2*n);\n end\n qd = q(:,n+1:end);\n q = q(:,1:n);\n else\n if numcols(q) ~= n\n error('RTB:coriolis:badarg', 'Cq must have %d columns', n);\n end\n if numcols(qd) ~= n\n error('RTB:coriolis:badarg', 'qd must have %d columns', n);\n end\n end\n\n % we need to create a clone robot with no friciton, since friction\n % is also proportional to joint velocity\n robot2 = robot.nofriction('all');\n\n if numrows(q) > 1\n if numrows(q) ~= numrows(qd)\n error('RTB:coriolis:badarg', 'for trajectory q and qd must have same number of rows');\n end\n C = [];\n for i=1:numrows(q)\n C = cat(3, C, robot2.coriolis(q(i,:), qd(i,:)));\n end\n return\n end\n\n N = robot2.n;\n \n if isa(q, 'sym')\n C(N,N) = sym();\n Csq(N,N) = sym();\n else\n \n C = zeros(N,N);\n Csq = zeros(N,N);\n end\n\n\n % find the torques that depend on a single finite joint speed,\n % these are due to the squared (centripetal) terms\n %\n % set QD = [1 0 0 ...] then resulting torque is due to qd_1^2\n for j=1:N\n QD = zeros(1,N);\n QD(j) = 1;\n tau = robot2.rne(q, QD, zeros(size(q)), [0 0 0]');\n Csq(:,j) = Csq(:,j) + tau.';\n end\n\n % find the torques that depend on a pair of finite joint speeds,\n % these are due to the product (Coridolis) terms\n % set QD = [1 1 0 ...] then resulting torque is due to \n % qd_1 qd_2 + qd_1^2 + qd_2^2\n for j=1:N\n for k=j+1:N\n % find a product term qd_j * qd_k\n QD = zeros(1,N);\n QD(j) = 1;\n QD(k) = 1;\n tau = robot2.rne(q, QD, zeros(size(q)), [0 0 0]');\n C(:,k) = C(:,k) + (tau.' - Csq(:,k) - Csq(:,j)) * qd(j)/2;\n C(:,j) = C(:,j) + (tau.' - Csq(:,k) - Csq(:,j)) * qd(k)/2;\n\n end\n end\n\n C = C + Csq * diag(qd);\n \n if isa(q, 'sym')\n C = simplify(C);\n end\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/@SerialLink/coriolis.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.78793120560257, "lm_q2_score": 0.6859494550081926, "lm_q1q2_score": 0.540480981067031}} {"text": "function f = constructorTurbo(f, op, pref)\n% F = CONSTRUCTORTURBO(F, OP, PREF) takes the CHEBTECH F that was constructed\n% from the function handle OP using the preferences in PREF and tries to use\n% contour integrals to compute some additional higher-order coefficients to\n% high accuracy. These coefficients are returned in the appropriate\n% positions in F.COEFFS.\n%\n% This function is only meant to be called by the CHEBTECH constructor.\n%\n% References:\n%\n% [1] Bornemann, F. Accuracy and stability of computing high-order\n% derivatives of analytic functions by Cauchy integrals. Found.\n% Comput. Math. 11 (2011), pp. 1-63.\n%\n% [2] Wang, H. and Huybrechs, D. Fast and accurate computation of Jacobi\n% expansion coefficients of analytic functions. Technical Report\n% TW-645, K.U. Leuven, 2015.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\n% How many coefficients do we want to compute?\nif ( ~isnan(pref.fixedLength) )\n n = pref.fixedLength;\nelse\n n = 2*length(f);\nend\n\n% Pick an ellipse over which to integrate.\nrhoCheb = exp(abs(log(eps())) / length(f));\nrho = rhoCheb^(2/3);\n\n% Do the contour integrals.\nc = chebCoeffsTurbo(op, rho, n);\n\n% Assign the new coefficients.\nif ( isreal(f) )\n f.coeffs = real(c);\nelseif ( isreal(1i*f) )\n f.coeffs = imag(c);\nelse\n f.coeffs = c;\nend\n\nend\n\nfunction c = chebCoeffsTurbo(f, rho, n)\n%CHEBCOEFFSTURBO Compute Chebyshev coefficients using contour integrals.\n% C = CHEBCOEFFSTURBO(F, RHO, N) computes the first N Chebyshev coefficients\n% of the holomorphic function represented by the function handle F using\n% Cauchy integrals over the Bernstein ellipse of parameter RHO. F must be\n% vectorized and able to accept complex inputs.\n\nK = 4*n; % Number of quadrature nodes.\ng = @(z) f((rho*z + 1./(rho*z))/2); % Remap ellipse to unit circle.\nz = exp(2*pi*1i*(0:1:(K - 1)).'/K); % Roots of unity.\n\n% Compute integrals with trap. rule and rescale to get coefficients.\nc = bsxfun(@rdivide, fft(g(z))/K, rho.^(0:1:(K - 1)).');\nc = [c(1,:) ; 2*c(2:n,:)];\n\nend\n", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/@chebtech/constructorTurbo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.78793120560257, "lm_q2_score": 0.6859494550081926, "lm_q1q2_score": 0.540480981067031}} {"text": "function [ x, w ] = rule01 ( n )\n\n%*****************************************************************************80\n%\n%% RULE01 returns the rule of degree 1.\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.00000000000000000 ];\n ys = [ ...\n 0.00000000000000000 ];\n ws = [ ...\n 0.2828427124746189E+01 ];\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/rule01.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.6859494614282922, "lm_q1q2_score": 0.5404809792937939}} {"text": "function [sos,P] = sospolymatrixvar(sos,ZSym,n,matrixstr)\n% SOSMATRIXVAR --- Declare a polynomial matrix variable P in the sos program\n% SOS of\n%\n% [SOSP,P] = sosmatrixvar(SOSP,ZSym,n,matrixstr)\n%\n% SOSP is the sum of squares program.\n% P is the new polynomial matrix.\n% n is the dimension of the matrix P: n(1) x n(2)\n% ZSym is the vector of monomials contained in VAR. Decision\n% variables corresponding to those monomials will be assigned\n% automatically by SOSPOLYVAR.\n% matrixstr is a char string with the option 'symmetric' when required\n\n% This file is part of SOSTOOLS - Sum of Squares Toolbox ver 3.00.\n%\n% Copyright (C)2002, 2004, 2013 A. Papachristodoulou (1), J. Anderson (1),\n% G. Valmorbida (1), S. Prajna (2),\n% P. Seiler (3), P. A. Parrilo (4)\n% (1) Department of Engineering Science, University of Oxford, Oxford, U.K.\n% (2) Control and Dynamical Systems - California Institute of Technology,\n% Pasadena, CA 91125, USA.\n% (3) Aerospace and Engineering Mechanics Department, University of\n% Minnesota, Minneapolis, MN 55455-0153, USA.\n% (4) Laboratory for Information and Decision Systems, M.I.T.,\n% Massachusetts, MA 02139-4307\n%\n% Send bug reports and feedback to: sostools@cds.caltech.edu\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n\n\n% JA&GV - 6/13/2013\n\n\n\n% Original Code\nif nargin == 4\n if matrixstr=='symmetric'\n if n(1)==n(2)\n if isfield(sos,'symvartable')\n P = sym(zeros(n(1),n(2)));\n else\n % Code for multipoly: PJS 9/9/2013\n P = polynomial(zeros(n(1),n(2)));\n end\n for i = 1:n(1)\n for j = i:n(1)\n [sos,var] = sospolyvar(sos,ZSym);\n P(i,j) = var;\n P(j,i) = var;\n clear var;\n end\n end\n else\n disp(['''symmetric''' ' option used, matrix must be square.']);\n P = [];\n return\n end\n else\n disp(['Matrix structure ' matrixstr ' is not defined.' ]);\n P = [];\n return\n \n end\nelse\n if isfield(sos,'symvartable')\n P = sym(zeros(n(1),n(2)));\n else\n % Code for multipoly: PJS 9/9/2013\n P = polynomial(zeros(n(1),n(2)));\n end\n for i = 1:n(1)\n for j = 1:n(2)\n [sos,var] = sospolyvar(sos,ZSym);\n P(i,j) = var;\n clear var;\n end\n end\n \nend", "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/sospolymatrixvar.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.5404809691766003}} {"text": "function [ a, ipvt, rcond ] = zgeco ( a, lda, n )\n\n%*****************************************************************************80\n%\n%% ZGECO factors a complex matrix and estimates its condition.\n%\n% Discussion:\n%\n% If RCOND is not needed, ZGEFA is slightly faster.\n%\n% To solve A*X = B, follow ZGECO by ZGESL.\n%\n% To compute inverse(A)*C, follow ZGECO by ZGESL.\n%\n% To compute determinant(A), follow ZGECO by ZGEDI.\n%\n% To compute inverse(A), follow ZGECO by ZGEDI.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 13 May 2007\n%\n% Author:\n%\n% MATLAB version by John Burkardt\n%\n% Reference:\n%\n% Jack Dongarra, Jim Bunch, Cleve Moler, Pete Stewart,\n% LINPACK User's Guide,\n% SIAM, 1979,\n% ISBN13: 978-0-898711-72-1,\n% LC: QA214.L56.\n%\n% Parameters:\n%\n% Input, complexA(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.\n%\n% Output, complex A(LDA,N), an upper triangular matrix and the multipliers\n% which were used to obtain it. The factorization can be written A = L*U\n% where L is a product of permutation and unit lower triangular matrices\n% and U is upper triangular.\n%\n% Output, integer IPVT(N), the pivot indices.\n%\n% Output, real RCOND, an estimate of the reciprocal condition of A.\n% For the system A*X = B, relative perturbations in A and B of size\n% EPSILON may cause relative perturbations in X of size (EPSILON/RCOND).\n% If RCOND is so small that the logical expression\n% 1.0 + RCOND == 1.0\n% is true, then A may be singular to working precision. In particular,\n% RCOND is zero if exact singularity is detected or the estimate\n% underflows.\n%\n\n%\n% Compute the 1-norm of A.\n%\n anorm = 0.0;\n for j = 1 : n\n anorm = max ( anorm, dzasum ( n, a(1:n,j), 1 ) );\n end\n%\n% Factor.\n%\n [ a, ipvt, info ] = zgefa ( a, lda, n );\n%\n% RCOND = 1/(norm(A)*(estimate of norm(inverse(A)))).\n%\n% Estimate = norm(Z)/norm(Y) where A*Z = Y and hermitian(A)*Y = E.\n%\n% Hermitian(A) is the conjugate transpose of A.\n%\n% The components of E are chosen to cause maximum local\n% growth in the elements of W where hermitian(U)*W = E.\n%\n% The vectors are frequently rescaled to avoid overflow.\n%\n% Solve hermitian(U)*W = E.\n%\n ek = 1.0;\n z(1:n) = 0.0;\n\n for k = 1 : n\n\n if ( zabs1 ( z(k) ) ~= 0.0 )\n ek = zsign1 ( ek, -z(k) );\n end\n\n if ( zabs1 ( a(k,k) ) < zabs1 ( ek - z(k) ) )\n s = zabs1 ( a(k,k) ) / zabs1 ( ek - z(k) );\n z(1:n) = z(1:n) * s;\n ek = s * ek;\n end\n\n wk = ek - z(k);\n wkm = -ek - z(k);\n s = zabs1 ( wk );\n sm = zabs1 ( wkm );\n\n if ( zabs1 ( a(k,k) ) ~= 0.0 )\n wk = wk / conj ( a(k,k) );\n wkm = wkm / conj ( a(k,k) );\n else\n wk = 1.0;\n wkm =1.0;\n end\n\n for j = k+1 : n\n sm = sm + zabs1 ( z(j) + wkm * conj ( a(k,j) ) );\n z(j) = z(j) + wk * conj ( a(k,j) );\n s = s + zabs1 ( 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 * conj ( a(k,k+1:n) );\n end\n\n z(k) = wk;\n\n end\n\n s = 1.0 / dzasum ( n, z, 1 );\n z(1:n) = z(1:n) * s;\n%\n% Solve hermitian(L) * Y = W.\n%\n for k = n : -1 : 1\n\n if ( k < n )\n z(k) = z(k) + z(k+1:n) * conj ( a(k+1:n,k) );\n end\n\n if ( 1.0 < zabs1 ( z(k) ) )\n s = 1.0 / zabs1 ( z(k) );\n z(1:n) = z(1:n) * s;\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 s = 1.0 / dzasum ( n, z, 1 );\n z(1:n) = z(1:n) * s;\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 if ( k < n )\n z(k+1:n) = z(k+1:n) + t * transpose ( a(k+1:n,k) );\n end\n\n if ( 1.0 < zabs1 ( z(k) ) )\n s = 1.0 / zabs1 ( z(k) );\n z(1:n) = z(1:n) * s;\n ynorm = s * ynorm;\n end\n\n end\n\n s = 1.0 / dzasum ( n, z, 1 );\n z(1:n) = z(1:n) * s;\n ynorm = s * ynorm;\n%\n% Solve U * Z = V.\n%\n for k = n : -1 : 1\n\n if ( zabs1 ( a(k,k) ) < zabs1 ( z(k) ) )\n s = zabs1 ( a(k,k) ) / zabs1 ( z(k) );\n z(1:n) = z(1:n) * s;\n ynorm = s * ynorm;\n end\n\n if ( zabs1 ( a(k,k) ) ~= 0.0 )\n z(k) = z(k) / a(k,k);\n else\n z(k) = 1.0;\n end\n\n t = -z(k);\n z(1:k-1) = z(1:k-1) + t * transpose ( a(1:k-1,k) );\n\n end\n%\n% Make ZNORM = 1.\n%\n s = 1.0 / dzasum ( n, z, 1 );\n z(1:n) = z(1:n) * s;\n ynorm = s * ynorm;\n\n if ( anorm ~= 0.0 )\n rcond = ynorm / anorm;\n else\n rcond = 0.0;\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/linpack_z/zgeco.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5403940282224315}} {"text": "% QUATERNION CONJUGATE\nfunction [qCon] = qConjugate(q)\n% This function defines the conjugate of the given quaternion.\n% Associated block:\n% \"Quaternion Conjugate\"\nqCon = zeros(4,1);\nqCon(2) = -q(2);\nqCon(3) = -q(3);\nqCon(4) = -q(4);\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/qConjugate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7956580806813576, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5403940202255543}} {"text": "function [HF,psi,x,y] = feed_dist(F,z,TF,PF)\n\nparameters_dist\nc = length(z); % c includes all species\noptions = optimset('Display','iter','Diagnostics','on','Algorithm','interior-point');\n\n% Bubble point calculation\nxB = z'; % Bubble point requirement (together with PF)\nyB = xB; % Initial guess\nTB = TF; % Initial guess\nx0 = [yB; TB];\nr = fmincon('1',x0,[],[],[],[],[],[],@gB,options,xB,PF,c);\nyB = r(1:c);\nTB = r(end);\n\n% Dew point calculation\nyD = z'; % Dew point requirement (together with PF)\nxD = yD; % Initial guess\nTD = TF; % Initial guess\nx0 = [xD; TD];\nr = fmincon('1',x0,[],[],[],[],[],[],@gD,options,yD,PF,c);\nxD = r(1:c);\nTD = r(end);\n\nif TF <= TB\n psi = 0;\n x = xB;\n y = yB;\n [~,~,~,~,~,HF,~,~] = prsrk(x,PF*1e5,TF+273.15,pc,Tc,w,k,cpig,DHf,DGf,'L',Thermo);\nelseif TF >= TD\n psi = 1;\n x = xD;\n y = yD;\n [~,~,~,~,~,HF,~,~] = prsrk(y,PF*1e5,TF+273.15,pc,Tc,w,k,cpig,DHf,DGf,'V',Thermo);\nelse\n % Two-phase calculation\n x = z'; % Initial guess\n y = x; % Initial guess\n V = 0.5*F; % Initial guess\n L = V; % Initial guess\n x0 = [x; y; V; L]; d = [F; TF; PF; z'];\n r = fmincon('1',x0,[],[],[],[],[],[],@gF,options,d,c);\n x = r(1:c); y = r(c+1:2*c);\n [~,~,~,~,~,HL,~,~] = prsrk(x,PF*1e5,TF+273.15,pc,Tc,w,k,cpig,DHf,DGf,'L',Thermo);\n [~,~,~,~,~,HV,~,~] = prsrk(y,PF*1e5,TF+273.15,pc,Tc,w,k,cpig,DHf,DGf,'V',Thermo);\n V = r(end-1); L = r(end);\n HF = 1/F*(HV*V + HL*L); psi = r(end-1)/F;\nend\n\n\nfunction [c,ceq] = gB(x0,x,PF,c)\n\nparameters_dist\ny = x0(1:c);\nT = x0(end);\n\n[~,~,phiL,~,~,~,~,~] = prsrk(x,PF*1e5,T+273.15,pc,Tc,w,k,cpig,DHf,DGf,'L',Thermo);\n[~,~,phiV,~,~,~,~,~] = prsrk(y,PF*1e5,T+273.15,pc,Tc,w,k,cpig,DHf,DGf,'V',Thermo);\nK = phiL./phiV;\n\nceq = [y - K.*x; sum(y) - 1];\nc = [];\n\n\nfunction [c,ceq] = gD(x0,y,PF,c)\n\nparameters_dist\nx = x0(1:c);\nT = x0(end);\n\n[~,~,phiL,~,~,~,~,~] = prsrk(x,PF*1e5,T+273.15,pc,Tc,w,k,cpig,DHf,DGf,'L',Thermo);\n[~,~,phiV,~,~,~,~,~] = prsrk(y,PF*1e5,T+273.15,pc,Tc,w,k,cpig,DHf,DGf,'V',Thermo);\nK = phiL./phiV;\n\nceq = [y - K.*x; sum(x) - 1];\nc = [];\n\n\nfunction [c,ceq] = gF(x0,d,c)\n\nparameters_dist\nx = x0(1:c);\ny = x0(c+1:2*c);\nV = x0(end-1);\nL = x0(end);\n\nF = d(1);\nTF = d(2);\nPF = d(3);\nz = d(4:end);\n\n[~,~,phiL,~,~,~,~,~] = prsrk(x,PF*1e5,TF+273.15,pc,Tc,w,k,cpig,DHf,DGf,'L',Thermo);\n[~,~,phiV,~,~,~,~,~] = prsrk(y,PF*1e5,TF+273.15,pc,Tc,w,k,cpig,DHf,DGf,'V',Thermo);\nK = phiL./phiV;\n\nceq = [y - K.*x; F*z - V*y - L*x; sum(x) - 1; sum(y) - 1];\nc = [];\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/27850-mixture-property-calculations-using-pr-rk-and-srk-eos/feed_dist.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898203834278, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.5403623590550107}} {"text": "function c = ttv(a,v,dims)\n%TTV Tensor times vector for ktensor.\n%\n% Y = TTV(X,A,N) computes the product of Kruskal tensor X with a\n% (column) vector A. The integer N specifies the dimension in X\n% along which A is multiplied. If size(A) = [I,1], then X must have\n% size(X,N) = I. Note that ndims(Y) = ndims(X) - 1 because the N-th\n% dimension is removed.\n%\n% Y = TTV(X,{A1,A2,...}) computes the product of tensor X with a\n% sequence of vectors in the cell array. The products are computed\n% sequentially along all dimensions (or modes) of X. The cell array\n% contains ndims(X) vectors.\n%\n% Y = TTV(X,{A1,A2,...},DIMS) computes the sequence tensor-vector\n% products along the dimensions specified by DIMS.\n%\n% See also TENSOR/TTV, KTENSOR, KTENSOR/TTM.\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%%% ERROR CHECKING %%%\n%%%%%%%%%%%%%%%%%%%%%%\n\n% Check the number of arguments\nif (nargin < 2)\n error('TTV requires at least two arguments.');\nend\n\n% Check for 3rd argument\nif ~exist('dims','var')\n dims = [];\nend\n\n% Check that 2nd argument is cell array. If not, recall with v as a\n% cell array with one element.\nif ~iscell(v)\n c = ttv(a,{v},dims);\n return;\nend\n\n% Get sorted dims and index for multiplicands\n[dims,vidx] = tt_dimscheck(dims,ndims(a),numel(v)); \n\n% Check that each multiplicand is the right size.\nfor i = 1:numel(dims)\n if ~isequal(size(v{vidx(i)}),[size(a,dims(i)) 1])\n error('Multiplicand is wrong size');\n end\nend\n\n% Figure out which dimensions will be left when we're done\nremdims = setdiff(1:ndims(a),dims);\n\n% Collapse dimensions that are being multiplied out\nnewlambda = a.lambda;\nfor i = 1:numel(dims) \n newlambda = newlambda .* ( a.u{dims(i)}' * v{vidx(i)} );\nend\n\n% Create final result\nif isempty(remdims)\n c = sum(newlambda);\nelse\n c = ktensor(newlambda,a.u{remdims});\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/@ktensor/ttv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802476562641, "lm_q2_score": 0.7025300573952052, "lm_q1q2_score": 0.540301990527474}} {"text": "function [ x, w ] = rule01 ( n )\n\n%*****************************************************************************80\n%\n%% RULE01 returns the rule of degree 1.\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.00000000000000000E+00 ];\n ys = [ ...\n 0.00000000000000000E+00 ];\n ws = [ ...\n 0.28284271247461904E+01 ];\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/rule01.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.6926419831347362, "lm_q1q2_score": 0.5402558292630191}} {"text": "function [kN] = dyn2kN(dyn)\n% Convert force from dyne to kilonewtons. \n% Chad A. Greene 2012\nkN = dyn*1e-8;\n%\n% C'mon, help me with this conversion--I'm dyne over here!", "meta": {"author": "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/dyn2kN.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7799929002541067, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.540255829263019}} {"text": "% Fixed budget quantized kernel least-mean-square algorithm\n%\n% S. Zhao, B. Chen, P. Zhu, J. C. Principe, \"Fixed budget quantized kernel\n% least-mean-square algorithm\", Signal Processing, Volume 93, Issue 9,\n% September 2013, Pages 2759-2770,\n% http://dx.doi.org/10.1016/j.sigpro.2013.02.012.\n%\n% Remark: significance calculation only implemented for Gaussian kernel.\n%\n% This file is part of the Kernel Adaptive Filtering Toolbox for Matlab.\n% https://github.com/steven2358/kafbox/\n\nclassdef qklms_fb < kernel_adaptive_filter\n \n properties (GetAccess = 'public', SetAccess = 'private')\n eta = .9; % learning rate\n epsu = .1; % quantization threshold\n beta = .95; % forgetting factor for influence\n M = 500; % dictionary size (K in publication)\n kerneltype = 'gauss'; % kernel type\n kernelpar = 1; % kernel parameter\n end\n \n properties (GetAccess = 'public', SetAccess = 'private')\n dict = []; % codebook\n alpha = []; % expansion coefficients\n E = []; % significance vector (~ importance)\n lambda = []; % influence vector (~ how many samples are quantized\n % to each centre)\n end\n \n methods\n function kaf = qklms_fb(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 y_est = kaf.evaluate(x);\n err = y - y_est;\n \n m = size(kaf.dict,1);\n if m==0\n d2 = kaf.epsu^2 + 1; % force dictionary growth\n else\n [d2,j] = min(sum((kaf.dict - repmat(x,m,1)).^2,2));\n end\n \n c1 = pi*kaf.kernelpar^2/2; % pre-calculate\n \n if d2 <= kaf.epsu^2 % new basis under quantization threshold\n kaf.alpha(j) = kaf.alpha(j) + kaf.eta*err;\n \n % update significance for quantizing y to j-th centre (16)\n if m>1\n inds = 1:m;\n inds(j) = [];\n kaf.E(inds) = kaf.beta*kaf.E(inds) + c1*abs(kaf.alpha(inds)).* ...\n kernel(kaf.dict(inds,:),kaf.dict(j,:),kaf.kerneltype,kaf.kernelpar);\n end\n kaf.E(j) = abs(1 + kaf.eta*err/kaf.alpha(j)) * ...\n kaf.beta*kaf.E(j) + ...\n abs(kaf.alpha(j) + kaf.eta*err) * ...\n c1*kernel(kaf.dict(j,:),kaf.dict(j,:),kaf.kerneltype,kaf.kernelpar);\n \n % update influence\n kaf.lambda = kaf.beta*kaf.lambda;\n kaf.lambda(j) = kaf.lambda(j) + 1;\n \n else % new basis not under quantization threshold\n if m < kaf.M % still room for extra centres\n kaf.dict = [kaf.dict; x]; % add to codebook\n kaf.alpha = [kaf.alpha; kaf.eta*err];\n \n % update significance for addition of m+1-th centre (15)\n kaf.E(m+1,1) = 0;\n kaf.E = kaf.beta*kaf.E + abs(kaf.alpha(m+1)) * ...\n kernel(kaf.dict,kaf.dict(m+1,:),kaf.kerneltype,kaf.kernelpar);\n \n % update influence\n kaf.lambda = kaf.beta*kaf.lambda;\n % initial influence\n kaf.lambda(m+1) = 1;\n \n else % no room for extra centres\n [~,L] = min(kaf.E); % centre with lowest significance\n \n % update significance for removing L-th centre (17)\n kaf.E = kaf.E - kaf.lambda(L) * c1*abs(kaf.alpha) .* ...\n kernel(kaf.dict,kaf.dict(L,:),kaf.kerneltype,kaf.kernelpar);\n \n % prune\n kaf.dict(L,:) = [];\n kaf.alpha(L) = [];\n kaf.E(L) = [];\n kaf.lambda(L) = [];\n \n % re-calculate error\n y_est = kaf.evaluate(x);\n err = y - y_est;\n \n % grow\n kaf.dict = [kaf.dict; x];\n kaf.alpha = [kaf.alpha; kaf.eta*err];\n \n % update significance for addition of m-th centre (15)\n kaf.E(m,1) = 0;\n kaf.E = kaf.beta*kaf.E + abs(kaf.alpha(m)) * ...\n kernel(kaf.dict,kaf.dict(m,:),kaf.kerneltype,kaf.kernelpar);\n \n % update influence\n kaf.lambda = kaf.beta*kaf.lambda;\n % initial influence\n kaf.lambda(m) = 1;\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/qklms_fb.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8479677622198947, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.5401815889473317}} {"text": "% REJKURT - calculation of kutosis of a 1D, 2D or 3D array and\n% rejection of outliers values of the input data array \n% using the discrete kutosis of the values in that dimension.\n%\n% Usage:\n% >> [kurtosis rej] = rejkurt( signal, threshold, kurtosis, normalize);\n%\n% Inputs:\n% signal - one dimensional column vector of data values, two \n% dimensional column vector of values of size \n% sweeps x frames or three dimensional array of size \n% component x sweeps x frames. If three dimensional, \n% all components are treated independently. \n% threshold - Absolute threshold. If normalization is used then the \n% threshold is expressed in standard deviation of the\n% mean. 0 means no threshold.\n% kurtosis - pre-computed kurtosis (only perform thresholding). Default\n% is the empty array [].\n% normalize - 0 = do not not normalize kurtosis. 1 = normalize kurtosis.\n% 2 is 20% trimming (10% low and 10% high) kurtosis before \n% normalizing. Default is 0.\n% \n% Outputs:\n% kurtosis - normalized joint probability of the single trials \n% (same size as signal without the last dimension)\n% rej - rejected matrix (0 and 1, size: 1 x sweeps)\n%\n% Remarks:\n% The exact values of kurtosis depend on the size of a time \n% step and thus cannot be considered as absolute.\n% This function uses the kurtosis function from the statistival\n% matlab toolbox. If the statistical toolbox is not installed, \n% it uses the 'kurt' function of the ICA/EEG toolbox.\n%\n% See also: KURT, KURTOSIS\n\n% Copyright (C) 2001 Arnaud Delorme, Salk Institute, arno@salk.edu\n%\n% This file is part of EEGLAB, see http://www.eeglab.org\n% for the documentation and details.\n%\n% Redistribution and use in source and binary forms, with or without\n% modification, are permitted provided that the following conditions are met:\n%\n% 1. Redistributions of source code must retain the above copyright notice,\n% this list of conditions and the following disclaimer.\n%\n% 2. Redistributions in binary form must reproduce the above copyright notice,\n% this list of conditions and the following disclaimer in the documentation\n% and/or other materials provided with the distribution.\n%\n% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF\n% THE POSSIBILITY OF SUCH DAMAGE.\n\nfunction [kurto, rej] = rejkurt( signal, threshold, oldkurtosis, normalize);\n\nif nargin < 1\n\thelp rejkurt;\n\treturn;\nend;\t\nif nargin < 2\n\tthreshold = 0;\nend;\t\nif nargin < 4\n\tnormalize = 0;\nend;\t\nif nargin < 3\n\toldkurtosis = [];\nend;\t\n\nif size(signal,2) == 1 % transpose if necessary\n\tsignal = signal';\nend\n\nnbchan = size(signal,1);\npnts = size(signal,2);\nsweeps = size(signal,3);\nkurto = zeros(nbchan,sweeps);\n\nif ~isempty( oldkurtosis ) % speed up the computation\n\tkurto = oldkurtosis;\nelse\n\tfor rc = 1:nbchan\n\t\t% compute all kurtosis\n\t\t% --------------------\n\t\tfor index=1:sweeps\n\t\t\ttry \n\t\t\t kurto(rc, index) = kurtosis(signal(rc,:,index));\n\t\t\tcatch\n\t\t\t\tkurto(rc, index) = kurt(signal(rc,:,index));\n\t\t\tend;\t\n\t\tend\n\tend\n\n\t% normalize the last dimension\n\t% ----------------------------\t\n\tif normalize\n tmpkurt = kurto;\n if normalize == 2,\n tmpkurt = sort(tmpkurt);\n minind = max(round(length(tmpkurt)*0.1),1);\n maxind = round(length(tmpkurt)-round(length(tmpkurt)*0.1));\n if size(tmpkurt,2) == 1\n tmpkurt = tmpkurt(minind:maxind);\n else tmpkurt = tmpkurt(:,minind:maxind);\n end\n end\n\t switch ndims( signal )\n\t \tcase 2,\tkurto = (kurto-mean(tmpkurt)) / std(tmpkurt);\n\t \tcase 3,\tkurto = (kurto-mean(tmpkurt,2)*ones(1,size(kurto,2)))./ ...\n\t\t\t\t (std(tmpkurt,0,2)*ones(1,size(kurto,2)));\n\t\tend\n\tend\nend\n\n% reject\n% ------\t\nif threshold(1) ~= 0 \n if length(threshold) > 1\n \trej = (threshold(1) > kurto) | (kurto > threshold(2));\n else\n \trej = abs(kurto) > threshold;\n end\nelse\n\trej = zeros(size(kurto));\nend;\t\n\nreturn;\n", "meta": {"author": "sccn", "repo": "eeglab", "sha": "36d3982a63cde83fb279ab465b7a026ec2807c0a", "save_path": "github-repos/MATLAB/sccn-eeglab", "path": "github-repos/MATLAB/sccn-eeglab/eeglab-36d3982a63cde83fb279ab465b7a026ec2807c0a/functions/sigprocfunc/rejkurt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8479677506936878, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.5401815699181434}} {"text": "function value = sdot ( n, dx, incx, dy, incy )\n\n%*****************************************************************************80\n%\n%% SDOT forms the dot product of two vectors.\n%\n% Discussion:\n%\n% This routine uses unrolled loops for increments equal to one.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 05 May 2006\n%\n% Author:\n%\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Jack Dongarra, Cleve Moler, Jim Bunch and Pete Stewart,\n% LINPACK User's Guide,\n% SIAM, 1979.\n%\n% Charles Lawson, Richard Hanson, David Kincaid, Fred Krogh,\n% Basic Linear Algebra Subprograms for Fortran Usage,\n% Algorithm 539, \n% ACM Transactions on Mathematical Software, \n% Volume 5, Number 3, September 1979, pages 308-323.\n%\n% Parameters:\n%\n% Input, integer N, the number of entries in the vectors.\n%\n% Input, real DX(*), the first vector.\n%\n% Input, integer INCX, the increment between successive entries in DX.\n%\n% Input, real DY(*), the second vector.\n%\n% Input, integer INCY, the increment between successive entries in DY.\n%\n% Output, real VALUE, the sum of the product of the \n% corresponding entries of DX and DY.\n%\n value = 0.0;\n\n if ( n <= 0 )\n return\n end\n%\n% Code for unequal increments or equal increments\n% not equal to 1.\n%\n if ( incx ~= 1 | incy ~= 1 )\n\n if ( 0 <= incx )\n ix = 1;\n else\n ix = ( - n + 1 ) * incx + 1;\n end\n\n if ( 0 <= incy )\n iy = 1;\n else\n iy = ( - n + 1 ) * incy + 1;\n end\n\n for i = 1 : n\n value = value + dx(ix) * dy(iy);\n ix = ix + incx;\n iy = iy + incy;\n end\n%\n% Code for both increments equal to 1.\n%\n else\n\n m = mod ( n, 5 );\n\n for i = 1 : m\n value = value + dx(i) * dy(i);\n end\n\n for i = m+1 : 5 : n\n\n value = value + dx(i ) * dy(i ) ...\n + dx(i+1) * dy(i+1) ...\n + dx(i+2) * dy(i+2) ...\n + dx(i+3) * dy(i+3) ...\n + dx(i+4) * dy(i+4);\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/sdot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.7549149978955811, "lm_q1q2_score": 0.5400843042713289}} {"text": "function[] = hindawi()\n% \n% Simulation code for [1], \n%\n% [1] Paul Rodriguez \"Review: Total Variation Regularization Algorithms for \n% \t\t Images Corrupted With Different Noise Models\"\n% \n% \n%\n% Legal:\n% \n% Authors\n% Paul Rodriguez prodrig@pucp.edu.pe\n% \n\n\n\n\nl2TV = 1;\nl2TV_nqp = 2;\nl1TV = 3;\nl1TV_adapt = 4;\npoiTV_denoi = 5;\npoiTV_deconv = 6;\ngammaTV = 7;\nmixTV = 8;\nnTV = mixTV;\n\n\n% Test Images (for each case)\n\nl2Imgs = {'goldhl', 'Clena'}; % To be corrupted with Gaussian noise\nl1Imgs = {'Cbarb', 'boats'}; % To be corrupted with Salt & Pepper noise\npoiImgs = {'cman512', 'cpeppers'}; % To be corrupted with Poisson noise\ngammaImgs = {'tank', 'Clena'}; % To be corrupted with Gamma noise\nmixImgs = {'cman512'}; % To be corrupted with mixed Gaussian + Impulse noise\n\n\nTests = cell(nTV-1, 1);\n\nTests{l2TV} = l2Imgs;\nTests{l2TV_nqp} = l2Imgs;\nTests{l1TV} = l1Imgs;\nTests{l1TV_adapt} = l1Imgs;\nTests{poiTV_denoi} = poiImgs;\nTests{poiTV_deconv} = poiImgs;\n\n% Tests{gammaTV} = gammaImgs;\n% Tests{mixTV} = mixImgs;\n\n\n% kernel\n\n kernel = fspecial('disk',3.2);\n\n K = @(x) imfilter(x, kernel, 'symmetric','conv');\n\n KT = @(x) K(x);\n KC = {K, KT};\n\n\n% Noise level (define the noise level to corrupt images)\n\nl2Noise = [0.1 0.2];\nl1Noise = [0.3 0.5 0.8];\nrandomNoise = [0.1 0.2 0.3];\npoiNoise = [5 30 100 255];\n\nNoise = cell(nTV-1, 1);\n\nNoise{l2TV} = l2Noise;\nNoise{l2TV_nqp} = l2Noise;\nNoise{l1TV} = l1Noise;\nNoise{l1TV_adapt} = l1Noise;\nNoise{poiTV_denoi} = poiNoise;\nNoise{poiTV_deconv} = poiNoise;\n\n\n\n% TV Noise Model (to corrupt imput images)\n\nNoiseModel = cell(nTV-1, 1);\n\nNoiseModel{l2TV} = @(Img, sigma) imnoise(K(Img),'gaussian', 0, (sigma^2) );\nNoiseModel{l2TV_nqp} = @(Img, sigma) imnoise(K(Img),'gaussian', 0, (sigma^2) );\nNoiseModel{l1TV} = @(Img, spnoise) imnoise(Img, 'salt & pepper', spnoise);\nNoiseModel{l1TV_adapt} = @(Img, spnoise) imnoise(Img, 'salt & pepper', spnoise);\n\nNoiseModel{poiTV_denoi} = @(Img, M) poissrnd( M*NormalizeMax(Img) );\nNoiseModel{poiTV_deconv} = @(Img, M) poissrnd( M*NormalizeMax(K(Img)) );\n\n% ----------------------\n% Define TV parameters\n% ----------------------\n\n% Loops\n\nTVLoops = zeros(nTV-1, 1);\n\nTVLoops(l2TV) = 5;\nTVLoops(l2TV_nqp) = 5;\nTVLoops(l1TV) = 4;\nTVLoops(l1TV_adapt) = 4;\n\nTVLoops(poiTV_denoi) = 6;\nTVLoops(poiTV_deconv) = 6;\n\n% regularization parameters\n\nTVLambda = zeros(nTV-1, 5);\n\nTVLambda(l2TV,1) = 0.05; TVLambda(l2TV,2) = 0.1; \nTVLambda(l2TV_nqp,1) = 0.05; TVLambda(l2TV_nqp,2) = 0.1; \n\nTVLambda(l1TV,1) = 1.2; TVLambda(l1TV,2) = 1.4; TVLambda(l1TV,3) = 1.5;\nTVLambda(l1TV_adapt,1) = 1.0; TVLambda(l1TV_adapt,2) = 1.0; TVLambda(l1TV_adapt,3) = 1.0;\n\nTVLambda(poiTV_denoi,1:4) = 2./[0.35, 0.15, 0.075, 0.025 ];\n\n\n\n\n% Wrappers to TV functions)\n\nRestoreTV = cell(nTV-1, 1);\n\nRestoreTV{l2TV} = @(b, lambda, loops, KC) runl2TV(b, lambda, loops, KC);\nRestoreTV{l2TV_nqp} = @(b, lambda, loops, KC) runl2TV_nqp(b, lambda, loops, KC);\nRestoreTV{l1TV} = @(b, lambda, loops, dummy) runl1TV(b, lambda, loops, []);\nRestoreTV{l1TV_adapt} = @(b, lambda, loops, dummy) runl1TV_Adapt(b, lambda, loops);\n\nRestoreTV{poiTV_denoi} = @(b, lambda, loops, dummy) run_poiTV(b, lambda, loops, {});\nRestoreTV{poiTV_deconv} = @(b, lambda, loops, KC) run_poiTV(b, lambda, loops, KC);\n\n% additional vars\n\nt1 = zeros(nTV-1, 2, 2);\nt2 = zeros(nTV-1, 2, 2);\n\nnmpdef;\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%\n% Setup %\n%%%%%%%%%%%%%%%%%%%%%%%%\n\nSSIM_CODE = exist('ssim_index');\nif( SSIM_CODE == 0 )\n disp('NOTE:');\n disp(' The function ssim_index (code for [SSIM]) is not in your path...');\n disp(' You may download it from:');\n disp(' http://www.ece.uwaterloo.ca/~z70wang/research/ssim/');\n disp(' ');\n disp(' Disabling SSIM reports');\n disp(' ');\n disp(' [SSIM] Z. Wang, A. Bovik, H. Sheikh and E. Simoncelli, ');\n disp(' \"Image quality assessment: From error visibility to');\n disp(' structural similarity \" ');\n disp(' IEEE Transactions on Image Processing, 2004, 13:4(600-612).');\n\nend\n\n\n\nt=5;\n\nstr_all = sprintf(' \\n');\n\n\n\nwhile( iscell(Tests{t}) )\n\n str = sprintf(' \\n'); str_all = [ str_all str ];\n str = sprintf(' Img \\t\\t Noise \\t\\t SNR (db) \\t\\t Time (s) \\t\\t SSIM \\n');\n str_all = [ str_all str ];\n\n\n NImgs = length( Tests{t} );\n\n for k = 1: NImgs,\n\n switch lower( Tests{t}{k} )\n\n case{'lena'}\n I = double( imread('gray_imgs/lena_gray_512.png') ) / 255;\n SSIM_COLOR = 1;\n\n case{'peppers'}\n I = double( imread('gray_imgs/peppers_gray.png') ) / 255;\n SSIM_COLOR = 1;\n\n case{'boats'}\n I = double( imread('gray_imgs/boats_gray.png') ) / 255;\n SSIM_COLOR = 1;\n\n case{'goldhl'}\n I = double( imread('gray_imgs/goldhill_gray.png') ) / 255;\n SSIM_COLOR = 1;\n\n case{'cman'}\n I = double( imread('gray_imgs/cameraman_256x256.tiff') ) / 255;\n SSIM_COLOR = 1;\n\n case{'cman512'}\n I = double( imread('gray_imgs/cameraman_512x512.tiff') ) / 255;\n SSIM_COLOR = 1;\n\n case{'clena'}\n I = double( imread('color_imgs/lena_color_512.png') ) / 255;\n SSIM_COLOR = 0;\n\n case{'cbarb'}\n I = double( imread('color_imgs/barbara_color.png') ) / 255;\n SSIM_COLOR = 0;\n\n case{'cpeppers'}\n I = double( imread('color_imgs/peppers_color.png') ) / 255;\n SSIM_COLOR = 0;\n\n case{'cmandrill'}\n I = double( imread('color_imgs/mandrill_color.png') ) / 255;\n SSIM_COLOR = 0;\n\n end % --- END (switch) ---\n\n\n for n = 1:length(Noise{t})\n\n % add noise\n b = NoiseModel{t}( I, Noise{t}(n) );\n figure; imagesc( Normalize(b) ); colormap gray; axis image; axis off;\n\n\n % Restore via TV\n [u t1(t,k,n) t2(t,k,n)] = RestoreTV{t}(b, TVLambda(t,n), TVLoops(t), KC );\n\n % Restore performance\n [snrRec(t,k,n), ssimRec(t,k,n)] = computePerf(I, u, SSIM_CODE*SSIM_COLOR, 0);\n\n if(n==1)\n str = sprintf('%s \\t\\t %1.2f \\t\\t %2.2f \\t\\t %2.2f (%2.2f) \\t\\t %1.3f \\n', ...\n lower( Tests{t}{k} ), Noise{t}(n), snrRec(t,k,n), t1(t,k,n), t2(t,k,n), ssimRec(t,k,n) );\n else\n str = sprintf(' \\t\\t %1.2f \\t\\t %2.2f \\t\\t %2.2f (%2.2f) \\t\\t %1.3f \\n', ...\n Noise{t}(n), snrRec(t,k,n), t1(t,k,n), t2(t,k,n), ssimRec(t,k,n) );\n end\n str_all = [ str_all str ];\n\n\n end % --- END (FOR(n)) ---\n\n end % --- END (FOR(k)) ---\n\n disp(str_all);\n \n\n t = t + 1;\n\n if(t==6) break; end\n\nend\n\n\nend\n\n% ============================================\n\n%%%%%%%%%%%%%%%%%%%%%%%%\n% Normalize %\n%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction[u] = Normalize(x)\n\nu = (x - min(x(:)))/(max(x(:)) - min(x(:)));\n\n\nend\n\n% ============================================\n\nfunction[u] = NormalizeMax(x)\n\nu = x/max(abs(x(:)));\n\n\nend\n\n% ============================================\n\nfunction[u, timePerf, t2] = runl2TV(b, lambda, loops, KC)\n\n\n pars = irntvInputPars('l2tv');\n\n pars.pcgtol_ini = 1e-4;\n pars.loops = loops;\n% pars.U0 = b;\n\n pars.adapt_epsR = 1;\n pars.epsR_cutoff = 0.01;\n pars.adapt_epsF = 1;\n pars.epsF_cutoff = 0.05; \n\n tic;\n u = irntv(b, KC, lambda, pars);\n timePerf = toc;\n\n t2 = 0;\n\nend\n\n% ============================================\n\nfunction[u, timePerf, t2] = runl2TV_nqp(b, lambda, loops, KC)\n\n pars = irntvInputPars('l2tv_nqp');\n\n pars.pcgtol_ini = 1e-4;\n pars.loops = loops;\n% pars.U0 = b;\n\n pars.adapt_epsR = 1;\n pars.epsR_cutoff = 0.01;\n pars.adapt_epsF = 1;\n pars.epsF_cutoff = 0.1; \n\n pars.loops_NQP = 15;\n pars.gamma_NQP = 0.5e-3;\n pars.alpha_NQP = 5e-1;\n pars.vmax_NQP = 1+1; % maximum value of output image\n\n\n tic;\n u = irntv(b+1, KC, lambda, pars)-1;\n timePerf = toc;\n\n t2 = 0;\n\nend\n\n% ============================================\n\nfunction[u, timePerf, t2] = runl1TV(b, lambda, loops, KC)\n\n\n if(nargin < 6)\n flagTitle = 0;\n end\n\n pars = irntvInputPars('l1tv');\n\n pars.pcgtol_ini = 1e-4;\n pars.epsF = 1e-2; \n pars.epsR = 1e-4;\n pars.loops = loops;\n\n\n tic;\n u = irntv(b, KC, lambda, pars);\n timePerf = toc;\n\n t2 = 0;\n\nend\n\n\n% ============================================\n\nfunction[u, timePerf, t2] = runl1TV_Adapt(b, lambda, loops)\n\n\ntic;\n\nS0 = adaptMedian(b);\n\nt2 = toc;\n\nInputDims = size(S0);\n\n\nif(length(InputDims) == 2)\n\n lambda_adapt = 1e-6*(S0 == 0) + lambda*5*(S0 ~= 0);\n\nelse\n\n for d=1:3,\n lambda_adapt(:,:,d) = 1e-6*(S0(:,:,d) == 0) + lambda*5.0*(S0(:,:,d) ~= 0);\n end\n\nend\n\n% ---------- Setup for IRN_adapt ------------------\n\npars_irn_adapt = irntvInputPars('l1tv_adapt');\n\npars_irn_adapt.adapt_epsR = 1;\npars_irn_adapt.epsR_cutoff = 0.01;\npars_irn_adapt.adapt_epsF = 1;\npars_irn_adapt.epsF_cutoff = 0.1;\n\npars_irn_adapt.pcgtol_ini = 1e-4;\n\npars_irn_adapt.loops = 1;\n\npars_irn_adapt.U0 = b; % necessary the for adapt case\n\n\n tic;\n u = irntv(b, [], lambda_adapt, pars_irn_adapt);\n\n for m = 2:loops\n\n pars_irn_adapt.U0 = u;\n lambda_adapt = lambda_adapt*1.2;\n\n u = irntv(b, [], lambda_adapt, pars_irn_adapt);\n\n end\n\n timePerf = toc;\n\n\n\nend\n\n\n% ============================================\n\n% ============================================\n\nfunction[u, timePerf, t2] = run_poiTV(b, lambda, loops, KC)\n\n pars = irntvInputPars('tv_poisson_adapt');\n\n pars.pcgtol_ini = 1e-4;\n pars.loops = 1;\n% pars.U0 = b;\n\n pars.adapt_epsR = 1;\n pars.epsR_cutoff = 0.1;\n pars.adapt_epsF = 1;\n pars.epsF_cutoff = 0.15; \n\n pars.loops_NQP = 35;\n pars.gamma_NQP = 5e-3;\n pars.alpha_NQP = 5e-1;\n pars.vmax_NQP = 1+1; % maximum value of output image\n\n T = lambda;\n\n tic;\n u = irntv(b+0.01, KC, lambda, pars)-0.01;\n\n \n\n for ln=2:loops,\n\n [sig1, cv1, mu1, siginv1, cvinv1, S1, lmu1] = estNoise(u, 2*3+1, 100, 1);\n [sig2, cv2, mu2, siginv2, cvinv2, S2, lmu2] = estNoise(lmu1, 2*3+1, 100, 1);\n\n pars.U0 = u;\n vmin = min( pars.U0(:) );\n if(vmin < 0) pars.U0 = pars.U0 - vmin + 0.01; end\n\n alpha = 1.0;\n [Nrows Ncols Ndims] = size(u);\n\n mask = zeros(size(S2)); \n\n for d = 1:Ndims,\n maskTmp = zeros(Nrows*Ncols,1);\n\n vS1 = S2(:,:,d); vS1 = vS1(:);\n\n tau = unimodal(S1(:,:,d));\n p2 = find( vS1 < alpha*tau );\n maskTmp(p2) = (1 - Normalize( vS1(p2) ) )*(1-0.85) + 0.85;\n\n p3 = find(vS1 >= alpha*tau);\n maskTmp(p3) = 1.0;\n\n mask(:,:,d) = reshape(maskTmp, [Nrows Ncols]);\n \n end % _END_ FOR(d)\n\n T = T.*mask;\n\n u = irntv(b+0.1, KC, T, pars)-0.1;\n\n end\n\n % ====================================\n timePerf = toc;\n\n t2 = 0;\n\nend\n\n% ============================================\n\nfunction[snrRec, ssimRec] = computePerf(Img, u, flagSSIM, flagTitle)\n\n snrRec = snr(Img, u); \n if(flagSSIM)\n ssimRec = ssim_index(255*Normalize(Img), 255*Normalize(u));\n else\n ssimRec = NaN;\n end\n\n figure; imagesc( Normalize(u) ); colormap gray; axis image; axis off;\n if(flagTitle)\n title(sprintf('Restored Image\\n SNR: %4.1fdB. SSIM: %1.2f ', ...\n snrRec, ssimRec));\n end\n\nend", "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/hindawi.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676284, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.5400843009621358}} {"text": "function line_enhanced = EnhanceLine(band)\n%ENHANCELINE enhance NDBI to light urban/built-up areas and dark other\n%bright surface, such as desert, rock. ref Guindon et. RSE 2004\n\n% also can see the details at\n% https://homepages.inf.ed.ac.uk/rbf/HIPR2/linedet.htm.\n% band=data_toabt.BandGreen;\n% \n% band=ndbi;\n \n%% line with a length of three pixels\n% template1=[-1 1 0;\n% -1 1 0;\n% -1 1 0;];\n% template2=[0 1 -1;\n% 0 1 -1;\n% 0 1 -1;];\n% line_enhanced1 = imfilter(band,template1);\n% line_enhanced2 = imfilter(band,template2);\n% line_enhanced=max(line_enhanced1,line_enhanced2);\n% \n% template1=[-1 -1 -1;\n% 1 1 1;\n% 0 0 0;];\n% template2=[0 0 0;\n% 1 1 1;\n% -1 -1 -1;];\n% line_enhanced1 = imfilter(band,template1);\n% line_enhanced2 = imfilter(band,template2);\n% line_enhanced=max(line_enhanced1,line_enhanced);\n% line_enhanced=max(line_enhanced2,line_enhanced);\n% \n% template1=[1 -1 -1;\n% 0 1 -1;\n% 0 0 1;];\n% template2=[1 0 0;\n% -1 1 0;\n% -1 -1 1;];\n% line_enhanced1 = imfilter(band,template1);\n% line_enhanced2 = imfilter(band,template2);\n% line_enhanced=max(line_enhanced1,line_enhanced);\n% line_enhanced=max(line_enhanced2,line_enhanced);\n% \n% template1=[-1 -1 1;\n% -1 1 0;\n% 1 0 0;];\n% template2=[0 0 1;\n% 0 1 -1;\n% 1 -1 -1;];\n% \n% line_enhanced1 = imfilter(band,template1);\n% line_enhanced2 = imfilter(band,template2);\n% line_enhanced=max(line_enhanced1,line_enhanced);\n% line_enhanced=max(line_enhanced2,line_enhanced); \n% \tline_enhanced = line_enhanced./3;\n \n\n template=[-1 2 -1;\n -1 2 -1;\n -1 2 -1;];\n\ttemplate = template./6;\n line_enhanced = imfilter(band,template);\n \n template=[-1 -1 -1;\n 2 2 2;\n -1 -1 -1;];\n\ttemplate = template./6;\n line_enhanced_new = imfilter(band,template);\n line_enhanced=max(line_enhanced_new,line_enhanced); \n \n template =[2 -1 -1;\n -1 2 -1;\n -1 -1 2;];\n\ttemplate = template./6;\n line_enhanced_new = imfilter(band,template);\n line_enhanced=max(line_enhanced_new,line_enhanced); \n \n template =[-1 -1 2;\n -1 2 -1;\n 2 -1 -1;];\n\ttemplate = template./6;\n line_enhanced_new = imfilter(band,template);\n line_enhanced=max(line_enhanced_new,line_enhanced); \nend\n\n", "meta": {"author": "GERSL", "repo": "Fmask", "sha": "e9e0e23af163ec55c60b7f93e6ab8e72617ee851", "save_path": "github-repos/MATLAB/GERSL-Fmask", "path": "github-repos/MATLAB/GERSL-Fmask/Fmask-e9e0e23af163ec55c60b7f93e6ab8e72617ee851/EnhanceLine.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.82893881677331, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.5399333308158185}} {"text": "classdef anisotropicdiffusion < TTeMPS_op_laplace\n % Class for anisotropic diffusion operator with tridiagonal diffusion matrix\n %\n % [ 1 a 0 ...0 ]\n % [ a 1 a 0 ..0 ]\n % D = [ 0 a 1 a 0 ..0 ]\n % [ .. .. . . ]\n % [ 0 ... .. 0 a 1 ]\n %\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\n\n properties\n L\n D\n % precomputed spectral decomp of 1D Laplace:\n\n end\n\n methods\n\n function A = update_properties( A );\n\n A.rank = [1, 3*ones(1, length(A.U)-1), 1]; % the TT rank is always three for such Laplace-like tensors\n size_col_ = cellfun( @(y) size(y,1), A.U);\n A.size_col = size_col_ ./ (A.rank(1:end-1).*A.rank(2:end));\n A.size_row = cellfun( @(y) size(y,2), A.U);\n A.order = length( A.size_row );\n end\n end\n\n\n methods( Access = public )\n\n function A = anisotropicdiffusion( n, d, alpha )\n\n if ~exist('alpha', 'var')\n alpha = 0.25;\n end\n \n one = ones(n,1);\n q = linspace( -10, 10, n)';\n h = abs(q(2) - q(1));\n L = -spdiags( [one, -2*one, one], [-1 0 1], n, n) / (h^2);\n\n % superclass constructor\n A = A@TTeMPS_op_laplace( L, d );\n % precompute eigenvalue information and exponential for use in local\n A = initialize_precond( A );\n % preconditioner:\n A.L = L;\n\n\t\t\t[A.V_L, A.E_L] = eig(full(A.L));\n A.E_L = diag(A.E_L);\n\n A.D = spdiags( [-one,one], [-1,1], n, n ) / (2*h); \n I = speye( n, n );\n\n e1 = sparse( 1, 1, 1, 3, 1 );\n e2 = sparse( 2, 1, 1, 3, 1 );\n e3 = sparse( 3, 1, 1, 3, 1 );\n\n l_mid = sparse( 3, 1, 1, 9, 1 ); % e_3\n b_mid = sparse( 6, 1, 1, 9, 1 ); % e_6\n m_mid = sparse( [1;9], [1;1], [1;1], 9, 1 ); % e_1 + e_9\n c_mid = sparse( 2, 1, 1, 9, 1 ); % e_2\n\n A.U = cell( 1, d );\n A.U{1} = kron( A.L, e1 ) + kron( 2*alpha*A.D, e2 ) + kron( I, e3);\n A_mid = kron( A.L, l_mid ) + kron( 2*alpha*A.D, b_mid ) + kron( I, m_mid) + kron( A.D, c_mid );\n for i=2:d-1\n A.U{i} = A_mid;\n end\n A.U{d} = kron( I, e1 ) + kron( A.D, e2 ) + kron( A.L, e3);\n\n A = update_properties( A );\n \n end\n\n function expB = constr_precond_inner( A, X, mu )\n\n n = size(A.L, 1);\n sz = [X.rank(mu), X.size(mu), X.rank(mu+1)]\n\n B1 = zeros( X.rank(mu) );\n % calculate B1 part:\n for i = 1:mu-1\n % apply L to the i'th core\n tmp = X;\n Xi = matricize( tmp.U{i}, 2 );\n Xi = A.L*Xi;\n tmp.U{i} = tensorize( Xi, 2, [X.rank(i), n, X.rank(i+1)] );\n B1 = B1 + innerprod( X, tmp, 'LR', mu-1);\n end\n\n B3 = zeros( X.rank(mu+1) );\n % calculate B3 part:\n for i = mu+1:A.order\n tmp = X;\n Xi = matricize( tmp.U{i}, 2 );\n Xi = A.L*Xi;\n tmp.U{i} = tensorize( Xi, 2, [X.rank(i), n, X.rank(i+1)] );\n B3 = B3 + innerprod( X, tmp, 'RL', mu+1);\n end\n \n [V1,e1] = eig(B1);\n e1 = diag(e1);\n [V3,e3] = eig(B3);\n e3 = diag(e3);\n\n lmin = min(e1) + min(A.E_L) + min(e3);\n lmax = max(e1) + max(A.E_L) + max(e3);\n\n R = lmax/lmin\n \n [omega, alpha] = load_coefficients( R );\n\n k = 3;\n omega = omega/lmin;\n alpha = alpha/lmin;\n\n expB = cell(3,k);\n \n for i = 1:k\n expB{1,i} = omega(i) * V1*diag( exp( -alpha(i)*e1 ))*V1'; % include omega in first part\n expB{2,i} = A.V_L*diag( exp( -alpha(i)*A.E_L ))*A.V_L';\n expB{3,i} = V3*diag( exp( -alpha(i)*e3 ))*V3';\n end\n end\n\n function expB = constr_precond_outer( A, X, mu1, mu2 )\n \n n = size(A.L, 1);\n\n B1 = zeros( X.rank(mu1) );\n % calculate B1 part:\n for i = 1:mu1-1\n % apply L to the i'th core\n tmp = X;\n Xi = matricize( tmp.U{i}, 2 );\n Xi = A.L*Xi;\n tmp.U{i} = tensorize( Xi, 2, [X.rank(i), n, X.rank(i+1)] );\n B1 = B1 + innerprod( X, tmp, 'LR', mu1-1);\n end\n\n B3 = zeros( X.rank(mu2+1) );\n % calculate B3 part:\n for i = mu2+1:A.order\n tmp = X;\n Xi = matricize( tmp.U{i}, 2 );\n Xi = A.L*Xi;\n tmp.U{i} = tensorize( Xi, 2, [X.rank(i), n, X.rank(i+1)] );\n B3 = B3 + innerprod( X, tmp, 'RL', mu2+1);\n end\n \n [V1,e1] = eig(B1);\n e1 = diag(e1);\n [V3,e3] = eig(B3);\n e3 = diag(e3);\n\n lmin = min(e1) + 2*min(A.E_L) + min(e3);\n lmax = max(e1) + 2*max(A.E_L) + max(e3);\n\n R = lmax/lmin\n \n [omega, alpha] = load_coefficients( R );\n\n k = 3;\n omega = omega/lmin;\n alpha = alpha/lmin;\n\n expB = cell(4,k);\n \n for i = 1:k\n expB{1,i} = omega(i) * V1*diag( exp( -alpha(i)*e1 ))*V1'; % include omega in first part\n expB{2,i} = A.V_L*diag( exp( -alpha(i)*A.E_L ))*A.V_L';\n expB{3,i} = A.V_L*diag( exp( -alpha(i)*A.E_L ))*A.V_L';\n expB{4,i} = V3*diag( exp( -alpha(i)*e3 ))*V3';\n end\n end\n\n function P = constr_precond( A, k )\n\n d = A.order;\n\n lmin = d*min(A.E_L);\n lmax = d*max(A.E_L);\n\n R = lmax/lmin\n\n % http://www.mis.mpg.de/scicomp/EXP_SUM/1_x/1_xk07_2E2\n % 0.0133615547183825570028305575534521842940 {omega[1]}\n % 0.0429728469424360175410925952177443321034 {omega[2]}\n % 0.1143029399081515586560726591147663100401 {omega[3]}\n % 0.2838881266934189482611071431161775535656 {omega[4]}\n % 0.6622322841999484042811198458711174907876 {omega[5]}\n % 1.4847175320092703810050463464342840325116 {omega[6]}\n % 3.4859753729916252771962870138366952232900 {omega[7]}\n % 0.0050213411684266507485648978019454613531 {alpha[1]}\n % 0.0312546410994290844202411500801774835168 {alpha[2]}\n % 0.1045970270084145620410366606112262388706 {alpha[3]}\n % 0.2920522758702768403556507270657505159761 {alpha[4]}\n % 0.7407504784499061527671195936939341208927 {alpha[5]}\n % 1.7609744335543204401530945069076494746696 {alpha[6]}\n % 4.0759036969145123916954953635638503328664 {alpha[7]}\n \n if k == 3\n [omega, alpha] = load_coefficients( R );\n\n elseif k == 7\n omega = [0.0133615547183825570028305575534521842940 0.0429728469424360175410925952177443321034 0.1143029399081515586560726591147663100401,...\n 0.2838881266934189482611071431161775535656 0.6622322841999484042811198458711174907876 1.4847175320092703810050463464342840325116,...\n 3.4859753729916252771962870138366952232900];\n alpha = [0.0050213411684266507485648978019454613531 0.0312546410994290844202411500801774835168 0.1045970270084145620410366606112262388706,...\n 0.2920522758702768403556507270657505159761 0.7407504784499061527671195936939341208927 1.7609744335543204401530945069076494746696,...\n 4.0759036969145123916954953635638503328664];\n else\n error('Unknown rank specified. Choose either k=3 or k=7');\n end\n\n omega = omega/lmin;\n alpha = alpha/lmin;\n\n % careful: all cores assumed to be of same size\n E = reshape( expm( -alpha(1) * A.L), [1, A.size_row(2), A.size_col(2), 1]);\n P = omega(1)*TTeMPS_op( repmat({E},1,d) );\n for i = 2:k\n E = reshape( expm( -alpha(i) * A.L), [1, A.size_row(2), A.size_col(2), 1]);\n P = P + omega(i)*TTeMPS_op( repmat({E},1,d) );\n end\n\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/manifolds/ttfixedrank/TTeMPS_1.1/operators/anisotropicdiffusion.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933403143929, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.5398321128660418}} {"text": "%==========================================================================\n%\n% Active contour with Chen-Vese Method\n% for image segementation\n%\n% Implemented by Yue Wu (yue.wu@tufts.edu)\n% Tufts University\n% Feb 2009\n% http://sites.google.com/site/rexstribeofimageprocessing/\n%\n% all rights reserved\n% Last update 02/26/2009\n%--------------------------------------------------------------------------\n% Usage of varibles:\n% input:\n% I = any gray/double/RGB input image\n% mask = initial mask, either customerlized or built-in\n% num_iter = total number of iterations\n% mu = weight of length term\n% method = submethods pick from ('chen','vector','multiphase')\n%\n% Types of built-in mask functions\n% 'small' = create a small circular mask\n% 'medium' = create a medium circular mask\n% 'large' = create a large circular mask\n% 'whole' = create a mask with holes around\n% 'whole+small' = create a two layer mask with one layer small\n% circular mask and the other layer with holes around\n% (only work for method 'multiphase')\n% Types of methods\n% 'chen' = general CV method\n% 'vector' = CV method for vector image\n% 'multiphase'= CV method for multiphase (2 phases applied here)\n%\n% output:\n% phi0 = updated level set function\n%\n%--------------------------------------------------------------------------\n%\n% Description: This code implements the paper: \"Active Contours Without\n% Edges\" by Chan and Vese for method 'chen', the paper:\"Active Contours Without\n% Edges for vector image\" by Chan and Vese for method 'vector', and the paper\n% \"A Multiphase Level Set Framework for Image Segmentation Using the\n% Mumford and Shah Model\" by Chan and Vese.\n%\n%--------------------------------------------------------------------------\n% Deomo: Please see HELP file for details\n%==========================================================================\n\nfunction [seg, phi0]= chenvese(I,mask,num_iter,mu,method)\n\n%%\n%-- Default settings\n% length term mu = 0.2 and default method = 'chan'\nif(~exist('mu','var'))\n mu=0.2;\nend\n\nif(~exist('method','var'))\n method = 'chan';\nend\n\n%-- End default settings\n\n%%\n%-- Initializations on input image I and mask\n% resize original image\nrow=size(I,1);\ncol=size(I,2);\ns = 200./min(size(I,1),size(I,2)); % resize scale\nif s<1\n I = imresize(I,s);\nend\n\n% auto mask settings\nif ischar(mask)\n switch lower (mask)\n case 'small'\n mask = maskcircle2(I,'small');\n case 'medium'\n mask = maskcircle2(I,'medium');\n case 'large'\n mask = maskcircle2(I,'large');\n case 'whole'\n mask = maskcircle2(I,'whole');\n %mask = init_mask(I,30);\n case 'whole+small'\n m1 = maskcircle2(I,'whole');\n m2 = maskcircle2(I,'small');\n mask = zeros(size(I,1),size(I,2),2);\n mask(:,:,1) = m1(:,:,1);\n mask(:,:,2) = m2(:,:,2);\n otherwise\n error('unrecognized mask shape name (MASK).');\n end\nelse\n if s<1\n mask = imresize(mask,s);\n end\n if size(mask,1)>size(I,1) || size(mask,2)>size(I,2)\n error('dimensions of mask unmathch those of the image.')\n end\n switch lower(method)\n case 'multiphase'\n if (size(mask,3) == 1)\n error('multiphase requires two masks but only gets one.')\n end\n end\n \nend\n\n\nswitch lower(method)\n case 'chan'\n if size(I,3)== 3\n P = rgb2gray(uint8(I));\n P = double(P);\n elseif size(I,3) == 2\n P = 0.5.*(double(I(:,:,1))+double(I(:,:,2)));\n else\n P = double(I);\n end\n layer = 1;\n \n case 'vector'\n s = 200./min(size(I,1),size(I,2)); % resize scale\n I = imresize(I,s);\n mask = imresize(mask,s);\n layer = size(I,3);\n if layer == 1\n display('only one image component for vector image')\n end\n P = double(I);\n \n case 'multiphase'\n layer = size(I,3);\n if size(I,1)*size(I,2)>200^2\n s = 200./min(size(I,1),size(I,2)); % resize scale\n I = imresize(I,s);\n mask = imresize(mask,s);\n end\n \n P = double(I); %P store the original image\n otherwise\n error('!invalid method')\nend\n%-- End Initializations on input image I and mask\n\n%%\n%-- Core function\nswitch lower(method)\n case {'chan','vector'}\n %-- SDF\n % Get the distance map of the initial mask\n \n mask = mask(:,:,1);\n phi0 = bwdist(mask)-bwdist(1-mask)+im2double(mask)-.5;\n % initial force, set to eps to avoid division by zeros\n force = eps;\n %-- End Initialization\n \n %-- Display settings\n figure();\n subplot(2,2,1); imshow(I); title('Input Image');\n subplot(2,2,2); contour(flipud(phi0), [0 0], 'r','LineWidth',1); title('initial contour');\n subplot(2,2,3); title('Segmentation');\n %-- End Display original image and mask\n \n %-- Main loop\n for n=1:num_iter\n inidx = find(phi0>=0); % frontground index\n outidx = find(phi0<0); % background index\n force_image = 0; % initial image force for each layer\n for i=1:layer\n L = im2double(P(:,:,i)); % get one image component\n c1 = sum(sum(L.*Heaviside(phi0)))/(length(inidx)+eps); % average inside of Phi0\n c2 = sum(sum(L.*(1-Heaviside(phi0))))/(length(outidx)+eps); % verage outside of Phi0\n force_image=-(L-c1).^2+(L-c2).^2+force_image;\n % sum Image Force on all components (used for vector image)\n % if 'chan' is applied, this loop become one sigle code as a\n % result of layer = 1\n end\n \n % calculate the external force of the image\n force = mu*kappa(phi0)./max(max(abs(kappa(phi0))))+1/layer.*force_image;\n \n % normalized the force\n force = force./(max(max(abs(force))));\n \n % get stepsize dt\n dt=0.5;\n \n % get parameters for checking whether to stop\n old = phi0;\n phi0 = phi0+dt.*force;\n new = phi0;\n indicator = checkstop(old,new,dt);\n% if n==1\n% figure;\n% showphi(I,phi0,n);\n% end\n% \n \n % intermediate output\n \n if(mod(n,20) == 0)\n showphi(I,phi0,n);\n end;\n if indicator % decide to stop or continue\n showphi(I,phi0,n);\n \n %make mask from SDF\n seg = phi0<=0; %-- Get mask from levelset\n if s<1\n seg = imresize(seg,[row col]);\n end\n \n subplot(2,2,4); imshow(seg); title('Global Region-Based Segmentation');\n \n return;\n end\n end;\n showphi(I,phi0,n);\n \n %make mask from SDF\n seg = phi0<=0; %-- Get mask from levelset\n \n subplot(2,2,4); imshow(seg); title('Global Region-Based Segmentation');\n case 'multiphase'\n %-- Initializations\n % Get the distance map of the initial masks\n mask1 = mask(:,:,1);\n mask2 = mask(:,:,2);\n phi1=bwdist(mask1)-bwdist(1-mask1)+im2double(mask1)-.5;%Get phi1 from the initial mask 1\n phi2=bwdist(mask2)-bwdist(1-mask2)+im2double(mask2)-.5;%Get phi1 from the initial mask 2\n \n %-- Display settings\n figure();\n subplot(2,2,1);\n if layer ~= 1\n imshow(I); title('Input Image');\n else\n imagesc(P); axis image; colormap(gray);title('Input Image');\n end\n subplot(2,2,2);\n hold on\n contour(flipud(mask1),[0,0],'r','LineWidth',2.5);\n contour(flipud(mask1),[0,0],'x','LineWidth',1);\n contour(flipud(mask2),[0,0],'g','LineWidth',2.5);\n contour(flipud(mask2),[0,0],'x','LineWidth',1);\n title('initial contour');\n hold off\n subplot(2,2,3); title('Segmentation');\n %-- End display settings\n \n %Main loop\n for n=1:num_iter\n %-- Narrow band for each phase\n nb1 = find(phi1<1.2 & phi1>=-1.2); %narrow band of phi1\n inidx1 = find(phi1>=0); %phi1 frontground index\n outidx1 = find(phi1<0); %phi1 background index\n \n nb2 = find(phi2<1.2 & phi2>=-1.2); %narrow band of phi2\n inidx2 = find(phi2>=0); %phi2 frontground index\n outidx2 = find(phi2<0); %phi2 background index\n %-- End initiliazaions on narrow band\n \n %-- Mean calculations for different partitions\n %c11 = mean (phi1>0 & phi2>0)\n %c12 = mean (phi1>0 & phi2<0)\n %c21 = mean (phi1<0 & phi2>0)\n %c22 = mean (phi1<0 & phi2<0)\n \n cc11 = intersect(inidx1,inidx2); %index belong to (phi1>0 & phi2>0)\n cc12 = intersect(inidx1,outidx2); %index belong to (phi1>0 & phi2<0)\n cc21 = intersect(outidx1,inidx2); %index belong to (phi1<0 & phi2>0)\n cc22 = intersect(outidx1,outidx2); %index belong to (phi1<0 & phi2<0)\n \n f_image11 = 0;\n f_image12 = 0;\n f_image21 = 0;\n f_image22 = 0; % initial image force for each layer\n \n for i=1:layer\n L = im2double(P(:,:,i)); % get one image component\n \n if isempty(cc11)\n c11 = eps;\n else\n c11 = mean(L(cc11));\n end\n \n if isempty(cc12)\n c12 = eps;\n else\n c12 = mean(L(cc12));\n end\n \n if isempty(cc21)\n c21 = eps;\n else\n c21 = mean(L(cc21));\n end\n \n if isempty(cc22)\n c22 = eps;\n else\n c22 = mean(L(cc22));\n end\n \n %-- End mean calculation\n \n %-- Force calculation and normalization\n % force on each partition\n \n f_image11=(L-c11).^2.*Heaviside(phi1).*Heaviside(phi2)+f_image11;\n f_image12=(L-c12).^2.*Heaviside(phi1).*(1-Heaviside(phi2))+f_image12;\n f_image21=(L-c21).^2.*(1-Heaviside(phi1)).*Heaviside(phi2)+f_image21;\n f_image22=(L-c22).^2.*(1-Heaviside(phi1)).*(1-Heaviside(phi2))+f_image22;\n end\n \n % sum Image Force on all components (used for vector image)\n % if 'chan' is applied, this loop become one sigle code as a\n % result of layer = 1\n \n % calculate the external force of the image\n \n % curvature on phi1\n curvature1 = mu*kappa(phi1);\n curvature1 = curvature1(nb1);\n % image force on phi1\n fim1 = 1/layer.*(-f_image11(nb1)+f_image21(nb1)-f_image12(nb1)+f_image22(nb1));\n fim1 = fim1./max(abs(fim1)+eps);\n \n % curvature on phi2\n curvature2 = mu*kappa(phi2);\n curvature2 = curvature2(nb2);\n % image force on phi2\n fim2 = 1/layer.*(-f_image11(nb2)+f_image12(nb2)-f_image21(nb2)+f_image22(nb2));\n fim2 = fim2./max(abs(fim2)+eps);\n \n % force on phi1 and phi2\n force1 = curvature1+fim1;\n force2 = curvature2+fim2;\n %-- End force calculation\n \n % detal t\n dt = 1.5;\n \n old(:,:,1) = phi1;\n old(:,:,2) = phi2;\n \n %update of phi1 and phi2\n phi1(nb1) = phi1(nb1)+dt.*force1;\n phi2(nb2) = phi2(nb2)+dt.*force2;\n \n new(:,:,1) = phi1;\n new(:,:,2) = phi2;\n \n indicator = checkstop(old,new,dt);\n \n if indicator\n showphi(I, new, n);\n %make mask from SDF\n seg11 = (phi1>0 & phi2>0); %-- Get mask from levelset\n seg12 = (phi1>0 & phi2<0);\n seg21 = (phi1<0 & phi2>0);\n seg22 = (phi1<0 & phi2<0);\n \n se = strel('disk',1);\n aa1 = imerode(seg11,se);\n aa2 = imerode(seg12,se);\n aa3 = imerode(seg21,se);\n aa4 = imerode(seg22,se);\n seg = aa1+2*aa2+3*aa3+4*aa4;\n if s<1\n seg = imresize(seg,[row col]);\n end\n subplot(2,2,4); imagesc(seg);axis image;title('Global Region-Based Segmentation');\n \n return\n end\n % re-initializations\n phi1 = reinitialization(phi1, 0.6);%sussman(phi1, 0.6);%\n phi2 = reinitialization(phi2, 0.6);%sussman(phi2,0.6);\n \n %intermediate output\n if(mod(n,20) == 0)\n phi(:,:,1) = phi1;\n phi(:,:,2) = phi2;\n showphi(I, phi, n);\n end;\n end;\n phi(:,:,1) = phi1;\n phi(:,:,2) = phi2;\n showphi(I, phi, n);\n %make mask from SDF\n seg11 = (phi1>0 & phi2>0); %-- Get mask from levelset\n seg12 = (phi1>0 & phi2<0);\n seg21 = (phi1<0 & phi2>0);\n seg22 = (phi1<0 & phi2<0);\n \n se = strel('disk',1);\n aa1 = imerode(seg11,se);\n aa2 = imerode(seg12,se);\n aa3 = imerode(seg21,se);\n aa4 = imerode(seg22,se);\n seg = aa1+2*aa2+3*aa3+4*aa4;\n %seg = bwlabel(seg);\n subplot(2,2,4); imagesc(seg);axis image;title('Global Region-Based Segmentation');\n \n \nend\nif s<1\n seg = imresize(seg,[row col]);\nend\nend\n\n", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/特征提取算法/DAPI_image_feature_extraction-master/chanvese/chenvese.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8333245953120234, "lm_q2_score": 0.6477982043529716, "lm_q1q2_score": 0.5398261764862955}} {"text": "function rVectECEF = getrVectEcefFromLatLongAlt(lat, long, alt, bodyInfo)\n r = bodyInfo.radius + alt;\n \n x = r.*cos(lat).*cos(long);\n y = r.*cos(lat).*sin(long);\n z = r.*sin(lat);\n \n rVectECEF = [x(:)';y(:)';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/fixed_frame/getrVectEcefFromLatLongAlt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.6187804407739559, "lm_q1q2_score": 0.5397914930113856}} {"text": "function varargout = sp_gen(varargin)\n%\n%\n% sp_gen is a GUI for generating Spirals.\n%\n%A. Select the plane that will be parallel to the spiral\n%B. Select the type of spiral:\n%You can choose from Archimedean,Logarithmic,Fermat,Hyperbolic,Lituus,Spherical and Polynomial Spirals.\n%you can see the equations used for the selected spiral, and change the parameters.\n%C. Select the normal component of the spiral. Note that this feature is\n%not available for the spherical spirals.\n%D. Add thickness to the spiral. This will provide volume and will give you\n%the possibility to generate surfaces. Note that this feature is not\n%available for the polynomial spirals.\n%E. Generate and export spiral variables to the workspace.\n%\n%%%%%%BUGS\n%\n%I am aware of the surface bug. This is clearly visible in the spherical\n%spiral, but also in the other spirals if you play with the normal\n%component.This is caused because the surface twists around itself. I\n%provide a partial correction, in function 'generate_thickness' in the 'if' \n%statement in lines 1128-1130.\n%\n% If anybody comes with a solution to this or finds other bugs, please post\n% on File EXchange. \n%\n%\n%Created by Katelouzos Ioannis.\n\n\ngui_Singleton = 1;\ngui_State = struct('gui_Name', mfilename, ...\n 'gui_Singleton', gui_Singleton, ...\n 'gui_OpeningFcn', @sp_gen_OpeningFcn, ...\n 'gui_OutputFcn', @sp_gen_OutputFcn, ...\n 'gui_LayoutFcn', [] , ...\n 'gui_Callback', []);\nif nargin && ischar(varargin{1})\n gui_State.gui_Callback = str2func(varargin{1});\nend\n\nif nargout\n [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});\nelse\n gui_mainfcn(gui_State, varargin{:});\nend\n% End initialization code - DO NOT EDIT\n\n\n% --- Executes just before sp_gen is made visible.\nfunction sp_gen_OpeningFcn(hObject, eventdata, handles, varargin)\n% This function has no output args, see OutputFcn.\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n% varargin command line arguments to sp_gen (see VARARGIN)\n\n% Choose default command line output for sp_gen\nhandles.output = hObject;\nhandles.plane=[0 0 1];\nvr=[[1 0;-1 0;0 1;0 -1]*null([0 0 1])';0 0 0];\nfc=[1 5 3;2 5 3;2 5 4;1 4 5];\nfv.vertices=vr;\nfv.faces=fc;\nhandles.fv=fv;\nhandles.xpl=zeros(3,3);\nhandles.ypl=zeros(3,3);\nhandles.zpl=zeros(3,3);\nhandles.surface=0;\nhandles.scloud=0;\nhandles.cloud=0;\nhandles.cerchi=[0;0;0];\nhandles.oct=zeros(8,3);\nhandles.spiral=zeros(3,1);\n% Update handles structure\nguidata(hObject, handles);\n\n% UIWAIT makes sp_gen wait for user response (see UIRESUME)\n% uiwait(handles.figure1);\n\n\n% --- Outputs from this function are returned to the command line.\nfunction varargout = sp_gen_OutputFcn(hObject, eventdata, handles) \n% varargout cell array for returning output args (see VARARGOUT);\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Get default command line output from handles structure\nvarargout{1} = handles.output;\n\n\n% --- Executes on selection change in spiral_type.\nfunction spiral_type_Callback(hObject, eventdata, handles)\n% hObject handle to spiral_type (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nval=(get(hObject,'Value'));\nzz=(get(handles.zcomp,'Value'));\nswitch val\n case 1\n set(handles.text15,'String','r = a + b * theta');\n set(handles.g,'Enable','off');\n set(handles.h,'Enable','off');\n set(handles.i,'Enable','off');\n set(handles.alpha,'Enable','on');\n set(handles.beta,'Enable','on');\n set(handles.zcomp,'Enable','on');\n set(handles.thick,'Enable','on');\n set(handles.surfface,'Enable','on');\n if zz~=1\n set(handles.c,'Enable','on');\n set(handles.d,'Enable','on');\n set(handles.e,'Enable','on');\n set(handles.f,'Enable','on');\n \n end\n case 2\n set(handles.text15,'String','r = a * exp( b * theta )');\n set(handles.g,'Enable','off');\n set(handles.h,'Enable','off');\n set(handles.i,'Enable','off');\n set(handles.alpha,'Enable','on');\n set(handles.beta,'Enable','on');\n set(handles.zcomp,'Enable','on');\n set(handles.thick,'Enable','on');\n set(handles.surfface,'Enable','on');\n if zz~=1\n set(handles.c,'Enable','on');\n set(handles.d,'Enable','on');\n set(handles.e,'Enable','on');\n set(handles.f,'Enable','on');\n \n end\n case 3 \n set(handles.text15,'String','r = +- sqrt( theta )');\n set(handles.g,'Enable','off');\n set(handles.h,'Enable','off');\n set(handles.i,'Enable','off');\n set(handles.alpha,'Enable','off');\n set(handles.beta,'Enable','off');\n set(handles.zcomp,'Enable','on');\n set(handles.thick,'Enable','on');\n set(handles.surfface,'Enable','on');\n if zz~=1\n set(handles.c,'Enable','on');\n set(handles.d,'Enable','on');\n set(handles.e,'Enable','on');\n set(handles.f,'Enable','on');\n \n end\n case 4\n set(handles.text15,'String','r = a / theta');\n set(handles.g,'Enable','off');\n set(handles.h,'Enable','off');\n set(handles.i,'Enable','off');\n set(handles.alpha,'Enable','on');\n set(handles.beta,'Enable','off');\n set(handles.zcomp,'Enable','on');\n set(handles.thick,'Enable','on');\n set(handles.surfface,'Enable','on');\n if zz~=1\n set(handles.c,'Enable','on');\n set(handles.d,'Enable','on');\n set(handles.e,'Enable','on');\n set(handles.f,'Enable','on');\n \n end\n case 5\n set(handles.text15,'String','r = sqrt( 1 / theta )');\n set(handles.g,'Enable','off');\n set(handles.h,'Enable','off');\n set(handles.i,'Enable','off');\n set(handles.alpha,'Enable','off');\n set(handles.beta,'Enable','off');\n set(handles.zcomp,'Enable','on');\n set(handles.thick,'Enable','on');\n set(handles.surfface,'Enable','on');\n if zz~=1\n set(handles.c,'Enable','on');\n set(handles.d,'Enable','on');\n set(handles.e,'Enable','on');\n set(handles.f,'Enable','on');\n \n end\n case 6\n set(handles.text15,'String','x=cos(t)cos(c) y=sin(t)cos(c) z=-sin(c) c=atan(a*t)');\n set(handles.g,'Enable','off');\n set(handles.h,'Enable','off');\n set(handles.i,'Enable','off');\n set(handles.alpha,'Enable','on');\n set(handles.beta,'Enable','off');\n set(handles.zcomp,'Enable','off');\n set(handles.c,'Enable','off');\n set(handles.d,'Enable','off');\n set(handles.e,'Enable','off');\n set(handles.f,'Enable','off');\n set(handles.thick,'Enable','on');\n set(handles.surfface,'Enable','on');\n otherwise\n set(handles.text15,'String','curvature = f(curve length) k=a*s^4+b*s^3+g*s^2+h*s+i');\n set(handles.g,'Enable','on');\n set(handles.h,'Enable','on');\n set(handles.i,'Enable','on');\n set(handles.alpha,'Enable','on');\n set(handles.beta,'Enable','on');\n set(handles.zcomp,'Enable','on');\n set(handles.thick,'Enable','off');\n set(handles.surfface,'Enable','off');\n if zz~=1\n set(handles.c,'Enable','on');\n set(handles.d,'Enable','on');\n set(handles.e,'Enable','on');\n set(handles.f,'Enable','on');\n end\n\nend\nguidata(hObject, handles);\n% Hints: contents = get(hObject,'String') returns spiral_type contents as cell array\n% contents{get(hObject,'Value')} returns selected item from spiral_type\n\n\n% --- Executes during object creation, after setting all properties.\nfunction spiral_type_CreateFcn(hObject, eventdata, handles)\n% hObject handle to spiral_type (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: popupmenu controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n\nfunction Xeq_Callback(hObject, eventdata, handles)\n% hObject handle to Xeq (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\npl=handles.plane;\nx=str2double(get(hObject,'String'));\nif pl(3)==0 && pl(2)==0, x=1;\nset(hObject,'String','1');\nend\nhandles.plane(1)=x;\nhandles=refresh_plane(handles);\nguidata(hObject, handles);\n% Hints: get(hObject,'String') returns contents of Xeq as text\n% str2double(get(hObject,'String')) returns contents of Xeq as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction Xeq_CreateFcn(hObject, eventdata, handles)\n% hObject handle to Xeq (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nhandles.plane(1)=str2double(get(hObject,'String'));\nguidata(hObject, handles);\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n\nfunction Yeq_Callback(hObject, eventdata, handles)\n% hObject handle to Yeq (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\npl=handles.plane;\nx=str2double(get(hObject,'String'));\nif pl(1)==0 && pl(3)==0, x=1;\nset(hObject,'String','1');\nend\nhandles.plane(2)=x;\nhandles=refresh_plane(handles);\nguidata(hObject, handles);\n% Hints: get(hObject,'String') returns contents of Yeq as text\n% str2double(get(hObject,'String')) returns contents of Yeq as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction Yeq_CreateFcn(hObject, eventdata, handles)\n% hObject handle to Yeq (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nhandles.plane(2)=str2double(get(hObject,'String'));\nguidata(hObject, handles);\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n\nfunction Zeq_Callback(hObject, eventdata, handles)\n% hObject handle to Zeq (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of Zeq as text\n% str2double(get(hObject,'String')) returns contents of Zeq as a double\npl=handles.plane;\nx=str2double(get(hObject,'String'));\nif pl(1)==0 && pl(2)==0, x=1;\nset(hObject,'String','1');\nend\nhandles.plane(3)=x;\nhandles=refresh_plane(handles);\nguidata(hObject, handles);\n\n% --- Executes during object creation, after setting all properties.\nfunction Zeq_CreateFcn(hObject, eventdata, handles)\n% hObject handle to Zeq (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nhandles.plane(3)=str2double(get(hObject,'String'));\nguidata(hObject, handles);\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n% --- Executes on button press in show_plane.\nfunction show_plane_Callback(hObject, eventdata, handles)\n% hObject handle to show_plane (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nhandles=refresh_plane(handles);\nguidata(hObject, handles);\n% Hint: get(hObject,'Value') returns toggle state of show_plane\n\n\n\nfunction thick_Callback(hObject, eventdata, handles)\n% hObject handle to thick (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nx=str2double(get(hObject,'String'));\nif x<0;\nset(hObject,'String','0');\nend\nguidata(hObject, handles);\n% Hints: get(hObject,'String') returns contents of thick as text\n% str2double(get(hObject,'String')) returns contents of thick as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction thick_CreateFcn(hObject, eventdata, handles)\n% hObject handle to thick (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n\nfunction lengt_Callback(hObject, eventdata, handles)\n% hObject handle to lengt (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of lengt as text\n% str2double(get(hObject,'String')) returns contents of lengt as a double\n\nx=str2double(get(hObject,'String'));\npr=str2double(get(handles.precision,'String'));\nif x<=2*pr;\npr=str2double(get(handles.precision,'String'));\nset(hObject,'String',sprintf('%g', pr*2));\nend\nguidata(hObject, handles);\n\n\n% --- Executes during object creation, after setting all properties.\nfunction lengt_CreateFcn(hObject, eventdata, handles)\n% hObject handle to lengt (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\nfunction h=refresh_plane(handles)\ncpos=get(handles.axes1,'CameraPosition');\npl=handles.plane;\n vr=[[1 0;-1 0;0 1;0 -1;1 1; 1 -1;-1 -1;-1 1]*null(pl)';0 0 0];\nfv.vertices=vr;\nxpl=[vr(8,1) vr(3,1) vr(5,1);vr(2,1) vr(9,1) vr(1,1);vr(7,1) vr(4,1) vr(6,1)];\nypl=[vr(8,2) vr(3,2) vr(5,2);vr(2,2) vr(9,2) vr(1,2);vr(7,2) vr(4,2) vr(6,2)];\nzpl=[vr(8,3) vr(3,3) vr(5,3);vr(2,3) vr(9,3) vr(1,3);vr(7,3) vr(4,3) vr(6,3)];\nhandles.xpl=xpl;\nhandles.ypl=ypl;\nhandles.zpl=zpl;\nspir=handles.spiral;\n\nif isempty(find(spir));\n mm=1;\nelse mm=max(max(abs(spir)));\nend\nxpl=xpl.*mm/2;\nypl=ypl.*mm/2;\nzpl=zpl.*mm/2;\nplot3(spir(1,:),spir(2,:),spir(3,:));\nhold on;\nif get(handles.show_plane,'Value')==1\n mesh(xpl,ypl,zpl,'FaceAlpha',0.1,'FaceColor','g','EdgeAlpha',0.5,'EdgeColor','k');\nend\nset(handles.axes1,'CameraPosition',cpos);\nset(handles.axes1,'DataAspectRatio',[1 1 1]);\nset(get(handles.axes1,'XLabel'),'String','X','Color','r','FontWeight','bold');\nset(get(handles.axes1,'YLabel'),'String','Y','Color','r','FontWeight','bold');\nset(get(handles.axes1,'ZLabel'),'String','Z','Color','r','FontWeight','bold');\nhold off;\nh=handles;\n\n\n% --- Executes on button press in export_internal.\nfunction export_internal_Callback(hObject, eventdata, handles)\n% hObject handle to export_internal (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\ncloud=handles.cloud;\nassignin('base','Spiral_IntCloud',cloud);\n\n\n% --- Executes on button press in show_scloud.\nfunction show_scloud_Callback(hObject, eventdata, handles)\n% hObject handle to show_scloud (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nset(handles.export_scloud,'BackgroundColor',[0 1 0]);\nset(handles.export_scloud,'Enable','on');\nH=figure(2);\ntitle('Surface Cloud Ordinary','Color','b','FontWeight','bold');\noct=handles.oct;\nhold on;\nfor it=1:length(oct(1,1,:))\n plot3(oct(:,1,it),oct(:,2,it),oct(:,3,it),'.');\nend\nset(get(H,'CurrentAxes'),'DataAspectRatio',[1 1 1]);\nset(get(get(H,'CurrentAxes'),'XLabel'),'String','X','Color','r','FontWeight','bold');\nset(get(get(H,'CurrentAxes'),'YLabel'),'String','Y','Color','r','FontWeight','bold');\nset(get(get(H,'CurrentAxes'),'ZLabel'),'String','Z','Color','r','FontWeight','bold');\nhold off;\nH=figure(3);\ntitle('Surface Cloud Random','Color','b','FontWeight','bold');\nscloud=gen_scloud(handles,oct);\nhandles.scloud=scloud;\nhold on;\nplot3(scloud(:,1),scloud(:,2),scloud(:,3),'.');\nset(get(H,'CurrentAxes'),'DataAspectRatio',[1 1 1]);\nset(get(get(H,'CurrentAxes'),'XLabel'),'String','X','Color','r','FontWeight','bold');\nset(get(get(H,'CurrentAxes'),'YLabel'),'String','Y','Color','r','FontWeight','bold');\nset(get(get(H,'CurrentAxes'),'ZLabel'),'String','Z','Color','r','FontWeight','bold');\nhold off;\nguidata(hObject, handles);\n\n\n% --- Executes on button press in show_surface.\nfunction show_surface_Callback(hObject, eventdata, handles)\n% hObject handle to show_surface (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nset(handles.export_surface,'BackgroundColor',[0 1 0]);\nset(handles.export_surface,'Enable','on');\nH=figure(4);\n\noct=handles.oct;\nC = permute(cat(1, oct, oct(1,:,:)),[3,1,2]);\nxsurf=squeeze(C(:,:,1));\nysurf=squeeze(C(:,:,2));\nzsurf=squeeze(C(:,:,3));\nsurface.x=xsurf;\nsurface.y=ysurf;\nsurface.z=zsurf;\nhandles.surface=surface;\nmesh(xsurf,ysurf,zsurf,'FaceAlpha',0.1,'FaceColor','g','EdgeAlpha',0.5,'EdgeColor','k');\ntitle('Surface','Color','b','FontWeight','bold');\nset(get(H,'CurrentAxes'),'DataAspectRatio',[1 1 1]);\nset(get(get(H,'CurrentAxes'),'XLabel'),'String','X','Color','r','FontWeight','bold');\nset(get(get(H,'CurrentAxes'),'YLabel'),'String','Y','Color','r','FontWeight','bold');\nset(get(get(H,'CurrentAxes'),'ZLabel'),'String','Z','Color','r','FontWeight','bold');\nguidata(hObject, handles);\n\n\n% --- Executes on button press in show_internal.\nfunction show_internal_Callback(hObject, eventdata, handles)\n% hObject handle to show_internal (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nset(handles.export_internal,'BackgroundColor',[0 1 0]);\nset(handles.export_internal,'Enable','on');\nH=figure(1);\ntitle('Internal Cloud','Color','b','FontWeight','bold');\noct=handles.oct;\n\ncloud=gen_cloud(handles,oct);\nhandles.cloud=cloud;\nhold on;\nplot3(cloud(:,1),cloud(:,2),cloud(:,3),'.');\nset(get(H,'CurrentAxes'),'DataAspectRatio',[1 1 1]);\nset(get(get(H,'CurrentAxes'),'XLabel'),'String','X','Color','r','FontWeight','bold');\nset(get(get(H,'CurrentAxes'),'YLabel'),'String','Y','Color','r','FontWeight','bold');\nset(get(get(H,'CurrentAxes'),'ZLabel'),'String','Z','Color','r','FontWeight','bold');\nhold off;\nguidata(hObject, handles);\n\n\n% --- Executes on button press in export_scloud.\nfunction export_scloud_Callback(hObject, eventdata, handles)\n% hObject handle to export_scloud (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\noct=handles.oct;\nscloud=handles.scloud;\nB = permute(oct,[1 3 2]);\nou = reshape(B,length(oct(:,1,1))*size(oct,3),3);\nassignin('base','Spiral_SurCloud_ord',ou);\nassignin('base','Spiral_SurCloud_rand',scloud);\n\n\n% --- Executes on button press in export_surface.\nfunction export_surface_Callback(hObject, eventdata, handles)\n% hObject handle to export_surface (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nsurface=handles.surface;\nassignin('base','Spiral_Surface',surface);\n\n\n% --- Executes on button press in export_line.\nfunction export_line_Callback(hObject, eventdata, handles)\n% hObject handle to export_line (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nassignin('base','Spiral_line',handles.spiral);\n\n\n% --- Executes on button press in gen_spiral.\nfunction gen_spiral_Callback(hObject, eventdata, handles)\n% hObject handle to gen_spiral (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\ncpos=get(handles.axes1,'CameraPosition');\nstype=get(handles.spiral_type,'Value');\nalpha=str2double(get(handles.alpha,'String'));\nbeta=str2double(get(handles.beta,'String'));\nc=str2double(get(handles.c,'String'));\nd=str2double(get(handles.d,'String'));\ne=str2double(get(handles.e,'String'));\nf=str2double(get(handles.f,'String'));\ng=str2double(get(handles.g,'String'));\nh=str2double(get(handles.h,'String'));\ni=str2double(get(handles.i,'String'));\nthick=str2double(get(handles.thick,'String'));\npr=str2double(get(handles.precision,'String'));\nlengt=str2double(get(handles.lengt,'String'));\ntheta=0:pr:lengt*pi;\nswitch stype\n case 1\n r=alpha+beta*theta;\n case 2\n r=alpha*(exp(beta*theta));\n case 3\n r=sqrt(theta);\n r2=-r;\n case 4\n r=alpha./theta;\n case 5\n r=sqrt(1./theta);\n case 6\n t=-lengt:pr:lengt;\n c=atan(alpha*t);\n x=cos(t).*cos(c); \n y=sin(t).*cos(c);\n z=-sin(c); \n [theta,r]=cart2pol(x,y);\n otherwise\n if alpha>0\n l=sqrt(lengt);\n p=pr^2;\n else \n l=lengt;\n p=pr;\n end\n [x y]=curv2cart(alpha,beta,g,h,i,l,p,handles);\n [theta,r]=cart2pol(x,y);\nend\nzc=(get(handles.zcomp,'Value'));\nif stype~=6\nswitch zc\n case 1\n z=zeros(1,length(theta));\n case 2\n z=c*r.^d+e*theta.^f;\n case 3 \n z = c*sin(r.*d) + e*sin(theta.*f);\n case 4\n z = c*exp(d*r) + e*exp(f*theta);\n otherwise\n z = c*log(r).^d + e*log(theta).^f;\nend\nend\nif stype==4 || stype==5\n theta=theta(end:-1:2);\n r=r(end:-1:2);\n z=z(end:-1:2);\nend\n[x,y]=pol2cart(theta,r);\nspiral=[x;y;z];\nif stype==3 \n [x2,y2]=pol2cart(theta,r2);\n z2=-z;\n spiral=[fliplr(x2) x(2:end);fliplr(y2) y(2:end);fliplr(z2) z(2:end)];\nend\npl=handles.plane;\nrotate= vrrotvec([0 0 1],pl);\nrm = vrrotvec2mat(rotate);\nspir=rm*spiral;\nnnn=sum(spir,1);\nw=nnn==nnn;\nw=find(w==0);\nspir(:,w)=[];\nhandles.spiral=spir;\nif ~isempty(find(spir))\n refresh_plane(handles);\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%% cerchiles generation\nhold on;\nif thick>0\n if stype==1 || stype==2 || stype ==6 ||stype==4 ||stype==5\n [cerchi oct]=generate_thickness(1,handles);\n elseif stype==3\n [cerchi oct]=generate_thickness(2,handles);\n else %stype==7\n cerchi=[0;0;0];\n oct=zeros(8,3);\n end\nhandles.cerchi=cerchi;\nhandles.oct=oct;\nend\nend\nset(handles.axes1,'CameraPosition',cpos);\nset(handles.axes1,'DataAspectRatio',[1 1 1]);\nset(get(handles.axes1,'XLabel'),'String','X','Color','r','FontWeight','bold');\nset(get(handles.axes1,'YLabel'),'String','Y','Color','r','FontWeight','bold');\nset(get(handles.axes1,'ZLabel'),'String','Z','Color','r','FontWeight','bold');\nhold off;\nif stype ~= 7 && thick >0\nset(handles.show_internal,'BackgroundColor',[0 1 0]);\nset(handles.show_internal,'Enable','on');\nset(handles.show_scloud,'BackgroundColor',[0 1 0]);\nset(handles.show_scloud,'Enable','on');\nset(handles.show_surface,'BackgroundColor',[0 1 0]);\nset(handles.show_surface,'Enable','on');\nset(handles.export_line,'BackgroundColor',[0 1 0]);\nset(handles.export_line,'Enable','on');\nset(handles.export_internal,'BackgroundColor',[1 0 0]);\nset(handles.export_internal,'Enable','off');\nset(handles.export_scloud,'BackgroundColor',[1 0 0]);\nset(handles.export_scloud,'Enable','off');\nset(handles.export_surface,'BackgroundColor',[1 0 0]);\nset(handles.export_surface,'Enable','off');\nelse\n set(handles.show_internal,'BackgroundColor','r');\nset(handles.show_internal,'Enable','off');\nset(handles.show_scloud,'BackgroundColor','r');\nset(handles.show_scloud,'Enable','off');\nset(handles.show_surface,'BackgroundColor','r');\nset(handles.show_surface,'Enable','off');\nset(handles.export_line,'BackgroundColor',[0 1 0]);\nset(handles.export_line,'Enable','on');\nset(handles.export_internal,'BackgroundColor','r');\nset(handles.export_internal,'Enable','off');\nset(handles.export_scloud,'BackgroundColor','r');\nset(handles.export_scloud,'Enable','off');\nset(handles.export_surface,'BackgroundColor','r');\nset(handles.export_surface,'Enable','off');\nend\nguidata(hObject, handles);\n\n\n\nfunction alpha_Callback(hObject, eventdata, handles)\n% hObject handle to alpha (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of alpha as text\n% str2double(get(hObject,'String')) returns contents of alpha as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction alpha_CreateFcn(hObject, eventdata, handles)\n% hObject handle to alpha (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n\nfunction beta_Callback(hObject, eventdata, handles)\n% hObject handle to beta (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of beta as text\n% str2double(get(hObject,'String')) returns contents of beta as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction beta_CreateFcn(hObject, eventdata, handles)\n% hObject handle to beta (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n% --- Executes on selection change in zcomp.\nfunction zcomp_Callback(hObject, eventdata, handles)\n% hObject handle to zcomp (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nval=(get(hObject,'Value'));\nswitch val\n case 1\n set(handles.text20,'String','z = 0');\n set(handles.c,'Enable','off');\n set(handles.d,'Enable','off');\n set(handles.e,'Enable','off');\n set(handles.f,'Enable','off'); \n case 2\n set(handles.text20,'String','z = c*r^d + e*theta^f');\n set(handles.c,'Enable','on');\n set(handles.d,'Enable','on');\n set(handles.e,'Enable','on');\n set(handles.f,'Enable','on');\n case 3 \n set(handles.text20,'String','z = c*sin(r*d) + e*sin(theta*f)');\n set(handles.c,'Enable','on');\n set(handles.d,'Enable','on');\n set(handles.e,'Enable','on');\n set(handles.f,'Enable','on');\n case 4\n set(handles.text20,'String','z = c*exp(d*r) + e*exp(f*theta)');\n set(handles.c,'Enable','on');\n set(handles.d,'Enable','on');\n set(handles.e,'Enable','on');\n set(handles.f,'Enable','on');\n otherwise\n set(handles.text20,'String','z = c*log(r)^d + e*log(theta)^f');\n set(handles.c,'Enable','on');\n set(handles.d,'Enable','on');\n set(handles.e,'Enable','on');\n set(handles.f,'Enable','on');\nend\nguidata(hObject, handles);\n% Hints: contents = get(hObject,'String') returns zcomp contents as cell array\n% contents{get(hObject,'Value')} returns selected item from zcomp\n\n\n% --- Executes during object creation, after setting all properties.\nfunction zcomp_CreateFcn(hObject, eventdata, handles)\n% hObject handle to zcomp (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: popupmenu controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n\nfunction e_Callback(hObject, eventdata, handles)\n% hObject handle to e (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of e as text\n% str2double(get(hObject,'String')) returns contents of e as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction e_CreateFcn(hObject, eventdata, handles)\n% hObject handle to e (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n\nfunction f_Callback(hObject, eventdata, handles)\n% hObject handle to f (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of f as text\n% str2double(get(hObject,'String')) returns contents of f as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction f_CreateFcn(hObject, eventdata, handles)\n% hObject handle to f (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n\nfunction c_Callback(hObject, eventdata, handles)\n% hObject handle to c (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of c as text\n% str2double(get(hObject,'String')) returns contents of c as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction c_CreateFcn(hObject, eventdata, handles)\n% hObject handle to c (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n\nfunction d_Callback(hObject, eventdata, handles)\n% hObject handle to d (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of d as text\n% str2double(get(hObject,'String')) returns contents of d as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction d_CreateFcn(hObject, eventdata, handles)\n% hObject handle to d (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n\nfunction g_Callback(hObject, eventdata, handles)\n% hObject handle to g (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of g as text\n% str2double(get(hObject,'String')) returns contents of g as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction g_CreateFcn(hObject, eventdata, handles)\n% hObject handle to g (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n\nfunction h_Callback(hObject, eventdata, handles)\n% hObject handle to h (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of h as text\n% str2double(get(hObject,'String')) returns contents of h as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction h_CreateFcn(hObject, eventdata, handles)\n% hObject handle to h (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n\nfunction i_Callback(hObject, eventdata, handles)\n% hObject handle to i (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of i as text\n% str2double(get(hObject,'String')) returns contents of i as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction i_CreateFcn(hObject, eventdata, handles)\n% hObject handle to i (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\nfunction [xo yo]=curv2cart(a,b,c,d,e,l,p,handles)\nset(handles.timebar_text,'Visible','on','String','Generating Spiral');\ndrawnow update\ns=0:p:l;\ns2=-s;\nx1=zeros(1,length(s));\ny1=zeros(1,length(s));\nx2=zeros(1,length(s));\ny2=zeros(1,length(s));\nk=a*s.^4+b*s.^3+c*s.^2+d*s+e;\nk2=a*s2.^4+b*s2.^3+c*s2.^2+d*s2+e;\nx1(2)=s(2);\ny1(2)=0;\nx2(2)=s2(2);\ny2(2)=0;\nperc=(length(s)*2-4)/100;\nls=length(s)-2;\nfor i=3:(length(s))\n sss=sprintf('Genetaring Spiral...%3.1f %%', i/perc);\n set(handles.timebar_text,'String',sss);\n drawnow update\n dth=k(i)*s(2);\n cth=(x1(i-1)-x1(i-2))/norm([x1(i-1) y1(i-1)]-[x1(i-2) y1(i-2)]);\n sth=(y1(i-1)-y1(i-2))/norm([x1(i-1) y1(i-1)]-[x1(i-2) y1(i-2)]);\n if sth>=0\n scorr=1;\n else scorr=-1;\n end\n newth=dth+scorr*acos(cth);\n xx=cos(newth);\n yy=sin(newth);\n x1(i)=(xx*s(2))+x1(i-1);\n y1(i)=(yy*s(2))+y1(i-1);\nend\n\nfor i=3:(length(s))\n sss=sprintf('Genetaring Spiral...%3.1f %%', (i+ls)/perc);\n set(handles.timebar_text,'String',sss);\n drawnow update\n dth=k2(i)*s2(2);\n cth=(x2(i-1)-x2(i-2))/norm([x2(i-1) y2(i-1)]-[x2(i-2) y2(i-2)]);\n sth=(y2(i-1)-y2(i-2))/norm([x2(i-1) y2(i-1)]-[x2(i-2) y2(i-2)]);\n if sth>=0\n scorr=1;\n else scorr=-1;\n end\n newth=dth+scorr*acos(cth);\n xx=cos(newth);\n yy=sin(newth);\n x2(i)=(xx*s(2))+x2(i-1);\n y2(i)=(yy*s(2))+y2(i-1);\nend\nset(handles.timebar_text,'Visible','off');\nxo=[fliplr(x2) x1];\nyo=[fliplr(y2) y1];\n\n\n\nfunction precision_Callback(hObject, eventdata, handles)\n% hObject handle to precision (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nx=str2double(get(hObject,'String'));\nl=str2double(get(handles.lengt,'String'));\nif x<=0 \n set(hObject,'String','0.1');\n x=0.1;\nelseif x>1 \n set(hObject,'String','1');\n x=1;\nend\n if l<=2*x\n set(hObject,'String',sprintf('%g', l/2));\n end\n\nguidata(hObject, handles);\n\n% Hints: get(hObject,'String') returns contents of precision as text\n% str2double(get(hObject,'String')) returns contents of precision as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction precision_CreateFcn(hObject, eventdata, handles)\n% hObject handle to precision (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n% --- Executes on button press in clear.\nfunction clear_Callback(hObject, eventdata, handles)\n% hObject handle to clear (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n set(handles.text20,'String','z = 0');\n set(handles.c,'Enable','off');\n set(handles.d,'Enable','off');\n set(handles.e,'Enable','off');\n set(handles.f,'Enable','off');\n set(handles.text15,'String','r = a + b * theta');\n set(handles.g,'Enable','off');\n set(handles.h,'Enable','off');\n set(handles.i,'Enable','off');\n set(handles.alpha,'Enable','on');\n set(handles.beta,'Enable','on');\n set(handles.zcomp,'Enable','on');\n set(handles.spiral_type,'Value',1);\n set(handles.zcomp,'Value',1);\n set(handles.thick,'Enable','on');\n set(handles.surfface,'Enable','on');\nhandles.plane=[0 0 1];\nset(handles.Xeq,'String','0');\nset(handles.Yeq,'String','0');\nset(handles.Zeq,'String','1');\nvr=[[1 0;-1 0;0 1;0 -1]*null([0 0 1])';0 0 0];\nfc=[1 5 3;2 5 3;2 5 4;1 4 5];\nfv.vertices=vr;\nfv.faces=fc;\nhandles.fv=fv;\nhandles.cerchi=[0;0;0];\nhandles.oct=zeros(8,3);\nhandles.surface=0;\nhandles.scloud=0;\nhandles.cloud=0;\nhandles.spiral=zeros(3,1);\nset(handles.show_internal,'BackgroundColor','r');\nset(handles.show_internal,'Enable','off');\nset(handles.show_scloud,'BackgroundColor','r');\nset(handles.show_scloud,'Enable','off');\nset(handles.show_surface,'BackgroundColor','r');\nset(handles.show_surface,'Enable','off');\nset(handles.export_line,'BackgroundColor','r');\nset(handles.export_line,'Enable','off');\nset(handles.export_internal,'BackgroundColor','r');\nset(handles.export_internal,'Enable','off');\nset(handles.export_scloud,'BackgroundColor','r');\nset(handles.export_scloud,'Enable','off');\nset(handles.export_surface,'BackgroundColor','r');\nset(handles.export_surface,'Enable','off');\nguidata(hObject, handles);\nrefresh_plane(handles);\nguidata(hObject, handles);\n\nfunction [cerchi oct]=generate_thickness(a,handles)\nsurfface=str2double(get(handles.surfface,'String'));\nstype=get(handles.spiral_type,'Value');\nthick=str2double(get(handles.thick,'String'));\nspir=handles.spiral;\nset(handles.timebar_text,'Visible','on','String','Generating Thickness');\ndrawnow update;\nif a==1\ncerchi=[[0;0;0] spir(:,2:end)-spir(:,1:end-1)];\nstart=2;\nelse cerchi=spir(:,2:(end+1)/2)-spir(:,1:(end+1)/2-1);\n start=1;\nend\noct=zeros(surfface,3,length(cerchi)); \nperc=(length(cerchi)-1)/100;\n for it=start:length(cerchi)\n sss=sprintf('Genetaring Thickness...%3.1f %%', it/perc);\n set(handles.timebar_text,'String',sss);\n drawnow update;\n cerc=cerchi(:,it);\n mm=norm(cerc)*thick;\n nullity=(null(cerc'))';\n if dot(cerc,[1 0 0])>0 \n nullity=[-1 0;0 1]*nullity;\n end\n vects=gen_polygon(handles,surfface,mm);\n piu=zeros(3,surfface);\n piu=bsxfun(@plus,piu,spir(:,it));\n oct(:,:,it)=vects*nullity+piu';\n end\nif a==2\n oct(:,:,end)=oct(:,:,end)-vects*nullity/2;\n cerchi=[cerchi fliplr(-cerchi)];\n oct= cat(3, oct, flipdim(-oct,3));\nend\nif stype==6\n piu=zeros(3,surfface);\n piu=bsxfun(@plus,piu,spir(:,1));\n oct(:,:,1)=piu';\n piu=zeros(3,surfface);\n piu=bsxfun(@plus,piu,spir(:,end));\n oct(:,:,end)=piu';\nend\n\nfor it=start:length(cerchi)\n plot3(oct(:,1,it),oct(:,2,it),oct(:,3,it));\nend\nset(handles.timebar_text,'Visible','off');\n\n\n\nfunction surfface_Callback(hObject, eventdata, handles)\n% hObject handle to surfface (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of surfface as text\n% str2double(get(hObject,'String')) returns contents of surfface as a double\nx=floor(str2double(get(hObject,'String')));\nif x<4;\nx=4;\nend\nsss=sprintf('%d', x);\nset(hObject,'String',sss);\nguidata(hObject, handles);\n\n\n% --- Executes during object creation, after setting all properties.\nfunction surfface_CreateFcn(hObject, eventdata, handles)\n% hObject handle to surfface (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\nfunction vects=gen_polygon(handles,surfface,mm)\ndiv=0:2*pi/surfface:2*pi-2*pi/surfface;\nvects=[cos(div')*mm sin(div')*mm];\n\nfunction scloud=gen_scloud(handles,oct)\nset(handles.timebar_text,'Visible','on','String','Generating Thickness');\ndrawnow update;\nfaces=length(oct(:,1,1))-1;\nperc=(length(oct(1,1,:))-1)*faces/100;\noct=cat(1, oct, oct(1,:,:));\npl=1;\nscloud=zeros(2*perc*100,3);\nfor slength=1:length(oct(1,1,:))-1\nfor polygon=1:faces\n it=(slength-1)*faces+polygon;\n sss=sprintf('Genetaring Surface Cloud...%3.1f %%', it/perc);\n set(handles.timebar_text,'String',sss);\n drawnow update;\np1=oct(polygon,:,slength);\np2=oct(polygon+1,:,slength);\np3=oct(polygon+1,:,slength+1);\np4=oct(polygon,:,slength+1);\np=[p1;p2;p3;p4];\n[or,in]=min([norm(p1);norm(p2);norm(p3);norm(p4)]);\np=circshift(p,-in+1);\ndx=p(2,:)-p(1,:);\ndy=p(4,:)-p(1,:);\nx1=p(1,:)/2+dx*rand;\ny1=p(1,:)/2+dy*rand;\npp1=x1+y1;\nx2=p(1,:)/2+dx*rand;\ny2=p(1,:)/2+dy*rand;\npp2=x2+y2;\nscloud(pl,:)=pp1;\npl=pl+1;\nscloud(pl,:)=pp2;\npl=pl+1;\nend\nend\n\n\nfunction cloud=gen_cloud(handles,oct)\nset(handles.timebar_text,'Visible','on','String','Generating Internal Cloud');\ndrawnow update;\nfaces=length(oct(:,1,1));\nperc=(length(oct(1,1,:)))*faces/100;\noct=cat(1, oct, oct(1,:,:));\npl=1;\nj=2; % j*faces is the number of points in every spital slice\npp=zeros(j*perc*100,3);\n\nfor slength=1:length(oct(1,1,:))-1\nfor polygon=1:faces-1\n it=(slength-1)*faces+polygon;\n sss=sprintf('Genetaring Internal Cloud...%3.1f %%', it/perc);\n set(handles.timebar_text,'String',sss);\n drawnow update;\n apenanti=mod(floor(faces/2)+polygon+1,faces);\n if apenanti==0,apenanti=faces;end\np1=oct(polygon+1,:,slength);\np2=oct(polygon,:,slength);\np3=oct(apenanti,:,slength);\np4=oct(apenanti,:,slength+1);\np5=oct(polygon+1,:,slength+1);\np6=oct(polygon,:,slength+1);\np=[p1;p2;p3;p4;p5;p6];\n\ndy=p2-p1;\ndz=p3-p1;\ndx=p5-p1;\n\nfor k=1:j\ndyp=dy*rand;\ndxp=dx*rand;\ndzn=norm(dy-dyp)*norm(dz)/norm(dy);\ndzp=dz./norm(dz)*rand*dzn;\npp(pl,:)=p(1,:)+dzp+dxp+dyp;\npl=pl+1;\nend\nend\nend\ncloud=pp;\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/23192-spiral-generator/sp_del/sp_gen.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.5397255448856835}} {"text": "% Demo: on-line design optimization for DCM of fMRI data.\n% This demo simplifies the network identification of Friston et al. (2003).\n% In brief, photic input enters V1, which is reciprocally connected to V5.\n% The goal of the experiment is to assess whether attention modulates the\n% feedforward connection from V1 to V5. This is addressed using Bayesian\n% model comparison given fMRI data (i.e. model 1: attention modulates the\n% V1->V5 connection; model 2: no modulatory effect). Within the session,\n% each block consists of 16 seconds of stimulation and 16 of rest. The\n% on-line design optimization consists in deciding, before each block,\n% whether we modulate subjects' attention. This is done by comparing the\n% design efficiency of two canonical block designs (i.e. with and without\n% attentional modulation).\n% NB: the procedure is adaptative, because it updates the posterior on\n% unknown model parameters after each block. This is why the design\n% efficiency inceases across time.\n\n\n\nclose all\nclear variables\n\n\n% Basic settings\nn_t = 16; % number of time samples per block\nnblocks = 10; % number of blocks\nnreg = 2; % number of regions\nTR = 3e0; % sampling period (in sec)\nmicroDT = 5e-2; % micro-time resolution (in sec)\nf_fname = @f_DCMwHRF;\ng_fname = @g_HRF3;\n\n\n% construct atomic designs\nnu = 2;\nu1 = [0,ones(1,floor(n_t/2))];\nu1(end:n_t) = 0;\nu2 = zeros(1,n_t);\nu = {[u1;u2];[u1;u1]}; % u{1}/u{2}: w/wo attentinal modulation\n\nnm = 2; % # candidate models (see below)\ntruemodel = 1; % index of true model (which generates the data)\n\n\n% model 1: u_att modulates connection from V1 to V5\nA = [0 1\n 1 0];\nB{1} = zeros(nreg,nreg);\nB{2} = zeros(nreg,nreg);\nB{2}(2,1) = 1;\nC = [1 0\n 0 0];\nD{1} = [0 0\n 0 0];\nD{2} = zeros(nreg,nreg);\nD{3} = zeros(nreg,nreg);\n[o4design{1},dim{1}] = getOptions4dcm(A,B,C,D,TR,microDT,n_t,1,1,1);\n\n\n% model 1: no modulatory effect of attention\nA = [0 1\n 1 0];\nnreg = size(A,1);\nB{1} = zeros(nreg,nreg);\nB{2} = zeros(nreg,nreg);\nC = [1 0\n 0 0];\nD{1} = [0 0\n 0 0];\nD{2} = zeros(nreg,nreg);\nD{3} = zeros(nreg,nreg);\n[o4design{2},dim{2}] = getOptions4dcm(A,B,C,D,TR,microDT,n_t,1,1,1);\n\n\no4design{truemodel}.verbose = 0;\n\n% simu parameters\nt_A = exp([ -0.5\n -0.5\n ]);\nt_Aself = -0;\nt_B{1} = [];\nt_B{2} = exp([ -0.5 ]);\nt_C = exp([ -0.5 ]);\nt_D{1} = [];\nt_D{2} = [];\ntheta = zeros(dim{truemodel}.n_theta,1);\nphi = zeros(dim{truemodel}.n_phi,1);\ntheta(o4design{truemodel}.inF.indA) = t_A;\nfor i=1:nu\n theta(o4design{truemodel}.inF.indB{i}) = t_B{i};\nend\ntheta(o4design{truemodel}.inF.indC) = t_C;\nalpha = Inf; % state noise precision\nsigma = 5e-1; % measurement noise precision\nx0 = zeros(dim{truemodel}.n,1); % initial conditions\n\n\n% prepare graphics & montoring variables\nhf = figure('color',[1 1 1]);\nha = subplot(3,2,1,'parent',hf,'nextplot','add','xlim',[1 nblocks+1]);\nxlabel(ha,'time (blocks)')\nylabel(ha,'design efficiency')\nha2 = subplot(3,2,3,'parent',hf,'nextplot','add','xlim',[1 n_t*nblocks]);\nxlabel(ha2,'time (scans)')\nylabel(ha2,'BOLD signal')\nha3 = subplot(3,2,2,'parent',hf,'nextplot','add','xlim',[1 nblocks+1]);\nxlabel(ha3,'time (blocks)')\nylabel(ha3,'log p(y|m_1) -log p(y|m_2)')\ne = zeros(2,1);\nY = zeros(dim{truemodel}.p,n_t*nblocks);\nU = zeros(2,n_t*nblocks);\nF = zeros(2,nblocks);\neb = zeros(1,nblocks);\nvb = zeros(1,nblocks);\n\n% on-line experiment\n\nfor tt=1:nblocks\n \n % 1- find best design given current information\n fprintf(1,'\\n')\n fprintf(1,['-- Optimizing design (block ',num2str(tt),')...'])\n fprintf(1,'\\n')\n for i=1:length(u) %loops over experimental designs\n fprintf(1,['- Candidate design #',num2str(i),'...'])\n fprintf(1,'\\n')\n [e(i,tt)] = VBA_designEfficiency(f_fname,g_fname,dim,o4design,u{i},'models');\n end\n [em,ind] = max(e(:,tt));\n U(:,(tt-1)*n_t+1:tt*n_t) = u{ind};\n fprintf(1,['Optimizing design (block ',num2str(tt),')... OK.'])\n fprintf(1,'\\n')\n plot(ha,tt,e(1,tt)','ro')\n plot(ha,tt,e(2,tt)','go')\n legend(ha,{'u_{att} = off','u_{att} = on'},'Location','southeast','Orientation','horizontal')\n \n % 2- simulate BOLD response to chosen design under true model\n fprintf(1,['-- Simulating data (block ',num2str(tt),')... '])\n [y,x,x0,eta,ee] = VBA_simulate (n_t,f_fname,g_fname,theta,phi,u{ind},alpha,sigma,o4design{truemodel},x0);\n Y(:,(tt-1)*n_t+1:tt*n_t) = y;\n x0 = x(:,end);\n \n try\n set(pl(1), 'XData', 1 : tt*n_t);\n set(pl(1), 'YData', [get(pl(1), 'YData') y(1,:)]);\n set(pl(2), 'XData', 1 : tt*n_t);\n set(pl(2), 'YData', [get(pl(2), 'YData') y(2,:)]);\n catch\n pl(1) = plot(ha2,1:n_t,y(1,:),'m');\n pl(2) = plot(ha2,1:n_t,y(2,:),'b');\n end \n legend(ha2,{'V1','V5'},'Location','southeast','Orientation','horizontal')\n fprintf(1,[' OK.']) \n fprintf(1,'\\n')\n drawnow\n \n % 3- invert both models given new piece of dataset\n % NB: priors for the next block are updated to current posterior\n fprintf(1,['-- VB (block ',num2str(tt),'): inverting model '])\n for j=1:length(o4design)\n fprintf(1,repmat('\\b',1,6))\n fprintf(1,[num2str(j),'/',num2str(length(o4design)),'...'])\n o4design{j}.DisplayWin = 0;\n o4design{j}.verbose = 0;\n [posterior,out] = VBA_NLStateSpaceModel(y,u{ind},f_fname,g_fname,dim{j},o4design{j});\n o4design{j}.priors = posterior;\n o4design{j}.priors.muX0 = posterior.muX(:,end);\n o4design{j}.priors.SigmaX0 = posterior.SigmaX.current{end};\n if tt > 1\n F(j,tt) = out.F + F(j,tt-1);\n else\n F(j,tt) = out.F;\n end\n OUT(j,tt).out = out;\n OUT(j,tt).posterior = posterior;\n end\n plot(ha3,tt,F(1,tt)-F(2,tt),'k*')\n \n eb(tt) = OUT(1,tt).posterior.muTheta(OUT(1,tt).out.options.inF.indB{2});\n vb(tt) = OUT(1,tt).posterior.SigmaTheta(OUT(1,tt).out.options.inF.indB{2},OUT(1,tt).out.options.inF.indB{2});\n \n fprintf(1,repmat('\\b',1,24))\n fprintf(1,[' OK.']) \n fprintf(1,'\\n')\n \n \nend\n\nha4 = subplot(3,2,4,'parent',hf,'nextplot','add','xlim',[0 nblocks+1]);\nxlabel(ha4,'time (blocks)')\nylabel(ha4,'modulatory effect')\nplotUncertainTimeSeries(eb',1.96^2*vb',[],ha4)\nhold(ha4,'on')\nplot(ha4,[0,nblocks+1],[t_B{2},t_B{2}],'g--')\n\nha5 = subplot(3,2,5,'parent',hf);\nimagesc(U,'parent',ha5)\ntitle(ha5,'chosen (online) design')\nxlabel(ha5,'time (scans)')\nhold(ha5,'on')\nplot(get(ha5,'xlim'),[1.5 1.5],'k')\nset(ha5,'ytick',[1,2],'yticklabel',{'u1','u2'})\ncolormap(flipud(bone))\n\n% invert full datasets at once\nn_t = size(Y,2);\nB{2}(2,1) = 1; % add modulatory effect (true model)\n[OPT,DIM] = getOptions4dcm(A,B,C,D,TR,microDT,n_t,1,1,1);\n[posterior,out] = VBA_NLStateSpaceModel(Y,U,f_fname,g_fname,DIM,OPT);\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/4_neural/demo_dcmonline.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426302, "lm_q2_score": 0.6992544147913994, "lm_q1q2_score": 0.5397149660523237}} {"text": "function [W,result] = IHR(Ws,npos,gama,afa,yuzhi)\nglobal eta;\nglobal TrainSetX;\nglobal TestSetX;\nglobal TestSetY;\nglobal kneighbor_testp;\n\nglobal W0;\nglobal s11;\nglobal w1;\nglobal index1;\nW0 = Ws;\nw1 = Ws;\n\ntempsum1 = 0;\nfor i=1:size(TestSetX,2)\n tempKN = kneighbor_testp(i,:);\n tempTuples = TestSetX(:,tempKN);\n s1 = w1'*tempTuples;\n p1 = 1./(1 + exp(-s1));\n tempsum1 = tempsum1 + (sum(p1)/size(kneighbor_testp,2)-1/(1+exp(-w1'*TestSetX(:,i))))^2;\nend\n\ntempsum2 = 0;\nfor i=1:size(TestSetX,2)\n tempsum2 = tempsum2 + (1/(1+exp(-w1'*TestSetX(:,i))) - 0.5)^2;\nend\n\ns1 = w1'*TestSetX;\np1 = 1./(1 + exp(-s1));\n\nf = ((w1)'*(w1))+afa*tempsum1/size(TestSetX,2)-gama*tempsum2/size(TestSetX,2)+eta*(sum(p1)-npos)^2/size(TestSetX,2); %07-12-31\nfprintf('initial value...%g\\n',f);\nindex1 = 0;\n\nresult(1,1) = getResult(p1,TestSetY);\nff(1,1) = f;\nwarning off;\nwhile index1 < 100\n\n temp11 = zeros(size(TestSetX,1),1);\n s11 = zeros(size(TestSetX,1),1);\n for i=1:size(TestSetX,2)\n tempKN = kneighbor_testp(i,:);\n tempTuples = TestSetX(:,tempKN);\n s1 = w1'*tempTuples;\n p1 = 1./(1 + exp(-s1));\n tmp_p1 = sum(p1)/size(kneighbor_testp,2)-1/(1+exp(-w1'*TestSetX(:,i)));\n p2 = exp(-s1)./((1 + exp(-s1)).^2);\n for k = 1:size(kneighbor_testp,2)\n temp11 = temp11 + tempTuples(:,k)*p2(1,k);\n end\n temp11 = temp11/size(kneighbor_testp,2) - (exp(-w1'*TestSetX(:,i))/(1+exp(-w1'*TestSetX(:,i)))^2)*TestSetX(:,i);\n s11 = s11 + 2*tmp_p1*temp11;\n end\n s11 = afa*s11/size(TestSetX,2); % \n\n\n\n s12 = zeros(size(TestSetX,1),1);\n for i = 1:size(TestSetX,2)\n s12 = s12 + 2*gama*(1/(1+exp(-w1'*TestSetX(:,i))) - 0.5)*((exp(-w1'*TestSetX(:,i)))/(1+exp(-w1'*TestSetX(:,i)))^2)*TestSetX(:,i);\n end\n s12 = s12/size(TestSetX,2);\n\n s1 = w1'*TestSetX;\n p1 = 1./(1 + exp(-s1));\n tmps13 = 2*eta*(sum(p1)-npos)*(exp(-w1'*TestSetX)./(1+exp(-w1'*TestSetX)).^2);\n s13 = sum(scale_cols(TestSetX,tmps13),2);\n s13 = s13/size(TestSetX,2);\n\n if [s11-s12+s13+2*(w1)]'*[s11-s12+s13+2*(w1)] < yuzhi^2\n break;\n end\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n if index1 == 0\n d0 = -s11+s12-s13-2*(w1);\n end\n if index1 > 0\n afa0 = ([s11-s12+s13+2*(w1)]'*[s11-s12+s13+2*(w1)-temp_s11-temp_s12])/([temp_s11+temp_s12]'*[temp_s11+temp_s12]);\n d1 = [-s11+s12-s13-2*(w1)] + afa0*d0;\n d0 = d1;\n end\n\n temp_s11 = s11;\n temp_s12 = -s12+s13+2*(w1);\n\n s11 = d0;\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n beta = 0;\n\n options = optimset('LargeScale','on');\n [x,fval] = fminunc(@objfun,beta,options);\n\n beta = x;\n if beta == 0\n break;\n end\n w1 = w1 + beta*d0;\n\n tempsum1 = 0;\n for i=1:size(TestSetX,2)\n tempKN = kneighbor_testp(i,:);\n tempTuples = TestSetX(:,tempKN);\n s1 = w1'*tempTuples;\n p1 = 1./(1 + exp(-s1));\n tempsum1 = tempsum1 + (sum(p1)/size(kneighbor_testp,2)-1/(1+exp(-w1'*TestSetX(:,i))))^2;\n end\n\n tempsum2 = 0;\n for i=1:size(TestSetX,2)\n tempsum2 = tempsum2 + (1/(1+exp(-w1'*TestSetX(:,i))) - 0.5)^2;\n end\n\n s1 = w1'*TestSetX;\n p1 = 1./(1 + exp(-s1));\n\n f = ((w1)'*(w1))+afa*tempsum1/size(TestSetX,2)-gama*tempsum2/size(TestSetX,2)+eta*(sum(p1)-npos)^2/size(TestSetX,2); %07-12-31\n\n s1 = w1'*TestSetX;\n p1 = 1./(1 + exp(-s1));\n index1 = index1+1;\n result(1,index1+1) = getResult(p1,TestSetY);\n ff(1,index1+1) = f;\n\n fprintf('iterating...%g value : %g...the accuracy:%g\\n',index1,f,getResult(p1,TestSetY));\n\nend\nW = w1;\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/IHR/IHR.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736773, "lm_q2_score": 0.6224593382055109, "lm_q1q2_score": 0.539694509524205}} {"text": "function [G1,C,impact,eu,F]=schur_solver(g0,g1,c,psi,pi,continuous,check_exist,check_uniq,n_v)\n% Solver based on Schur decomposition (This is based on Sims's gensys, but adjusted\n% to take advantage of special case that applies to heterogeneous agent models).\n%\n% by SeHyoun Ahn, Dec 2016\n%\n% REFERENCES:\n% * Sims, Christopher A. \"Solving linear rational expectations models.\"\n% Computational economics 20.1 (2002): 1-20.\n% * Ahn, SeHyoun, Greg Kaplan, Benjamin Moll, Thomas Winberry, and\n% Christian Wolf. \"When Inequality Matters for Macro and Macro Matters\n% for Inequality.\"\n%\n% PARAMETERS:\n% Check Sims's paper for notation or Our Paper for notation\n%\n% XXXXX DO NOT USE DISCRETE TIME VERSION. IT PROBABLY IS WRONG XXXXXX\n% The issue is noted in < https://github.com/gregkaplan/phact/issues/1 >\n%\n% continuous = 1 for a continuous time problem (default)\n% 0 for a discrete time problem\n%\n% check_exist = 1 check for existence of solution (default)\n% 0 existence has been checked before\n% check_uniq = 0 do not check for uniqueness (default)\n% 1 check for uniqueness\n% n_v = number of unstable roots\n%\n% OUPUTS:\n% eu(1) = 1 solution exists\n% 0 no stable solution\n% -5 Flag for checking existence is off\n% eu(2) = 1 solution is unique\n% 0 solution is not unique\n% -5 Flag for checking uniqueness is off\n%\n% SYNTAX:\n% [G1,C,impact,eu,F]=schur_solver(g0,g1,c,psi,pi,continuous,check_exist,check_uniq,varargin)\n\n%% Set Default Values %%\nswitch nargin\n case 8\n n_v = -1;\n case 7\n check_uniq = 0;\n n_v = -1;\n case 6\n check_uniq = 0;\n check_exist = 1;\n n_v = -1;\n case 5\n check_uniq = 0;\n check_exist = 1;\n continuous = 1;\n n_v = -1;\n case 1:4\n error('Insufficient Number of Input Variables');\nend\n\nrealsmall = sqrt(eps)*10;\neu = [-5;-5];\nn = size(g1,1);\n\n%% Schur Decomposition\n[U,T] = schur(full(g1),'real');\nif continuous\n g_eigs = real(ordeig(T));\n nunstab = sum(g_eigs>0);\n if n_v > -1\n [aux,ind] = sort(g_eigs,'descend');\n locs = ones(n,1);\n locs(ind(1:n_v)) = 0;\n [U,T] = ordschur(U,T,locs);\n if nunstab > n_v\n warning(': There are more than n_v number of positive eigenvalues with smallest values:');\n disp(aux(n_v+1:nunstab));\n elseif nunstab < n_v\n warning(': There are less than n_v number of positive eigenvalues:');\n disp(aux(nunstab+1:n_v));\n end\n nunstab = n_v;\n else\n [U,T] = ordschur(U,T,'lhp');\n end\nelse\n g_eigs = abs(ordeig(T));\n nunstab = sum(g_eigs>1);\n if n_v > -1\n [aux,ind] = sort(g_eigs,'descend');\n locs = ones(n,1);\n locs(ind(1:n_v)) = 0;\n [U,T] = ordschur(U,T,locs);\n if nunstab > n_v\n warning(': There are more than n_v number of positive eigenvalues with smallest values:');\n disp(aux(n_v+1:nunstab));\n elseif nunstab < n_v\n warning(': There are less than n_v number of positive eigenvalues:');\n disp(aux(nunstab+1:n_v));\n end\n nunstab = n_v;\n else\n\t[U,T] = ordschru(U,T,'udi');\n end\nend\n\nu1 = U(:,1:n-nunstab)';\nu2 = U(:,n-nunstab+1:n)';\n\netawt = u2*pi;\n[ueta,deta,veta] = svd(etawt);\nmd = min(size(deta));\nbigev = find(diag(deta(1:md,1:md))>realsmall);\nueta = ueta(:,bigev);\nveta = veta(:,bigev);\ndeta = deta(bigev,bigev);\n\nif check_exist\n zwt = u2*psi;\n [uz,dz,vz] = svd(zwt);\n md = min(size(dz));\n bigev = find(diag(dz(1:md,1:md))>realsmall);\n uz = uz(:,bigev);\n vz = vz(:,bigev);\n dz = dz(bigev,bigev);\n\n if isempty(bigev)\n eu(1) = 1;\n else\n eu(1) = (norm(uz-ueta*ueta'*uz,'fro') < realsmall*n);\n end\n\n if (~eu(1) && (n_v == -1))\n warning(': Solution does not exist');\n end\n impact = real(-pi*veta*(deta\\ueta')*uz*dz*vz'+psi);\nelse\n impact = real(-pi*veta*(deta\\ueta')*u2*psi+psi);\nend\n\nG1 = U*T*spdiags([ones(n-nunstab,1);zeros(nunstab,1)],0,n,n)*U';\nG1 = real(G1);\n\nif check_uniq\n [~,deta1,veta1] = svd(u1*pi);\n md = min(size(deta1));\n bigev = find(diag(deta1(1:md,1:md))>realsmall);\n veta1 = veta1(:,bigev);\n if isempty(veta1)\n eu(2) = 1;\n else\n eu(2) = norm(veta1-veta*veta'*veta1,'fro')d\nfor i=1:d-1\n cr = tt{i};\n cr = reshape(cr, rcr(i)*n(i), rcr(i+1));\n [cr, rv]=qr(cr, 0);\n cr2 = tt{i+1};\n cr2 = rv*reshape(cr2, rcr(i+1), n(i+1)*rcr(i+2));\n rcr(i+1) = size(cr,2);\n tt{i} = reshape(cr, rcr(i), n(i), rcr(i+1));\n tt{i+1} = reshape(cr2, rcr(i+1), n(i+1), rcr(i+2));\nend;\n\n% Split tucker factors from d->1\ncore = tt;\nnextcr = core{d};\nrtuck = zeros(d,1);\nfor i=d:-1:1\n cr = nextcr;\n cr = permute(cr, [2, 1, 3]);\n cr = reshape(cr, n(i), rcr(i)*rcr(i+1));\n [u,s,v]=svd(cr, 'econ');\n s = diag(s);\n nrm = norm(s);\n r = my_chop2(s, tol*nrm); % !!!!!!\n rtuck(i) = r;\n if (i>1)\n fc{i} = u(:,1:r);\n cr = diag(s(1:r))*v(:,1:r)';\n cr = reshape(cr, r, rcr(i), rcr(i+1));\n cr = permute(cr, [1, 3, 2]);\n cr = reshape(cr, r*rcr(i+1), rcr(i));\n [cr,rv] = qr(cr, 0);\n cr2 = core{i-1};\n cr2 = reshape(cr2, rcr(i-1)*n(i-1), rcr(i));\n cr2 = cr2*(rv.');\n rcr(i) = size(cr, 2);\n nextcr = reshape(cr2, rcr(i-1), n(i-1), rcr(i));\n cr = reshape(cr, r, rcr(i+1), rcr(i));\n core{i} = permute(cr, [3, 1, 2]);\n else\n cr = v(:,1:r)';\n cr = reshape(cr, r, rcr(i), rcr(i+1));\n core{i} = permute(cr, [2, 1, 3]);\n fc{i} = u(:,1:r)*diag(s(1:r));\n end; \nend;\n\n% Quantics approximation\nfor i=1:d\n %d0 = log2(n(i));\n fc{i} = tt_tensor(fc{i});\n szc=sz{i}; d0=numel(szc); m0=szc(end); szc=szc(:);\n %fc{i} = tt_reshape(fc{i}, [2*ones(1,d0-1), 2*rtuck(i)], tol);\n fc{i}=tt_reshape(fc{i},[szc(1:end-1); m0*rtuck(i)],tol);\n nocore = fc{i}{d0}; % rqtt, 2*rtuck, 1\n rqtt = size(nocore, 1);\n if (icr{i}->cr{i+1}->fc{i+1} \n nocore = reshape(nocore, rqtt*m0, rtuck(i));\n [ocore, nocore]=qr(nocore, 0); \n cr1 = core{i};\n cr1 = permute(cr1, [2, 1, 3]);\n cr1 = reshape(cr1, rtuck(i), rcr(i)*rcr(i+1));\n cr1 = nocore*cr1;\n rtuck(i) = size(cr1, 1);\n fc{i}{d0} = reshape(ocore, rqtt, m0, rtuck(i));\n \n cr1 = reshape(cr1, rtuck(i)*rcr(i), rcr(i+1));\n [cr1, rv]=qr(cr1, 0);\n cr2 = core{i+1};\n cr2 = reshape(cr2, rcr(i+1), rtuck(i+1)*rcr(i+2));\n cr2 = rv*cr2;\n rcr(i+1) = size(cr1, 2);\n cr1 = reshape(cr1, rtuck(i), rcr(i), rcr(i+1));\n core{i} = permute(cr1, [2,1,3]);\n cr2 = reshape(cr2, rcr(i+1), rtuck(i+1), rcr(i+2));\n cr2 = permute(cr2, [1, 3, 2]);\n cr2 = reshape(cr2, rcr(i+1)*rcr(i+2), rtuck(i+1));\n [cr2, rv]=qr(cr2, 0);\n fc{i+1} = fc{i+1}*(rv.');\n rtuck(i+1) = size(cr2, 2);\n cr2 = reshape(cr2, rcr(i+1), rcr(i+2), rtuck(i+1));\n core{i+1} = permute(cr2, [1, 3, 2]); \n else\n fc{i}{d0} = reshape(nocore, rqtt, m0, rtuck(i));\n end;\nend;\n\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/qtt_tucker_m.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619979547273, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5396158205189527}} {"text": "function BoschettiEnc(img, name, bos_rateE, bos_rateRGB, nBit, tmo_operator)\n%\n%\n% BoschettiEnc(img, name, bos_rateE, bos_rateRGB, nBit)\n%\n%\n% Input:\n% -img: input HDR image\n% -name: is output name of the image. If img is empty\n% an HDR image with filename 'name' is loaded\n% -bos_rateE: JPEG2000 compression rate for the E layer\n% -bos_rateRGB: JPEG2000 compression rate for the RGB layer\n% -nBit: number of bit of the encoding. The maximum is 16.\n% -tmo_operator: an handle to a tone mapping operator\n%\n%\n% Copyright (C) 2012 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('name', 'var'))\n name = 'bosc_enc';\nend\n\nif(~exist('bos_rateRGB', 'var'))\n rateRGB = 15;\nelse\n rateRGB = bos_rateRGB;\nend\n\nif(~exist('bos_rateE', 'var'))\n rateE = 15;\nelse\n rateE = bos_rateE;\nend\n\nif(~exist('nBit','var'))\n nBit = 16;\nend\n\nif(~exist('tmo_operator','var'))\n tmo_operator = @ReinhardTMO;\nend\n\n%Tone mapping\nimgTMO = tmo_operator(img);\n%LDR Encoding\nimgTMO = GammaTMO(imgTMO, 2.2, 0.0, 0);\n\n%Quantization\nmaxVal = 2^nBit - 1;\nimgTMO = round(imgTMO * maxVal) / maxVal;\n\n%Computing E\nepsilon = 1e-4;\nepi = 1.0 / maxVal;\nE = log2(img ./ (imgTMO + epi) + epsilon);\nE = mean(E, 3);\n\n%Encoding E\nmaxE = max(E(:));\nminE = min(E(:));\nEq = (E - minE) / (maxE - minE);\n\n%metadata string\nmetatadata = [num2str(nBit), ' ', num2str(maxE), ' ', num2str(minE)];\n\nif(nBit == 16)\n Eq = uint16(Eq * maxVal);\nend\n\nimwrite(Eq,[name,'_bos_E.jp2'], 'Mode', 'lossy', 'CompressionRatio', rateE);\n\n%Decoding E\nEqDec = double(imread([name, '_bos_E.jp2'])) / maxVal;\nEDec = EqDec * (maxE - minE) + minE;\n\n%Computing RGB\nRGB = zeros(size(img));\ndiv = 2.^EDec;\nfor i=1:size(img, 3)\n RGB(:,:,i) = (img(:,:,i) ./ div);\nend\n\n%Encoding RGB\nif(nBit == 16)\n RGB = uint16(RGB * maxVal);\nend\n\nnameOut = [name,'_bos_RGB.jp2'];\nimwrite(RGB, nameOut, 'Mode', 'lossy', 'CompressionRatio', rateRGB, 'Comment', metatadata);\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/Compression/BoschettiEnc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199714402812, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.539615815296225}} {"text": "%MDL_FANUC10L Create kinematic model of Fanuc AM120iB/10L robot \n%\n% MDL_FANUC10L is a script that creates the workspace variable R which\n% describes the kinematic characteristics of a Fanuc AM120iB/10L robot\n% using standard DH conventions.\n%\n% Also defines the workspace vector:\n% q0 mastering position.\n%\n% Notes::\n% - SI units of metres are used.\n%\n% Author::\n% Wynand Swart,\n% Mega Robots CC, P/O Box 8412, Pretoria, 0001, South Africa,\n% wynand.swart@gmail.com\n%\n% See also mdl_irb140, mdl_m16, mdl_motomanHP6, mdl_puma560, SerialLink.\n\n% MODEL: Fanuc, AM120iB/10L, 6DOF, standard_DH\n\n% Copyright (C) 1993-2011, by Peter I. Corke\n%\n% This file is part of The Robotics Toolbox for Matlab (RTB).\n% \n% RTB is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Lesser General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% RTB is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU Lesser General Public License for more details.\n% \n% You should have received a copy of the GNU Leser General Public License\n% along with RTB. If not, see .\n\n%Cell: 073-1555-430\n%30 Sep 2007\n%Fanuc AM120iB/10L robot\n\n% theta d a alpha\nclear L\nL(1) = Link([0 0 0.15 -pi/2 0 ]);\nL(2) = Link([0 0 0.77 pi 0 ]);\nL(3) = Link([0 0 0.1 -pi/2 0 ]);\nL(4) = Link([0 -0.96 0 pi/2 0 ]);\nL(5) = Link([0 0 0 -pi/2 0 ]);\nL(6) = Link([0 -0.1 0 0 0 ]);\n%##########################################################\n%Pose 0; At MASTERING position;\n%##########################################################\nq0 =[0 -pi/2 0 0 0 0];\nR=SerialLink(L, 'name', 'Fanuc AM120iB/10L');\n%##########################################################\n", "meta": {"author": "petercorke", "repo": "robotics-toolbox-matlab", "sha": "bd7a9d75176c660f43fc799b24d838f70b02250c", "save_path": "github-repos/MATLAB/petercorke-robotics-toolbox-matlab", "path": "github-repos/MATLAB/petercorke-robotics-toolbox-matlab/robotics-toolbox-matlab-bd7a9d75176c660f43fc799b24d838f70b02250c/models/mdl_fanuc10L.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199511728004, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.5396158136824093}} {"text": "function innerpro = cinnerprodgeneral(x, y)\n% Computes the Euclidean inner product between x and y in the complex case\n%\n% function innerpro = cinnerprodgeneral(x, y)\n%\n% The input x and y are numeric data structures which can be defined \n% recursively by arrays, structs and cells. Each part of x and y should \n% be a struct which contains the fields real and iamg which indicate\n% the real and imaginary part of the stored complex numbers. The inner\n% product between x and y is defined as sum(real(conj(x(:)).*y(:))).\n% The return is the sum of the inner products over each part of x and y.\n% In case that x and y are structs with different fields, the inner products\n% are computed only for the common fields.\n%\n% Note: Operations between dlarrays containing complex numbers have been\n% introduced in Matlab R2021b or later. This file is only useful for Matlab\n% R2021a or earlier. It will be discarded when Matlab R2021b is stable. \n% \n% See also: innerprodgeneral, manoptADhelp\n\n% This file is part of Manopt: www.manopt.org.\n% Original author: Xiaowen Jiang, Aug. 31, 2021.\n% Contributors: Nicolas Boumal\n% Change log: \n\n if ~((isstruct(x) && isstruct(y)) || (iscell(x) && iscell(y))...,\n || (isnumeric(x) && isnumeric(y)) || (isstruct(x) && isnumeric(y)))\n \n up = MException('manopt:autodiff:cinnerprodgeneral' ,...\n 'cinnerprodgeneral should only accept structs, cells or arrays.');\n throw(up);\n \n end\n % recursively compute the inner product \n if isstruct(x) && isstruct(y) && (~isfield(x,'real')) && (~isfield(y,'real'))\n innerpro = cinnerprodgeneral_struct(x,y);\n elseif iscell(x) && iscell(y)\n innerpro = cinnerprodgeneral_cell(x,y);\n else\n xconj = cconj(x);\n product = cdottimes(xconj,y);\n innerpro = sum(creal(product),'all');\n % slower\n % xcol = cmat2col(x);\n % innerpro = creal(cprod(ctransp(xcol),xcol));\n end\n \n % struct case\n function innerpro = cinnerprodgeneral_struct(x,y)\n innerpro = 0;\n elemsx = fieldnames(x);\n elemsy = fieldnames(y);\n % find the common fields\n [elems,ix,iy] = intersect(elemsx,elemsy, 'stable');\n nelems = numel(elems);\n for ii = 1:nelems\n if isstruct(x.(elemsx{ix(ii)})) && (~isfield(x.(elemsx{ix(ii)}),'real'))...,\n && (~isfield(y.(elemsy{iy(ii)}),'real'))\n innerpro = innerpro + cinnerprodgeneral_struct(...,\n x.(elemsx{ix(ii)}),y.(elemsy{iy(ii)}));\n elseif iscell(x.(elemsx{ix(ii)}))\n innerpro = innerpro + cinnerprodgeneral_cell(...,\n x.(elemsx{ix(ii)}),y.(elemsy{iy(ii)}));\n else\n xconj = cconj(x.(elemsx{ix(ii)}));\n product = cdottimes(xconj, y.(elemsy{iy(ii)}));\n innerpro = innerpro + sum(creal(product), 'all');\n end\n end\n end\n \n % cell case\n function innerpro = cinnerprodgeneral_cell(x,y)\n innerpro = 0;\n ncell = length(x);\n for ii = 1:ncell\n if isstruct(x{ii}) && (~isfield(x{ii},'real')) && (~isfield(y{ii},'real'))\n innerpro = innerpro + cinnerprodgeneral_struct(...,\n x{ii},y{ii});\n elseif iscell(x{ii})\n innerpro = innerpro + cinnerprodgeneral_cell(...,\n x{ii},y{ii});\n else\n xconj = cconj(x{ii});\n product = cdottimes(xconj, y{ii});\n innerpro = innerpro + sum(creal(product), 'all');\n end\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/autodiff/functions_AD/cinnerprodgeneral.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5395952317805245}} {"text": "function [A, Z, title, key, mtype] = RBfix (filename)\n%RBFIX read a possibly corrupted matrix from a R/B file\n% (assembled format only). Usage:\n%\n% [A Z title key mtype] = RBfix (filename)\n%\n% The Rutherford/Boeing format stores a sparse matrix in a file in compressed-\n% column form, using 3 arrays: Ap, Ai, and Ax. The row indices of entries in\n% A(:,j) are in Ai(p1:p2) and the corresponding numerical values are Ax(p1:p2),\n% where p1 = Ap(j) and p2 = Ap(j+1)-1. The row indices ought to be sorted, and\n% no duplicates should appear, but this function ignores that requirement.\n% Duplicate entries are summed if they exist, and A is returned with sorted\n% columns. Symmetric matrices are stored with just their lower triangular\n% parts in the file. Normally, it is an error if entries are present in the\n% upper triangular part of a matrix that is declared in the file to be\n% symmetric. This function simply ignores those entries.\n%\n% If CHOLMOD is installed, this function is faster and uses less memory.\n%\n% Example:\n%\n% load west0479\n% RBwrite ('mywest', west0479, [ ], 'My west0479 file', 'west0479') ;\n% [A Z title key mtype] = RBfix ('mywest') ;\n% isequal (A, west0479)\n% title, key, mtype\n%\n% See also mread, RBread, RBwrite, RBreade, sparse2.\n\n% Optionally uses the CHOLMOD sparse2 mexFunction.\n\n% Copyright 2007, Timothy A. Davis\n\n%-------------------------------------------------------------------------------\n% read in the raw contents of the Rutherford/Boeing file\n%-------------------------------------------------------------------------------\n\n[mtype Ap Ai Ax title key nrow] = RBraw (filename) ;\nmtype = lower (mtype) ;\n\n%-------------------------------------------------------------------------------\n% determine dimension, number of entries, and convert numerical entries\n%-------------------------------------------------------------------------------\n\n% number of columns\nncol = length (Ap) - 1 ;\n\n% number of entries\nnz = length (Ai) ;\n\n% check column pointers\nif (any (Ap ~= sort (Ap)) | (Ap (1) ~= 1) | (Ap (ncol+1) - 1 ~= nz))\t %#ok\n error ('invalid column pointers') ;\nend\n\n% check row indices\nif ((double (max (Ai)) > nrow) | double (min (Ai)) < 1)\t\t\t %#ok\n error ('invalid row indices') ;\nend\n\n% Ax can be empty, for a p*a matrix\nif (~isempty (Ax))\n if (mtype (1) == 'c')\n\t% Ax is real, with real/imaginary parts interleaved\n\tif (2 * nz ~= length (Ax))\n\t error ('invalid matrix') ;\n\tend\n\tAx = Ax (1:2:end) + (1i * Ax (2:2:end)) ;\n elseif (mtype (1) == 'i')\n\tAx = double (Ax) ;\n end\n % numerical values must be of the right size\n if (nz ~= length (Ax))\n\terror ('invalid matrix') ;\n end\nend\n\n%-------------------------------------------------------------------------------\n% create the triplet form\n%-------------------------------------------------------------------------------\n\n% construct column indices\nAj = zeros (nz,1) ;\nfor j = 1:ncol\n p1 = Ap (j) ;\n p2 = Ap (j+1) - 1 ;\n Aj (p1:p2) = j ;\nend\n\n%-------------------------------------------------------------------------------\n% create the sparse matrix form\n%-------------------------------------------------------------------------------\n\nif (exist ('sparse2') == 3)\t\t\t\t\t\t %#ok\n % Use sparse2 in CHOLMOD. It's faster, allows integer Ai and Aj, and\n % returns the Z matrix as the 2nd output argument.\n if (isempty (Ax))\n\tAx = 1 ;\n end\n % numerical matrix\n [A Z] = sparse2 (Ai, Aj, Ax, nrow, ncol) ;\nelse\n % stick with MATLAB, without CHOLMOD. This is slower and takes more memory.\n Ai = double (Ai) ;\n Aj = double (Aj) ;\n if (isempty (Ax))\n\t% pattern-only matrix\n\tA = spones (sparse (Ai, Aj, 1, nrow, ncol)) ;\n\tZ = sparse (nrow, ncol) ;\n else\n\t% numerical matrix\n\tA = sparse (Ai, Aj, Ax, nrow, ncol) ;\n\t% determine the pattern of explicit zero entries\n\tS = spones (sparse (Ai, Aj, 1, nrow, ncol)) ;\n\tZ = S - spones (A) ;\n end\nend\n\n% check for entries in upper part\nif (any (mtype (2) == 'shz') & nnz (triu (A,1) > 0))\t\t\t %#ok\n fprintf ('entries in upper triangular part of %s matrix ignored\\n', mtype);\nend\n\n% add the upper triangular part\nif (mtype (2) == 's')\n A = A + tril (A,-1).' ;\n Z = Z + tril (Z,-1)' ;\nelseif (mtype (2) == 'h')\n A = A + tril (A,-1)' ;\n Z = Z + tril (Z,-1)' ;\nelseif (mtype (2) == 'z')\n A = A - tril (A,-1).' ;\n Z = Z + tril (Z,-1)' ;\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/RBio/RBfix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5395952317805245}} {"text": "function tcpWithBoost = seanWalshTCP(paramS,doseBinsC,volHistC)\n% Sean Walsh TCP model for prostate\n% http://dx.doi.org/10.1118/1.4939260\n%\n% APA, 07/20/2016\n% AI, 09/12/16 Modified for use with outcomeModelsGUI\n\n\n% Get parameters\nalpha = 0.25; %paramS.alpha.val;\nbeta = 0.1008;% paramS.beta.val;\nsigmaAlpha = alpha*11.3/100;\nsigmaBeta = beta*12.9/100;\n\nn = paramS.numFractions.val; % number of fractions\n\n\nDILparS = paramS.structures.DIL;\ndilVolume = DILparS.dilVolume.val; % percent\npDIL = DILparS.pDIL.val; % DIL density\ndDIL = DILparS.dDIL.val; % dose per fraction to the DIL\n\nPTVparS = paramS.structures.PTV_1;\nhypoxicFraction = PTVparS.hypoxicFraction.val; % percent\nOER = PTVparS.OER.val; % Oxygen Enhancement Ratio\npCTV = PTVparS.pCTV.val; % Prostate density\nctvVolume = PTVparS.ctvVolume.val; % 36 cm^3 for intermediate risk \n % 72 cm^3 for high risk pts\nnumSimulations = PTVparS.numSimulations.val; % number of (alpha,beta) simulations\n\n%Compute mean dose to prostate\nprost = calc_meanDose(doseBinsC{2},volHistC{2},1);\n%Dose per fraction to the prostate\ndProst = prost/n;\n\n% Compute TCP\n%Seed the random generator\nrng(now,'twister');\n\n\n%Generate normally distributed, positive aplha and beta\nalphaV = alpha + randn(numSimulations*2, 1) * sigmaAlpha;\nbetaV = beta + randn(numSimulations*2, 1) * sigmaBeta;\nalphaV = alphaV(alphaV > 0);\nbetaV = betaV(betaV > 0);\nalphaV = alphaV(1:numSimulations);\nbetaV = betaV(1:numSimulations);\n\n%Hypoxic cells alpha,beta\nalphaPO2 = alphaV / OER;\nbetaPO2 = betaV / OER^2;\n\n% Total initial clonogen number\nN0 = ((100-dilVolume)*pCTV + dilVolume*pDIL) / 100 * ctvVolume;\n\n%Initial number of clonogens in prostate\nNprost = (100-dilVolume)*pCTV / 100 * ctvVolume;\n\n%Initial number of clonogens in DIL\nNdil = dilVolume*pDIL / 100 * ctvVolume;\n\n%Surviving fraction for Prostate\nSProstateV = exp(-alphaV*n*dProst -betaV*n*dProst^2);\n\n%Surviving fraction for hypoxic Prostate\nShypoxicProstateV = exp(-alphaPO2*n*dProst -betaPO2*n*dProst^2);\n\n%Surviving fraction for DIL\nSdilV = exp(-alphaV*n*dDIL -betaV*n*dDIL^2);\n\n%Surviving fraction for hypoxic DIL\nShypoxicDilV = exp(-alphaPO2*n*dDIL -betaPO2*n*dDIL^2);\n\n%Total surviving clonogens\nNumSurvivingV = Nprost*(1-hypoxicFraction)*SProstateV + ...\n Nprost*hypoxicFraction*ShypoxicProstateV + ...\n Ndil*(1-hypoxicFraction)*SdilV + ...\n Ndil*hypoxicFraction*ShypoxicDilV;\n\n% TCP\nTCPv = exp(-NumSurvivingV);\n\n%Record the TCP for this DIL dose\ntcpWithBoost = mean(TCPv);\n\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/ModelImplementationLibrary/DosimetricModels/seanWalshTCP.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505453836382, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.5395635710531727}} {"text": "function []=panel5disp(n,N,m,p,k,T,d1,d2,d3,d4,d5,Ymat,Xdot,Units,endo,exo,const,Xi,theta_gibbs,theta_median,theta_std,theta_lbound,theta_ubound,sigma_gibbs,sigma_median,D_estimates,gamma_estimates,alpha0,delta0,startdate,enddate,forecast_record,forecast_estimates,Fcperiods,stringdates3,Fstartdate,Fcenddate,Feval,Fcomp,data_endo_c,data_endo_c_lags,data_exo_c,It,Bu,IRF,IRFt,pref,names)\n\n\n\n\n\n\n% recover a point estimate (the median) of the VAR coefficients\nbetatilde=Xi*theta_median;\nBtilde=reshape(betatilde,k,N*n);\n\n% check whether the model is stationary\n[stationary,eigmodulus]=bear.checkstable(betatilde,N*n,p,k);\n\n% estimate the in-sample evaluation criteria\n\n% obtain a point estimate thetatilde of the structural factors, which is the median\nthetatilde=theta_median;\n% compute fitted values\nYtilde=full(Xdot*kron(speye(T),thetatilde))';\n% reshape for convenience\nYtilde=reshape(Ytilde,T,n,N);\nYmat=reshape(Ymat,T,n,N);\n\n% loop over units\nfor ii=1:N\n% estimate the residuals for this unit\nEPS(:,:,ii)=Ymat(:,:,ii)-Ytilde(:,:,ii);\n\n% Compute then the sum of squared residuals\n% compute first the RSS matrix, defined in (1.9.5)\nRSS(:,:,ii)=EPS(:,:,ii)'*EPS(:,:,ii);\n% retain only the diagonal elements to get the vector of RSSi values\nrss(:,:,ii)=diag(RSS(:,:,ii));\n\n% Go on calculating R2\n% generate Mbar\nMbar=eye(T)-ones(T,T)/T;\n% then compute the TSS matrix, defined in (1.9.8)\nTSS(:,:,ii)=Ymat(:,:,ii)'*Mbar*Ymat(:,:,ii);\n% generate the R2 matrix in (1.9.9)\nR2(:,:,ii)=eye(n)-RSS(:,:,ii)./TSS(:,:,ii);\n% retain only the diagonal elements to get the vector of R2 values\nr2(:,:,ii)=diag(R2(:,:,ii));\n\n% then calculate the adjusted R2, using (1.9.11)\nR2bar(:,:,ii)=eye(n)-((T-1)/(T-k))*(eye(n)-R2(:,:,ii));\n% retain only the diagonal elements to get the vector of R2bar values\nr2bar(:,:,ii)=diag(R2bar(:,:,ii));\n\nend\n\n\n\n\n% estimate the forecast evaluation criteria\n% first note that forecast evaluation can only be conducted if it is activated, and if there is some observable data after the beginning of the forecast\nif Feval==1 && Fcomp==1\n\n% generate the elements required for the evaluation\nbeta_gibbs=Xi*theta_gibbs;\nforecast_record=reshape(forecast_record,N*n,1);\nforecast_estimates=reshape(forecast_estimates,N*n,1);\ndata_endo_c=reshape(data_endo_c,Fcperiods,N*n);\ndata_endo_c_lags=reshape(data_endo_c_lags,p,N*n);\n\n% compute forecast evaluation\n[RMSE,MAE,MAPE,Ustat,CRPS_estimates,S1_estimates,S2_estimates]=bear.panelfeval(N*n,p,k,beta_gibbs,sigma_gibbs,forecast_record,forecast_estimates,Fcperiods,data_endo_c,data_endo_c_lags,data_exo_c,const,It,Bu);\n\nend\n\n\n\n\n% start displaying and saving the general results\n\n\n% preliminary task: create and open the txt file used to save the results\n\nfilelocation=fullfile(pref.results_path, [pref.results_sub '.txt']);\nfid=fopen(filelocation,'wt');\n\n% print toolbox header\n\nfprintf('%s\\n','');\nfprintf(fid,'%s\\n','');\n\n% print the list of contributors\nbear.printcontributors(fid);\n\n% print then estimation results\n\nfprintf('%s\\n','');\nfprintf(fid,'%s\\n','');\nfprintf('%s\\n','');\nfprintf(fid,'%s\\n','');\n\ntoolboxinfo='BEAR toolbox estimates';\nfprintf('%s\\n',toolboxinfo);\nfprintf(fid,'%s\\n',toolboxinfo);\n\ntime=clock;\ndatestring=datestr(time);\ndateinfo=['Date: ' datestring(1,1:11) ' Time: ' datestring(1,13:17)];\nfprintf('%s\\n',dateinfo);\nfprintf(fid,'%s\\n',dateinfo);\n\nfprintf('%s\\n','');\nfprintf(fid,'%s\\n','');\nfprintf('%s\\n','');\nfprintf(fid,'%s\\n','');\n\nVARtypeinfo='Panel VAR: structural factor (static)';\nfprintf('%s\\n',VARtypeinfo);\nfprintf(fid,'%s\\n',VARtypeinfo);\n\nif IRFt==1\nSVARinfo='structural decomposition: none';\nfprintf('%s\\n',SVARinfo);\nfprintf(fid,'%s\\n',SVARinfo);\nelseif IRFt==2\nSVARinfo='structural decomposition: choleski factorisation'; \nfprintf('%s\\n',SVARinfo);\nfprintf(fid,'%s\\n',SVARinfo);\nelseif IRFt==3\nSVARinfo='structural decomposition: triangular factorisation'; \nfprintf('%s\\n',SVARinfo);\nfprintf(fid,'%s\\n',SVARinfo);\nend\n\ntemp='units: ';\nfor ii=1:N\ntemp=[temp ' ' Units{ii,1} ' '];\nend\nunitinfo=temp;\nfprintf('%s\\n',unitinfo);\nfprintf(fid,'%s\\n',unitinfo);\n\ntemp='endogenous variables: ';\nfor ii=1:n\ntemp=[temp ' ' endo{ii,1} ' '];\nend\nendoinfo=temp;\nfprintf('%s\\n',endoinfo);\nfprintf(fid,'%s\\n',endoinfo);\n\ntemp='exogenous variables: ';\nif const==0 && m==0\ntemp=[temp ' none'];\nelseif const==1 && m==1\ntemp=[temp ' constant '];\nelseif const==0 && m>0\n for ii=1:m-1\n temp=[temp ' ' exo{ii,1} ' '];\n end\nelseif const==1 && m>1\ntemp=[temp ' constant '];\n for ii=1:m-1\n temp=[temp ' ' exo{ii,1} ' '];\n end\nend\nexoinfo=temp;\nfprintf('%s\\n',exoinfo);\nfprintf(fid,'%s\\n',exoinfo);\n\nsampledateinfo=['estimation sample: ' startdate '-' enddate];\nfprintf('%s\\n',sampledateinfo);\nfprintf(fid,'%s\\n',sampledateinfo);\n\nsamplelengthinfo=['sample size (omitting initial conditions): ' num2str(T)];\nfprintf('%s\\n',samplelengthinfo);\nfprintf(fid,'%s\\n',samplelengthinfo);\n\nlaginfo=['number of lags included in regression: ' num2str(p)];\nfprintf('%s\\n',laginfo);\nfprintf(fid,'%s\\n',laginfo);\n\nhyperparam1='hyperparameters:';\nfprintf('%s\\n',hyperparam1);\nfprintf(fid,'%s\\n',hyperparam1);\n\nhyperparam2=['IG shape on residual variance (alpha0): ' num2str(alpha0)];\nfprintf('%s\\n',hyperparam2);\nfprintf(fid,'%s\\n',hyperparam2);\n\nhyperparam3=['IG scale on residual variance (delta0): ' num2str(delta0)];\nfprintf('%s\\n',hyperparam3);\nfprintf(fid,'%s\\n',hyperparam3);\n\nfprintf('%s\\n','');\nfprintf(fid,'%s\\n','');\nfprintf('%s\\n','');\nfprintf(fid,'%s\\n','');\nfprintf('%s\\n','');\nfprintf(fid,'%s\\n','');\nfprintf('%s\\n','');\nfprintf(fid,'%s\\n','');\n\n\n% display factor estimates\n\nfactorinfo=['Structural factors:'];\nfprintf('%s\\n',factorinfo);\nfprintf(fid,'%s\\n',factorinfo);\n\nfprintf('%s\\n','');\nfprintf(fid,'%s\\n','');\n\nfactorheader=fprintf('%35s %15s %15s %15s %15s\\n','','Median','St.dev','Low.bound','Upp.bound');\nfactorheader=fprintf(fid,'%35s %15s %15s %15s %15s\\n','','Median','St.dev','Low.bound','Upp.bound');\n\n\n% common component\n\nfprintf('%s\\n','theta1 (common component)');\nfprintf(fid,'%s\\n','theta1 (common component)');\nvalues=[theta_median(1,1) theta_std(1,1) theta_lbound(1,1) theta_ubound(1,1)];\nfprintf('%-35s %15.3f %15.3f %15.3f %15.3f\\n','common component',values);\nfprintf(fid,'%-35s %15.3f %15.3f %15.3f %15.3f\\n','common component',values);\nfprintf('%s\\n','');\nfprintf(fid,'%s\\n','');\n\n% unit component\n\nfprintf('%s\\n','theta2 (unit-specific component)');\nfprintf(fid,'%s\\n','theta2 (unit component)');\nfor ii=1:d2\nvalues=[theta_median(d1+ii,1) theta_std(d1+ii,1) theta_lbound(d1+ii,1) theta_ubound(d1+ii,1)];\nfprintf('%-35s %15.3f %15.3f %15.3f %15.3f\\n',['unit ' int2str(ii) ' component'],values);\nfprintf(fid,'%-35s %15.3f %15.3f %15.3f %15.3f\\n',['unit ' int2str(ii) ' component'],values);\nend\nfprintf('%s\\n','');\nfprintf(fid,'%s\\n','');\n\n% variable component\n\nfprintf('%s\\n','theta3 (variable-specific component)');\nfprintf(fid,'%s\\n','theta3 (endogenous variable component)');\nfor ii=1:d3\nvalues=[theta_median(d1+d2+ii,1) theta_std(d1+d2+ii,1) theta_lbound(d1+d2+ii,1) theta_ubound(d1+d2+ii,1)];\nfprintf('%-35s %15.3f %15.3f %15.3f %15.3f\\n',['variable ' int2str(ii) ' component'],values);\nfprintf(fid,'%-35s %15.3f %15.3f %15.3f %15.3f\\n',['variable ' int2str(ii) ' component'],values);\nend\nfprintf('%s\\n','');\nfprintf(fid,'%s\\n','');\n\n% lag component (if applicable)\n\nif d4~=0\nfprintf('%s\\n','theta4 (lag-specific component)');\nfprintf(fid,'%s\\n','theta4 (lag component)');\nfor ii=1:d4\nvalues=[theta_median(d1+d2+d3+ii,1) theta_std(d1+d2+d3+ii,1) theta_lbound(d1+d2+d3+ii,1) theta_ubound(d1+d2+d3+ii,1)];\nfprintf('%-35s %15.3f %15.3f %15.3f %15.3f\\n',['lag ' int2str(ii) ' component'],values);\nfprintf(fid,'%-35s %15.3f %15.3f %15.3f %15.3f\\n',['lag ' int2str(ii) ' component'],values);\nend\nfprintf('%s\\n','');\nfprintf(fid,'%s\\n','');\nend\n\n% exogenous component (if applicable)\n\nif d5~=0\nfprintf('%s\\n','theta5 (exogenous variable component)');\nfprintf(fid,'%s\\n','theta5 (exogenous component)');\n% initiate equation count\neqcount=0;\n% initiate exogenous count\nexocount=0;\nfor ii=1:d5\n if exocount==m\n exocount=0;\n end\n if exocount==0\n eqcount=eqcount+1;\n end\nexocount=exocount+1;\nvalues=[theta_median(d1+d2+d3+d4+ii,1) theta_std(d1+d2+d3+d4+ii,1) theta_lbound(d1+d2+d3+d4+ii,1) theta_ubound(d1+d2+d3+d4+ii,1)];\nfprintf('%-35s %15.3f %15.3f %15.3f %15.3f\\n',['equation ' int2str(eqcount) ', exogenous ' int2str(exocount) ' component'],values);\nfprintf(fid,'%-35s %15.3f %15.3f %15.3f %15.3f\\n',['equation ' int2str(eqcount) ', exogenous ' int2str(exocount) ' component'],values);\nend\nfprintf('%s\\n','');\nfprintf(fid,'%s\\n','');\nend\n\n\nfprintf('%s\\n','');\nfprintf(fid,'%s\\n','');\nfprintf('%s\\n','');\nfprintf(fid,'%s\\n','');\nfprintf('%s\\n','');\nfprintf(fid,'%s\\n','');\n\n\n\n% display VAR stability results\neigmodulus=reshape(eigmodulus,p,N*n);\nstabilityinfo1=['Roots of the characteristic polynomial (modulus):'];\nfprintf('%s\\n',stabilityinfo1);\nfprintf(fid,'%s\\n',stabilityinfo1);\nfor jj=1:p\ntemp=num2str(eigmodulus(jj,1),'%.3f');\n for kk=2:N*n\n temp=[temp,' ',num2str(eigmodulus(jj,kk),'%.3f')];\n end\nfprintf('%s\\n',temp);\nfprintf(fid,'%s\\n',temp);\nend\nif stationary==1;\nstabilityinfo2=['No root lies outside the unit circle.'];\nstabilityinfo3=['The estimated VAR model satisfies the stability condition'];\nfprintf('%s\\n',stabilityinfo2);\nfprintf(fid,'%s\\n',stabilityinfo2);\nfprintf('%s\\n',stabilityinfo3);\nfprintf(fid,'%s\\n',stabilityinfo3);\nelse\nstabilityinfo2=['Warning: at leat one root lies on or outside the unit circle.'];\nstabilityinfo3=['The estimated VAR model will not be stable'];\nend\n\n\n\nfprintf('%s\\n','');\nfprintf(fid,'%s\\n','');\nfprintf('%s\\n','');\nfprintf(fid,'%s\\n','');\nfprintf('%s\\n','');\nfprintf(fid,'%s\\n','');\n\n\n\n% display posterior for sigma\n% reshape sigma\nsigma_median=reshape(sigma_median,N*n,N*n);\n% start displaying\nsigmainfo=['sigma (residual covariance matrix): posterior estimates'];\nfprintf('%s\\n',sigmainfo);\nfprintf(fid,'%s\\n',sigmainfo);\n% calculate the (integer) length of the largest number in sigma, for formatting purpose\nwidth=length(sprintf('%d',floor(max(abs(bear.vec(sigma_median))))));\n% add a separator, a potential minus sign, and three digits (total=5) to obtain the total space for each entry in the matrix\nwidth=width+5;\nfor ii=1:N*n\ntemp=[];\n for jj=1:N*n\n % convert matrix entry into string\n number=num2str(sigma_median(ii,jj),'% .3f');\n % pad potential missing blanks\n while numel(number) 1)\n warning(sprintf(['The estimated AR model is unstable.\\n',...\n\t\t '\\t Some excitations may be negative.']))\n end\n \n % Fix phase of eigenvectors such that the real part and the\n % imaginary part of each vector are orthogonal\n BigS = adjph(BigS);\n\n % Return only last m components of each eigenvector\n S \t = BigS((p-1)*m+1:p*m, :);\n\n % Compute inverse of BigS for later use\n BigS_inv = inv(BigS);\n\n % Recover the matrix Uinv that appears in the asymptotic covariance\n % matrix of the least squares estimator (Uinv is output of AR)\n if (size(th,2) == m*p+1) \n % The intercept vector has been fitted by AR; in computing\n % confidence intervals for the eigenmodes, this vector is\n % irrelevant. The first row and first column in Uinv,\n % corresponding to elements of the intercept vector, are not\n % needed.\n Uinv = th(3:size(th,1), 2:size(th,2));\n\n elseif (size(th,2) == m*p)\n % No intercept vector has been fitted\n Uinv = th(2:size(th,1), :);\n else\n error('Input arguments of ARMODE must be output of ARFIT.')\n end\n % Number of degrees of freedom \n dof \t = th(1,1); \n % Quantile of t distribution for given confidence coefficient and dof\n t = tquant(dof, .5+ccoeff/2); \n \n % Asymptotic covariance matrix of estimator of coefficient matrix A\n Sigma_A = kron(Uinv, C);\n\n % Noise covariance matrix of system of relaxators and oscillators\n CovDcpld = BigS_inv(:, 1:m) * C * BigS_inv(:, 1:m)';\n\n % For each eigenmode j: compute the period per, the damping time\n % tau, and the excitation exctn; also get the margins of error for\n % per and tau\n for j=1:m*p\t\t\t\t% eigenmode number\n a\t\t= real(lambda(j)); \t% real part of eigenvalue j\n b \t\t= imag(lambda(j)); \t% imaginary part of eigenvalue j\n abs_lambda_sq= abs(lambda(j))^2; \t% squared absolute value of eigenvalue j\n tau(1,j) \t= -2/log(abs_lambda_sq);% damping time of eigenmode j\n\n % Excitation of eigenmode j \n exctn(j) \t= real(CovDcpld(j,j) / (1-abs_lambda_sq)); \n\n % Assemble derivative of eigenvalue with respect to parameters in \n % the coefficient matrix A \n dot_lam \t= zeros(m^2*p, 1);\n for k=1:m\n dot_lam(k:m:k+(m*p-1)*m) = BigS_inv(j,k) .* BigS(1:m*p,j);\n end\n dot_a \t= real(dot_lam); \t% derivative of real part of lambda(j)\n dot_b \t= imag(dot_lam); \t% derivative of imag part of lambda(j)\n \n % Derivative of the damping time tau w.r.t. parameters in A\n phi \t= tau(1,j)^2 / abs_lambda_sq * (a*dot_a + b*dot_b);\n % Margin of error for damping time tau\n tau(2,j) \t= t * sqrt(phi'*Sigma_A*phi);\n \n % Period of eigenmode j and margin of error for period. (The\n % if-statements avoid warning messages that may otherwise result\n % from a division by zero)\n if (b == 0 & a >= 0) % purely real, nonnegative eigenvalue\n per(1,j)\t= Inf; \t\t\n per(2,j) = 0; \n elseif (b == 0 & a < 0) % purely real, negative eigenvalue\n per(1,j)\t= 2; \t\t\n per(2,j) = 0; \n else % complex eigenvalue\n per(1,j)\t= 2*pi/abs(atan2(b,a)); \n \n % Derivative of period with respect to parameters in A\n phi \t= per(1,j)^2 / (2*pi*abs_lambda_sq)*(b*dot_a-a*dot_b);\n % Margin of error for period\n per(2,j) \t= t * sqrt(phi'*Sigma_A*phi);\n end\n end\n\n % Give the excitation as `relative importance' that sums to one\n exctn \t= exctn/sum(exctn);\n \n % Compute confidence intervals for eigenmodes \n % -------------------------------------------\n % Shorthands for matrix products\n XX \t = real(BigS)'*real(BigS);\n YY \t = imag(BigS)'*imag(BigS);\n XY \t = real(BigS)'*imag(BigS);\n\n % Need confidence intervals only for last m rows of BigS\n row1 \t = (p-1)*m+1; % first row for which confidence interval is needed\n\n mp = m*p; \t% dimension of equivalent AR(1) model\n for k=1:mp \t\t\t% loop over columns of S\n for l=row1:mp \t\t\t% loop over rows of S\n\t\t\t\t\t\n % evaluate gradient of S_{lk}\n for ii=1:m\n\tfor jj=1:mp\n\t % compute derivative with respect to A(ii,jj)\n\t zsum = 0;\n\t zkkr = 0; \t\t\t% real part of Z_{kk}\n\t zkki = 0; \t\t\t% imaginary part of Z_{kk}\n\t for j=1:mp\n\t if (j ~= k) \t\t% sum up elements that appear in Z_{kk}\n\t zjk = BigS_inv(j,ii)*BigS(jj,k)/(lambda(k)-lambda(j));\n\t zjkr = real(zjk);\n\t zjki = imag(zjk);\n\t zkkr = zkkr+zjki*(XY(k,j)-XY(j,k))-zjkr*(XX(k,j)+YY(k,j));\n\t zkki = zkki+zjki*(YY(k,j)-XX(k,j))-zjkr*(XY(k,j)+XY(j,k));\n\t zsum = zsum+BigS(l,j)*zjk;\n\t end\n\t end\n\t % now add Z_{kk}\n\t zkki = zkki / (XX(k,k)-YY(k,k));\n\t grad_S((jj-1)*m+ii) = zsum+BigS(l,k)*(zkkr+i*zkki);\n\tend \n end \n Serr(l,k) = t * ( sqrt( real(grad_S)*Sigma_A*real(grad_S)') ...\n\t\t\t + i*sqrt( imag(grad_S)*Sigma_A*imag(grad_S)') );\n end\n end\n\n % Only return last m*p rows of Serr\n Serr = Serr(row1:m*p, :);\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/174-arfit/armode.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289835, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.5393158792452726}} {"text": "function a = r8cbb_add ( n1, n2, ml, mu, a, i, j, value )\n\n%*****************************************************************************80\n%\n%% R8CBB_ADD adds a value to an entry of a R8CBB matrix.\n%\n% Discussion:\n%\n% The R8CBB storage format is for a compressed border banded matrix. \n% Such a matrix has the logical form:\n%\n% A1 | A2\n% ---+---\n% A3 | A4\n%\n% with A1 a (usually large) N1 by N1 banded matrix, while A2, A3 and A4\n% are dense rectangular matrices of orders N1 by N2, N2 by N1, and N2 by N2,\n% respectively. \n%\n% The R8CBB format is the same as the DBB format, except that the banded\n% matrix A1 is stored in compressed band form rather than standard\n% banded form. In other words, we do not include the extra room\n% set aside for fill in during pivoting.\n%\n% A should be defined as a vector. The user must then store\n% the entries of the four blocks of the matrix into the vector A.\n% Each block is stored by columns.\n%\n% A1, the banded portion of the matrix, is stored in\n% the first (ML+MU+1)*N1 entries of A, using the obvious variant\n% of the LINPACK general band format.\n%\n% The following formulas should be used to determine how to store\n% the entry corresponding to row I and column J in the original matrix:\n%\n% Entries of A1:\n%\n% 1 <= I <= N1, 1 <= J <= N1, (J-I) <= MU and (I-J) <= ML.\n%\n% Store the I, J entry into location\n% (I-J+MU+1)+(J-1)*(ML+MU+1).\n%\n% Entries of A2:\n%\n% 1 <= I <= N1, N1+1 <= J <= N1+N2.\n%\n% Store the I, J entry into location\n% (ML+MU+1)*N1+(J-N1-1)*N1+I.\n%\n% Entries of A3:\n%\n% N1+1 <= I <= N1+N2, 1 <= J <= n1.\n%\n% Store the I, J entry into location\n% (ML+MU+1)*N1+N1*N2+(J-1)*N2+(I-N1).\n%\n% Entries of A4:\n%\n% N1+1 <= I <= N1+N2, N1+1 <= J <= N1+N2\n%\n% Store the I, J entry into location\n% (ML+MU+1)*N1+N1*N2+(J-1)*N2+(I-N1).\n% (same formula used for A3).\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 27 February 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N1, N2, the order of the banded and dense blocks.\n% N1 and N2 must be nonnegative, and at least one must be positive.\n%\n% Input, integer ML, MU, the lower and upper bandwidths.\n% ML and MU must be nonnegative, and no greater than N1-1.\n%\n% Input, real A((ML+MU+1)*N1 + 2*N1*N2 + N2*N2), the R8CBB matrix.\n%\n% Input, integer I, J, the indices of the entry to be incremented.\n%\n% Input, real VALUE, the value to be added to the (I,J) entry.\n%\n% Output, real A((ML+MU+1)*N1 + 2*N1*N2 + N2*N2), the modified R8CBB matrix.\n%\n if ( value == 0.0 )\n return;\n end\n%\n% Check for I or J out of bounds.\n%\n if ( i <= 0 .or. n1+n2 < i )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8CBB_ADD - Fatal error!\\n' );\n fprintf ( 1, ' Illegal input value of row index I = %d/n', i );\n error ( 'R8CBB_ADD - Fatal error!' );\n end\n\n if ( j <= 0 | n1+n2 < j )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8CBB_ADD - Fatal error!\\n' );\n fprintf ( 1, ' Illegal input value of column index J = %d/n',j );\n error ( 'R8CBB_ADD - Fatal error!' );\n end\n%\n% The A1 block of the matrix.\n%\n% Check for out of band problems.\n%\n if ( i <= n1 & j <= n1 )\n if ( mu < (j-i) | ml < (i-j) )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8CBB_ADD - Warning!\\n' );\n fprintf ( 1, ' Unable to add to entry (%d,%d).\\n', i, j );\n return\n else\n ij = (i-j+mu+1)+(j-1)*(ml+mu+1);\n end\n%\n% The A2 block of the matrix:\n%\n elseif ( i <= n1 & n1 < j )\n ij = (ml+mu+1)*n1+(j-n1-1)*n1 + i;\n%\n% The A3 and A4 blocks of the matrix.\n%\n elseif ( n1 < i )\n ij = (ml+mu+1)*n1+n2*n1+(j-1)*n2 + (i-n1);\n end\n\n a(ij) = a(ij) + value;\n\n return\nend\n", "meta": {"author": "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/r8cbb_add.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.5393158715512131}} {"text": "function [X,P] = femUnk(fe)\n%+========================================================================+\n%| |\n%| OPENFEM - LIBRARY FOR FINITE ELEMENT METHOD |\n%| openFem is part of the GYPSILAB toolbox for Matlab |\n%| |\n%| COPYRIGHT : Matthieu Aussal & Francois Alouges (c) 2017-2018. |\n%| PROPERTY : Centre de Mathematiques Appliquees, Ecole polytechnique, |\n%| route de Saclay, 91128 Palaiseau, France. All rights reserved. |\n%| LICENCE : This program is free software, distributed in the hope that|\n%| it will be useful, but WITHOUT ANY WARRANTY. Natively, you can use, |\n%| redistribute and/or modify it under the terms of the GNU General Public|\n%| License, as published by the Free Software Foundation (version 3 or |\n%| later, http://www.gnu.org/licenses). For private use, dual licencing |\n%| is available, please contact us to activate a \"pay for remove\" option. |\n%| CONTACT : matthieu.aussal@polytechnique.edu |\n%| francois.alouges@polytechnique.edu |\n%| WEBSITE : www.cmap.polytechnique.fr/~aussal/gypsilab      |\n%| |\n%| Please acknowledge the gypsilab toolbox in programs or publications in |\n%| which you use it. |\n%|________________________________________________________________________|\n%| '&` | |\n%| # | FILE : femUnk.m |\n%| # | VERSION : 0.40 |\n%| _#_ | AUTHOR(S) : Matthieu Aussal & François Alouges |\n%| ( # ) | CREATION : 14.03.2017 |\n%| / 0 \\ | LAST MODIF : 14.03.2018 |\n%| ( === ) | SYNOPSIS : Unknowns and reduction matrix for constrained |\n%| `---' | finite elements |\n%+========================================================================+\n\n% Initialization with dofs\nX = fe.dof;\nNx = size(X,1);\nP = speye(Nx);\n\n% Dirichlet\nif ~isempty(fe.dir)\n % Finite element for dirichlet mesh\n fed = fem(fe.dir,fe.typ);\n \n % Dof indices\n I = find(~ismember(X,fed.dof,'rows'));\n \n % Reduction matrix\n M = speye(Nx);\n M = M(:,I);\n \n % Update\n P = P * M;\n X = X(I,:);\n Nx = length(I);\nend\n\n% Junction\nif ~isempty(fe.jct)\n % Number of junction\n Njct = length(fe.jct)/2;\n \n % Initialization\n feJct = cell(1,Njct);\n Ijct = cell(1,Njct);\n \n % Finite element for junction meshes\n for i = 1:Njct\n if isa(fe.jct{2*i-1},'msh') && isnumeric(fe.jct{2*i})\n feJct{i} = fem(fe.jct{2*i-1},fe.typ);\n else\n error('femUnknown.m : unavailable case');\n end\n end\n \n % Valid dof indices for junction meshes \n for i = 1:Njct\n Xi = feJct{i}.dof;\n Ijct{i} = zeros(size(Xi,1),1);\n [~,I,J] = intersect(Xi,X,'rows','stable');\n Ijct{i}(I) = J; \n end\n Ijct = cell2mat(Ijct);\n \n % Extract dirichlet condition and multiple indices\n bool = (Ijct(:,Njct) == 0);\n for i = 1:Njct-1\n bool = bool + (Ijct(:,Njct) == Ijct(:,i));\n end\n Ijct = Ijct(~bool,:);\n \n % Final dof after extraction of the last indices\n I = setdiff((1:Nx)',Ijct(:,end));\n\n % Linear relation matrix\n M = speye(Nx);\n for i = 1:Njct\n for j = setdiff(1:Njct,i) \n M = M + sparse(Ijct(:,i),Ijct(:,j),-fe.jct{2*j}/fe.jct{2*i},Nx,Nx);\n end\n end \n \n % Reduction\n M = M(:,I);\n \n % Update\n P = P * M;\n X = X(I,:);\n% Nx = length(I);\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/openFem/femUnk.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788995148792, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.5393012227563636}} {"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% Apr. 3, 2015 (NB):\n% Replaced trace(A'*B) by A(:)'*B(:) : equivalent but faster.\n% \n% Apr. 17, 2018 (NB):\n% Removed dependency on lyap entirely.\n%\n% Sep. 6, 2018 (NB):\n% Removed M.exp() as it was not implemented.\n\n% TODO: modify normalize_rows and project_rows to work without transposes.\n% TODO: enhance ehess2rhess to also use bsxfun.\n \n if k < 2\n warning('manopt:elliptopefactory:lowk', ...\n 'k should be an integer >= 2. At k = 1, the set is discrete.');\n end\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 % 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 norms = sqrt(sum(X.^2, 1));\n X = 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 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 Omega = lyapunov_symmetric(SS, AS);\n \n % It does not seem necessary to enforce skew-symmetry numerically.\n % Omega = (Omega-Omega')/2;\n \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% 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": "NicolasBoumal", "repo": "manopt", "sha": "b8b54a6af8b965f7ae572972ba0d15787427744b", "save_path": "github-repos/MATLAB/NicolasBoumal-manopt", "path": "github-repos/MATLAB/NicolasBoumal-manopt/manopt-b8b54a6af8b965f7ae572972ba0d15787427744b/manopt/manifolds/symfixedrank/elliptopefactory.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5390777595268267}} {"text": "function varargout = linop_test( op, cmode, maxits )\n\n%LINOP_TEST Performs an adjoint test on a linear operator.\n% LINOP_TEST( OP ) attempts to verify that a linear operator OP obeys\n% the inner product test: = for all x, y. OP must be a\n% TFOCS linear operator with hard-coded size information; that is,\n% OP([],0) must return valid size info.\n%\n% When called with a single argument, LINOP_TEST creates real test\n% vectors for X and Y. To test complex operators, use the two-argument\n% version LINOP_TEST( OP, cmode ), where:\n% cmode = 'R2R': real input, real output\n% cmode = 'R2C': real input, complex output\n% cmode = 'R2CC': real input, conjugate-symmetric complex output\n% cmode = 'C2R': complex input, real output\n% cmode = 'CC2R': conjugate-symmetric complex input, real output\n% cmode = 'C2C': complex input, complex output\n%\n% The conjugate-symmetric options follow the symmetry conventions of Matlab's FFT.\n%\n% LINOP_TEST( OP, CMODE, MAXITS ) performs MAXITS iterations of the\n% test loop. MAXITS=25 is the default.\n%\n% myNorm = LINOP_TEST(...) returns an estimate of the myNorm of\n% the linear operator.\n\nerror(nargchk(1,3,nargin));\nif isnumeric( op ),\n if nargin < 2 || isempty( cmode )\n disp('warning: for matrix inputs, this assumes the cmode is ''C2C'' unless you specify otherwise');\n cmode = 'C2C'; \n end\n op = linop_matrix( op, cmode );\nend\ny_conjSymmetric = false;\nx_conjSymmetric = false;\nif nargin < 2 || isempty( cmode ),\n x_real = true;\n y_real = true;\nelse\n switch upper( cmode ),\n case 'R2R', x_real = true; y_real = true;\n case 'R2C', x_real = true; y_real = false;\n case 'R2CC', x_real = true; y_real = false; y_conjSymmetric = true;\n case 'C2R', x_real = false; y_real = true;\n case 'CC2R', x_real = false; y_real = true; x_conjSymmetric = true;\n case 'C2C', x_real = false; y_real = false;\n case 'CC2CC', x_real = false; y_real = false; \n x_conjSymmetric = true;\n y_conjSymmetric = true; % this is probably never going to happen though\n otherwise, error( 'Invalid cmode: %s', cmode );\n end\nend\nif nargin < 3 || isempty(maxits),\n maxits = 25;\nend\nsz = op([],0);\nif ~iscell(sz)\n sz = { [sz(2),1], [sz(1),1] };\nelseif isempty(sz{1})\n disp('warning: could not detect the size; this often happens when using a scalar input, which represents scaling');\n if isempty( sz{2} )\n disp(' Proceeding under the assumption that the domain is 1D');\n sz{1} = [1,1];\n sz{2} = [1,1];\n else\n disp(' Proceeding under the assumption that the domain equals the range');\n sz{1} = sz{2};\n end\nelseif isempty(sz{2})\n disp('warning: could not detect the size; this often happens when using a scalar input, which represents scaling');\n disp(' Proceeding under the assumption that the domain equals the range');\n sz{2} = sz{1};\nend\nnf = 0;\nna = 0; \nerrs = zeros(1,maxits+1);\nnxe = 0; nye = 0;\nfor k = 1 : maxits,\n \n %\n % The adjoint test\n %\n \n if x_real,\n x = randn(sz{1});\n else\n x = randn(sz{1})+1j*randn(sz{1});\n if x_conjSymmetric\n x = make_conj_symmetrix( x );\n end\n end\n \n if y_real,\n y = randn(sz{2});\n else\n y = randn(sz{2})+1j*randn(sz{2});\n if y_conjSymmetric\n y = make_conj_symmetrix( y );\n end\n end\n \n nx = myNorm(x);\n Ax = op(x,1);\n nf = max( nf, myNorm(Ax)/nx );\n Ax_y = tfocs_dot( Ax, y ); \n \n ny = myNorm(y);\n Ay = op(y,2);\n na = max( na, myNorm(Ay) / ny );\n Ay_x = tfocs_dot( x, Ay ); \n \n errs(k) = abs(Ax_y-Ay_x)/(nx*ny);\n \n %\n % The myNorm iteration\n %\n \n if nxe == 0,\n if x_real,\n xx = randn(sz{1});\n else\n xx = randn(sz{1}) + 1j*randn(sz{1});\n if x_conjSymmetric\n xx = make_conj_symmetrix( xx );\n end\n end\n nxe = myNorm(xx);\n end\n yy = op(xx/nxe,1);\n nye = max(realmin,myNorm(yy));\n xx = op(yy/nye,2);\n nxe = myNorm(xx);\n \nend\n\n%\n% Use the estimated singular vectors for a final adjoint est\n%\n\nif nxe > 0,\n Ax_y = tfocs_dot( op(xx,1), yy );\n Ay_x = tfocs_dot( op(yy,2), xx );\n errs(end) = abs(Ax_y-Ay_x) / (nxe*nye);\nend\n\n%\n% Display the output\n% \n\nnmax = max(nye,nxe);\nmyNorm_err = abs(nye-nxe) / nmax;\npeak_err = max(errs) / nmax;\nmean_err = mean(errs) / nmax;\nrc = { 'complex', 'real', 'complex symmetric' };\nfprintf( 'TFOCS linear operator test:\\n' );\nfprintf( ' Input size: [' ); fprintf( ' %d', sz{1} ); fprintf( ' ], %s\\n', rc{x_real+1+2*x_conjSymmetric} );\nfprintf( ' Output size: [' ); fprintf( ' %d', sz{2} ); fprintf( ' ], %s\\n', rc{y_real+1+2*y_conjSymmetric} );\nfprintf( 'After %d iterations:\\n', maxits );\nfprintf( ' myNorm estimates (forward/adjoint/error): %g/%g/%g\\n', nye, nxe, myNorm_err );\nfprintf( ' Gains: forward %g, adjoint %g\\n', nf, na );\nfprintf( ' Inner product error:\\n' );\nfprintf( ' Mean (absolute/relative): %g/%g\\n', mean(errs), mean_err );\nfprintf( ' Peak (absolute/relative): %g/%g\\n', max(errs), peak_err );\nfprintf( ' (inner product errors should 1e-10 or smaller)\\n');\n\ngood = true;\nif myNorm_err/max( nye, nxe ) > 1e-4\n fprintf(' Detected mismatch in forward/adjoint norm estimates. This is potentially a bad sign. Check your implementation\\n');\n good = false;\nend\nif mean_err > 1e-8\n fprintf(' The mean error (relative) is high. This is a bad sign. Check your implementation\\n');\n good = false;\nend\nif good\n fprintf(' Allowing for some roundoff error, there are no obvious errors. This is good.\\n');\nend\n\nif nargout > 0\n varargout{1} = mean([nye,nxe]);\nend\n\n\n% Improvement as suggested by Graham Coleman\n% Allows for 3D arrays.\n% This also changes default behavior of 2D arrays\n% to now use the Frobenius norm instead of spectral norm.\n% This is wise, since it's a much quicker computation.\nfunction y = myNorm(x)\ny = norm( x(:) );\n\nfunction y = make_conj_symmetrix( y )\nny = size( y, 1 );\ny(1,:) = real(y(1,:)); % DC component is 0\nif round(ny/2) == ny/2 % even\n y(ny/2+1,:) = real(y(ny/2+1,:)); % Nyquist component is 0\n y( ny:-1:(ny/2+2) ) = conj( y(2:ny/2) );\nelse % odd\n y( ny:-1:((ny+1)/2+1) ) = conj( y(2:((ny+1)/2)) );\nend\n\n\n% TFOCS v1.3 by Stephen Becker, Emmanuel Candes, and Michael Grant.\n% Copyright 2013 California Institute of Technology and CVX Research.\n% See the file LICENSE for full license information.\n", "meta": {"author": "cvxr", "repo": "TFOCS", "sha": "164ada20401cd445930673e42bb3d2a5489f2030", "save_path": "github-repos/MATLAB/cvxr-TFOCS", "path": "github-repos/MATLAB/cvxr-TFOCS/TFOCS-164ada20401cd445930673e42bb3d2a5489f2030/linop_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7371581626286833, "lm_q2_score": 0.7310585844894971, "lm_q1q2_score": 0.5389058029162037}} {"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 [yc,dy,para] = getTrafoFromVelocityRK4(vc,yc,varargin)\n%\n% compute transformation yc by integrating velocity field in time using \n% a fourth-order Runge-Kutta method. Here, vc is assumed to be stationary. \n% For instationary velocities, use getTrafoFromInstatinaryVelocityRK4.m\n%\n% For more details see Sec. 3 of the paper:\n%\n% @article{MangRuthotto2017,\n% Title = {A {L}agrangian {G}auss--{N}ewton--{K}rylov solver for mass- and intensity-preserving diffeomorphic image registration},\n% Year = {2017},\n% Journal = {SIAM Journal on Scientific Computing},\n% Author = {A. Mang, L. Ruthotto},\n% }\n%\n% Input:\n%\n% vc - discrete velocity field (nodal, cell-centered, or staggered)\n% yc - particle positions\n%\n% Additional REQUIRED Input (provided through varargin)\n%\n% omega - spatial domain (required!)\n% m - number of cells in each direction (required!)\n%\n% Optional Input (provided through varargin)\n%\n% doDerivative - compute derivative w.r.t. velocity\n% tspan - time interval (default: [0 1]) \n% N - number of time discretization points (nodal) (default: 5)\n% storeInter - store intermediate transformation (e.g., for visualization)\n%\n% Output:\n%\n% yc - end point of characteristics\n% dy - derivative w.r.t. vc\n% para - info such as CFL\n%\n% =========================================================================\nfunction [yc,dy,para] = getTrafoFromVelocityRK4(vc,yc,varargin)\n\nif nargin==0\n runMinimalExample\n return;\nend\ndoDerivative = (nargout>1);\nomega = [];\nm = [];\ntspan = [0 1];\nN = 5;\nstoreInter = false;\nfor k=1:2:length(varargin) % overwrites default parameter\n eval([varargin{k},'=varargin{',int2str(k+1),'};']);\nend;\nif isempty(omega) || isempty(m)\n error('%s - omega and m must be provided through varargin or trafo(''set'',''omega'',omega,''m'',m')\nend\ndt = (tspan(2)-tspan(1))/(N-1); % note dt is negatave when going backwards in time\ndy = [];\nif doDerivative\n dy = sparse(numel(yc),numel(vc));\nend\n% compute the CFL number (not actually required for stability in Lagrangian\n% methods, but an indicator of how many voxels the particles may move in\n% one time step.\nh = (omega(2:2:end)-omega(1:2:end))./m;\n% vt = sqrt(sum(reshape(vc.^2,[],dim),2));\n% CFL = max(vt)*dt/min(h);\nCFL = 0.0;\npara = struct('CFL',CFL,'dt',dt,'N',N,'omega',omega,'m',m,'h',h);\nif storeInter\n para.YC = zeros(numel(yc),N);\n para.YC(:,1) = yc;\nend\nfor k=1:N-1\n [vi,dvidy] = linearInterGrid(vc,omega,m,yc,'doDerivative',doDerivative);\n if doDerivative\n Ty = getLinearInterGridMatrix(omega,m,yc);\n dyi = Ty + dvidy*dy;\n dytemp = dyi;\n end\n ytemp = vi;\n yi = yc + .5*dt*vi; \n\n [vi,dvidy] = linearInterGrid(vc,omega,m,yi,'doDerivative',doDerivative);\n if doDerivative\n Ty = getLinearInterGridMatrix(omega,m,yi);\n dyi = Ty + dvidy*(dy+.5*dt*dyi);\n dytemp = dytemp + 2*dyi;\n end\n ytemp = ytemp + 2*vi;\n yi = yc + .5*dt*vi;\n\n [vi,dvidy] = linearInterGrid(vc,omega,m,yi,'doDerivative',doDerivative);\n if doDerivative\n Ty = getLinearInterGridMatrix(omega,m,yi);\n dyi = Ty + dvidy*(dy+.5*dt*dyi);\n dytemp = dytemp + 2*dyi;\n end\n ytemp = ytemp + 2*vi;\n yi = yc + dt*vi;\n [vi,dvidy] = linearInterGrid(vc,omega,m,yi,'doDerivative',doDerivative);\n if doDerivative\n Ty = getLinearInterGridMatrix(omega,m,yi);\n dyi = Ty + dvidy*(dy+dt*dyi);\n dytemp = dytemp + dyi;\n dy = dy + (dt/6)*dytemp;\n end\n ytemp = ytemp + vi;\n yc = yc + (dt/6)*ytemp;\n if storeInter, para.YC(:,k+1) = yc; end\nend\n\n\n\n\nfunction runMinimalExample\n\nomegaV = [-1 1 -1 1];\nomega = .1*omegaV;\nm = [24 24];\ntspan = [2 3];\nN = 2;\nyc = getNodalGrid(omega,m)+.0002;\n\n\n% test cell-centered grid\nregularizer('set','regularizer','mbCurvature','alpha',1)\nxc = reshape(getCellCenteredGrid(omegaV,m),[],2);\nvc = [.3*sign(xc(:,1)).*xc(:,1).^2 sin(pi*xc(:,2))];\nfctn = @(vc) getTrafoFromVelocityRK4(vc,yc,'omega',omegaV,'m',m,'T',tspan,'N',N);\ncheckDerivative(fctn,vc(:))\n\n\n% test nodal grid\nregularizer('set','regularizer','mbElasticNodal','alpha',1)\nxc = reshape(getNodalGrid(omegaV,m),[],2);\nvc = [.3*sign(xc(:,1)).*xc(:,1).^2 sin(pi*xc(:,2))];\nfctn = @(vc) getTrafoFromVelocityRK4(vc,yc,'omega',omegaV,'m',m,'T',tspan,'N',N);\ncheckDerivative(fctn,vc(:))\n\n% test staggered grid\nregularizer('set','regularizer','mbElastic','alpha',1)\nvc = grid2grid(vc(:),m,'nodal','staggered');\nfctn = @(vc) getTrafoFromVelocityRK4(vc,yc,'omega',omegaV,'m',m,'T',tspan,'N',N);\ncheckDerivative(fctn,vc(:))\n\nomegaV = [-1 1 -1 1 -1 1];\nomega = .1*omegaV;\nm = [16 16 8];\ntspan = [4 3];\nN = 10;\nyc = getNodalGrid(omega,m)+.0002;\n\nregularizer('set','regularizer','mbCurvature','alpha',1)\nxc = reshape(getCellCenteredGrid(omegaV,m),[],3);\nvc = [.3*sign(xc(:,1)).*xc(:,1).^2 sin(pi*xc(:,2)) xc(:,3)];\nfctn = @(vc) getTrafoFromVelocityRK4(vc,yc,'omega',omegaV,'m',m,'T',tspan,'N',N);\n% [yc,dy] = fctn(vc(:));\ncheckDerivative(fctn,0*vc(:))\n\n% test nodal grid\nregularizer('set','regularizer','mbElasticNodal','alpha',1)\nxc = reshape(getNodalGrid(omegaV,m),[],3);\nvc = [.3*sign(xc(:,1)).*xc(:,1).^2 sin(pi*xc(:,2)) xc(:,3)];\nfctn = @(vc) getTrafoFromVelocityRK4(vc,yc,'omega',omegaV,'m',m,'T',tspan,'N',N);\ncheckDerivative(fctn,vc(:))\n\n% test staggered grid\nregularizer('set','regularizer','mbElastic','alpha',1)\nvc = grid2grid(vc(:),m,'nodal','staggered');\nfctn = @(vc) getTrafoFromVelocityRK4(vc,yc,'omega',omegaV,'m',m,'T',tspan,'N',N);\ncheckDerivative(fctn,vc(:))\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/getTrafoFromVelocityRK4.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8459424373085145, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.5388913829233147}} {"text": "%This Matlab script can be used to reproduce Figure 7.13 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\nlambda = 1; %Wavelength (normalized)\nM_H = 8; %Number of antenna per horizontal row\nM_V = 4; %Number of rows\nd_H = 0.5*lambda; %Horizontal antenna spacing\nd_V = 0.5*lambda; %Vertical antenna spacing\n\n%Define the antenna geometry\nM = M_H*M_V; %Total number of antennas\nU = zeros(3,M); %Matrix containing the position of the antennas\n\ni = @(m) mod(m-1,M_H); %Horizontal index\nj = @(m) floor((m-1)/M_H); %Vertical index\n\nfor m = 1:M\n U(:,m) = [0; i(m)*d_H; j(m)*d_V]; %Position of the mth element\nend\n\n\n%% Compute the spatial signature for various directions\nvarphi = linspace(-pi/2,pi/2,1000);\ntheta= [0,-pi/3];\nP = zeros(length(varphi),length(theta));\nv = ones(M,1);\n\nfor i = 1:length(varphi)\n \n for j = 1:length(theta)\n \n P(i,j) = abs(v'*functionSpatialSignature3DLoS(U,varphi(i),theta(j),lambda))/M;\n \n end\n \nend\n\nP = P/max(max(P));\nP = 10*log10(P);\n\n\n%% Plot the simulation results\nfigure;\nhold on; box on;\nplot(varphi/pi,P(:,1)','-k','LineWidth',1)\nplot(varphi/pi,P(:,2)','r--','LineWidth',1)\n\nylim([-30,0])\nax = gca;\nset(ax, 'XTick', [-0.5, -0.25, 0, 0.25, 0.5]);\nxlabel('Azimuth angle $\\varphi$ in multiples of $\\pi$','Interpreter','latex');\nylabel('Normalized array response [dB]');\nlegend({'$\\theta = 0$', '$\\theta = -\\pi/3$ '},'Interpreter','latex');\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_figure13.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146848, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.538871479889652}} {"text": "function [xUpdate,PUpdate,innov,Pzz,W]=QMCKalUpdateWithPred(z,R,zPred,PzPred,otherInfo)\n%%QMCKALUPDATEWITHPRED Given the output of the measurement prediction step\n% from QMCKalMeasPred and a measurement, complete the measurement\n% update step of the quasi-Monte Carlo Kalman filter with\n% additive measurement noise. Separating the measurement\n% prediction step from the rest of the update step can make the\n% creation of multiple measurement association hypotheses from a\n% single target prediction more efficient. The full measurement\n% update function is QMCKalUpdate.\n%\n%INPUTS: z The zDimX1 vector measurement.\n% R The zDim X zDim measurement covariance matrix in the native\n% coordinate system of the measurement.\n% zPred The zDimXnumComp measurement predictions from the filter.\n% PzPred The zDimXzDimXnumComp covariance matrices associated with zPred.\n% otherInfo The intermediate results returned in the otherInfo output of\n% the QMCKalMeasPred function.\n%\n%OUTPUTS: xUpdate The xDimXnumComp updated state vectors.\n% PUpdate The updated xDimXxDimXnumComp state covariance matrices\n% associated with xUpdate.\n% innov, Pzz The zDimXnumComp innovations and the zDimXzDim innovation\n% covariance matrices are returned in case one wishes to\n% analyze the consistency of the estimator or use those\n% values in gating or likelihood evaluation.\n% W The xDimXzDimXnumComp gains used in the update.\n%\n%See the comments to the function QMCKalMeasPred for an example of usage of\n%this function. See the comments to QMCKalUpdate for more information on\n%the algorithm.\n%\n%June 2018 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\ninnovTrans=otherInfo.innovTrans;\nstateTrans=otherInfo.stateTrans;\nxPred=otherInfo.xPred;\nPPred=otherInfo.PPred;\nPxz=otherInfo.Pxz;\n\nxDim=size(xPred,1);\nnumComp=size(xPred,2);\nzDim=size(z,1);\n\nxUpdate=zeros(xDim,numComp);\nPUpdate=zeros(xDim,xDim,numComp);\ninnov=zeros(zDim,numComp);\nPzz=zeros(zDim,zDim,numComp);\nW=zeros(xDim,zDim,numComp);\n\nfor k=1:numComp\n Pzz(:,:,k)=PzPred(:,:,k)+R;\n\n %The innovation, transformed as necessary to keep values in a desired\n %range.\n innov(:,k)=innovTrans(z,zPred(:,k));\n\n %The filter gain\n W(:,:,k)=Pxz(:,:,k)/Pzz(:,:,k);\n\n %Updated state estimate\n xUpdate(:,k)=stateTrans(xPred(:,k)+W(:,:,k)*innov(:,k));\n\n %Updated state covariance matrix\n PUpdate(:,:,k)=PPred(:,:,k)-W(:,:,k)*Pzz(:,:,k)*W(:,:,k)';\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_Estimation/Measurement_Update/Update_Parts/Filter_Update_With_Prediction/QMCKalUpdateWithPred.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146847, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5388714798896519}} {"text": "function [I,B1,B2,B3] = in_element(V,F,P,varargin)\n % IN_ELEMENT test for each p in P whether it lies inside each f in F defined\n % over V.\n % \n % I = in_element(V,F,P)\n % [I,B1,B2,B3] = in_element(V,F,P,'ParameterName',ParameterValue,...)\n % \n % Inputs:\n % V #V by dim list of vertex positions\n % F #F by dim+1 list of element indices\n % P #P by dim list of query positions\n % Optional:\n % 'Method' followed by one of the following {'knn'}:\n % 'brute-force' no acceleration O(#P * #F)\n % 'edge-walk' walk along edges ~O(#P * sqrt(#F)) Starting with a random\n % barycenter step along the edges that intersect with the ray toward\n % the query point. If a boundary is reached then search along all\n % boundary edges and jump to farthest hit. **dim=2 only**\n % 'knn' use knnsearch to find closest element barycenters\n % 'spatial-hash' spatial hash on regular grid ~O(#P * sqrt(#F)) **dim=2\n % only**\n % 'First' only keep first match {false}\n % 'Quiet' suppress warnings {false}\n % 'Epsilon' epsilon used for determining inclusion {eps}\n % Outputs:\n % I #P by #F matrix of bools\n % B1 #P by #F list of barycentric coordinates\n % B2 #P by #F list of barycentric coordinates\n % B3 #P by #F list of barycentric coordinates \n %\n % Example:\n % P = bsxfun(@plus,min(V),bsxfun(@times,rand(100,2),max(V)-min(V)));\n % [I,B1,B2,B3] = in_element(V,F,P);\n % % Only keep first\n % [mI,J] = max(I,[],2);\n % I = sparse(1:size(I,1),J,mI,size(I,1),size(I,2));\n % % Mask barycentric coordinates\n % B1 = B1.*I;\n % B2 = B2.*I;\n % B3 = B3.*I;\n % Q = B1*V(F(:,1),:) + B2*V(F(:,2),:) + B3*V(F(:,3),:);\n % Q = Q(any(I,2),:);\n % tsurf(F,V);\n % hold on;\n % plot(Q(:,1),Q(:,2),'or','LineWidth',6);\n % plot(P(:,1),P(:,2),'ob','LineWidth',2);\n % hold off;\n %\n\n\n function [I] = in_element_brute_force(V,F,P)\n dim = size(V,2);\n assert(dim+1 == size(F,2));\n \n % number of elements \n m = size(F,1);\n % number of query points \n np = size(P,1);\n \n switch dim \n case 3\n T = F;\n % tet face ares\n vol = abs(volume(V,T));\n allF = [ ...\n T(:,2) T(:,4) T(:,3); ...\n T(:,1) T(:,3) T(:,4); ...\n T(:,1) T(:,4) T(:,2); ...\n T(:,1) T(:,2) T(:,3); ...\n ];\n % List of tets for each face f of each tet t for each point p\n TP = cat(2, ...\n repmat(allF,[1 1 np]), ...\n permute(repmat(size(V,1)+(1:np),m*4,1),[1 3 2]));\n TP = reshape(permute(TP,[1 3 2]),m*4*np,dim+1);\n Pvol = abs(volume([V;P],TP));\n % Pvol(t,f,p) --> volume of tet t, face f with point p\n Pvol = reshape(Pvol,[size(T,1) dim+1 np]);\n % sumvol(p,t) --> sum of volumes of tets made with faces of t and p\n sumvol = permute(sum(Pvol,2),[3 1 2]);\n I = sparse(abs(bsxfun(@minus,sumvol,vol')) < sqrt(epsilon));\n case 2\n % triangle side lengths\n l = [ ...\n sqrt(sum((V(F(:,2),:)-V(F(:,3),:)).^2,2)) ...\n sqrt(sum((V(F(:,3),:)-V(F(:,1),:)).^2,2)) ...\n sqrt(sum((V(F(:,1),:)-V(F(:,2),:)).^2,2)) ...\n ];\n \n B = zeros([np m dim+1]);\n for ii = 1:(dim+1)\n jj = mod(ii+1,dim+1)+1;\n kk = mod(ii,dim+1)+1;\n ljj = pdist2(P,V(F(:,jj),:));\n lkk = pdist2(P,V(F(:,kk),:));\n \n % semiperimeters\n s = bsxfun(@plus,l(:,ii)',ljj + lkk)*0.5;\n % Heron's formula for area\n B(:,:,ii) = 2*sqrt(s.*(bsxfun(@minus,s,l(:,ii)').*(s-ljj).*(s-lkk)));\n end\n % sum of barycentric coordinates\n sumA = sum(B,3);\n % area of element\n dblA = doublearea(V,F);\n %% check whether sum is more than true are\n %I = ~bsxfun(@gt,sumA,dblA');\n I = sparse((bsxfun(@minus,sumA,dblA')) < sqrt(epsilon));\n case 1\n % To-do: this is actually being computed in a dense way\n I = sparse( ...\n ((P <= V(F(:,1))') & (P >= V(F(:,2))')) | ...\n ((P <= V(F(:,2))') & (P >= V(F(:,1))')));\n end\n %B1 = sparse(B(:,:,1));\n %B2 = sparse(B(:,:,2));\n %B3 = sparse(B(:,:,3));\n end\n\n function I = in_element_hash_helper(V,F,P)\n assert(size(F,2) == 3, ...\n 'F must contain triangles for Method=''spatial-hash''');\n num_bins = ceil(sqrt(size(F,1)));\n bin_x = ceil(sqrt(num_bins));\n bin_y = ceil(num_bins/bin_x); \n num_bins = bin_x*bin_y;\n % spatial hash\n function VH = hash(V,MN,MX,bin_x,bin_y)\n [~,X] = histc(V(:,1),linspace(MN(1),MX(1),bin_x));\n [~,Y] = histc(V(:,2),linspace(MN(2),MX(2),bin_y));\n VH = sub2ind([bin_x bin_y],X,Y);\n end\n %% http://stackoverflow.com/a/5929567/148668\n %primes = [ 40960001, 59969537 45212177];\n %hash = @(X) mod( ...\n % bitxor( int32(V(:,1)*primes(1)), int32(V(:,2)*primes(2))), ...\n % num_bins);\n MN = min([V;P]);\n MX = max([V;P]);\n VH = hash(V,MN,MX,bin_x,bin_y);\n PH = hash(P,MN,MX,bin_x,bin_y);\n % This is wrong for triangles that span more hash cells than their vertices:\n % any time a triangle lands on the corner....\n FH = sparse(repmat(1:size(F,1),1,size(F,2))',VH(F(:)),1,size(F,1),num_bins)~=0;\n [~,FHI,FHJ] = find(FH);\n [FHJX,FHJY] = ind2sub([bin_x,bin_y],FHJ);\n % This assumes that #P >> #F\n I = sparse(size(P,1),size(F,1));\n for h = 1:num_bins\n %Vh = V(VH==h,:);\n IFh = FH(:,h);\n if any(IFh)\n IPh = PH==h;\n Ph = P(IPh,:);\n if any(IPh)\n Fh = F(IFh,:);\n Ih = in_element_brute_force(V,Fh,Ph);\n I(IPh,IFh) = Ih;\n end\n end\n end\n end\n\n % default values\n method = [];\n first = false;\n quiet = false;\n epsilon = eps;\n % Map of parameter names to variable names\n params_to_variables = containers.Map( {'Method','First','Quiet','Epsilon'}, ...\n {'method','first','quiet','epsilon'});\n v = 1;\n while v <= numel(varargin)\n param_name = varargin{v};\n if isKey(params_to_variables,param_name)\n assert(v+1<=numel(varargin));\n v = v+1;\n % Trick: use feval on anonymous function to use assignin to this\n % workspace\n feval(@()assignin('caller',params_to_variables(param_name),varargin{v}));\n else\n error('Unsupported parameter: %s',varargin{v});\n end\n v=v+1;\n end\n if isempty(method)\n switch size(V,2)\n case 1\n method = 'brute-force';\n otherwise \n method = 'knn';\n end\n end\n\n switch method\n case 'brute-force'\n I = in_element_brute_force(V,F,P);\n case 'spatial-hash'\n % Try 45?? spatial grid, too (reduce corner cases)\n switch size(V,2)\n case 2\n R = [cos(pi/4) -sin(pi/4);sin(pi/4) cos(pi/4)];\n case 3\n R = [cos(pi/4) -sin(pi/4) 0 ;sin(pi/4) cos(pi/4) 0; 0 0 1];\n end\n I = in_element_hash_helper(V,F,P) | in_element_hash_helper(V*R,F,P*R);\n\n % Find any obviously incorrect values: not inside but winding number says\n % inside. Could still missing something if mesh overlaps itself.\n NI = ~any(I,2);\n switch size(F,2)\n case 3\n O = outline(F);\n case 4\n O = boundary_faces(F);\n end\n WI = abs(winding_number(V,O,P(NI,:))/(2*pi))>0.5;\n WI = sparse(find(NI),1,WI,size(P,1),1)~=0;\n % redo any that currently are not in any but winding number says are inside\n RI = NI & WI;\n I(RI,:) = in_element_brute_force(V,F,P(RI,:));\n\n case 'edge-walk'\n\n assert(size(F,2) == 3,'F must contain triangles for Method=''edge-walk''');\n % List of all \"half\"-edges: 3*#F by 2\n allE = [F(:,[2 3]); F(:,[3 1]); F(:,[1 2])];\n % Sort each row\n sortallE = sort(allE,2);\n % IC(i) tells us where to find sortallE(i,:) in uE:\n % so that sortallE(i,:) = uE(IC(i),:)\n [uE,~,IC] = unique(sortallE,'rows');\n % uE2F(e,f) = i means face f's ith edge is unique edge e\n uE2F = sparse(IC(:),repmat(1:size(F,1),1,3)',reshape(repmat(1:3,size(F,1),1),[],1));\n % uE2F(e,f) = 1 means face f is adjacent to unique edge e\n uE2F1 = sparse(IC(:),repmat(1:size(F,1),1,3)',1);\n % Face-face Adjacency matrix\n A = uE2F1'*uE2F;\n % A(f,g) = i means face f's ith edge is shared with g\n A = A-diag(diag(A));\n\n I = sparse(size(P,1),size(F,1));\n B1 = sparse(size(I,1),size(I,2));\n B2 = sparse(size(I,1),size(I,2));\n B3 = sparse(size(I,1),size(I,2));\n\n [~,is_b] = on_boundary(F);\n EF = repmat(1:size(F,1),1,3)';\n EFI = reshape(repmat(1:3,size(F,1),1),[],1);\n O = allE(is_b(:),:);\n OF = EF(is_b(:));\n OFI = EFI(is_b(:));\n\n % initial closest vertex\n BC = barycenter(V,F);\n % Centroid\n f_init = snap_points(mean(V),BC);\n %% Random initial guess\n %f_init = ceil(rand(1,1)*size(F,1));\n for p = 1:size(P,1)\n % current closest face, barycenter\n f = f_init;\n q = BC(f_init,:);\n % incoming edge\n e_in = [];\n while true\n % current point\n % edges to test\n E = ... %mod(bsxfun(@plus,setdiff([1;2;3],e_in),-1+(1:2)),3)+1;\n [2 3;3 1;1 2];\n out = ...\n lineSegmentIntersect([q P(p,:)],[V(F(f,E(:,1)),:) V(F(f,E(:,2)),:)]);\n out.intAdjacencyMatrix(e_in) = false;\n e_out = find(out.intAdjacencyMatrix);\n if isempty(e_out)\n % no hits so we're in the element\n I(p,f) = 1;\n B = barycentric_coordinates( ...\n P(p,:),V(F(f,1),:),V(F(f,2),:),V(F(f,3),:));\n B1(p,f) = B(1); B2(p,f) = B(2); B3(p,f) = B(3);\n else\n f_prev = f;\n if numel(e_out) > 1\n % Take farthests\n [sd,si] = sort(out.intNormalizedDistance1To2(e_out),'descend');\n e_out = e_out(si(1));\n % TODO: recurse on all in f\n end\n f = find(A(:,f_prev)==e_out);\n % Todo if \n if isempty(f)\n % no neighbors so we're shooting outside.\n out = ...\n lineSegmentIntersect([q P(p,:)],[V(O(:,1),:) V(O(:,2),:)]);\n hits = find(out.intAdjacencyMatrix);\n [sd,si] = sort(out.intNormalizedDistance1To2(hits),'descend');\n f = OF(hits(si(1)));\n e_in = OFI(hits(si(1)));\n if f==f_prev\n error('Point is outside');\n end\n else\n if numel(f) > 1\n f = f(1);\n if ~quiet\n warning('Ignoring non-manifold edge: might miss multiply inside.');\n end\n % TODO: recurse on all in f\n end\n e_in = A(f_prev,f);\n end\n end\n %tsurf(F,V);\n %hold on;\n %tsurf(F(f,:),V,'CData',-1);\n %tsurf(F(f_prev,:),V,'CData',1);\n %plot_edges([q;P(p,:)],[1 2],'r');\n %plot_edges(V,[F(f_prev,E(:,1));F(f_prev,E(:,2))]','b');\n %plot(P(p,1),P(p,2),'*');\n %plot_edges(V,[F(f_prev,E(e_out,1));F(f_prev,E(e_out,2))]', ...\n % 'y','LineWidth',2);\n %hold off;\n %drawnow;\n %input('');\n end\n end\n\n return\n case 'knn'\n % assumes samples are all inside exactly one element\n BC = barycenter(V,F);\n I = sparse(size(P,1),size(F,1));\n B1 = sparse(size(P,1),size(F,1));\n B2 = sparse(size(P,1),size(F,1));\n B3 = sparse(size(P,1),size(F,1));\n B4 = sparse(size(P,1),size(F,1));\n % indices of points we haven't found yet\n IP = 1:size(P,1);\n\n prev_k = 0;\n k = 2;\n while true\n K = knnsearch(BC,P(IP,:),'K',k);\n K = K(:,prev_k+1:end);\n for ki = 1:size(K,2)\n switch size(F,2)\n case 3\n B = abs(barycentric_coordinates( ...\n P(IP,:), ...\n V(F(K(:,ki),1),:), ...\n V(F(K(:,ki),2),:), ...\n V(F(K(:,ki),3),:)));\n case 4\n B = abs(barycentric_coordinates( ...\n P(IP,:), ...\n V(F(K(:,ki),1),:), ...\n V(F(K(:,ki),2),:), ...\n V(F(K(:,ki),3),:), ...\n V(F(K(:,ki),4),:)));\n end\n found = abs(sum(B,2)-1) 1\n B1 = sparse(size(I,1),size(I,2));\n B2 = sparse(size(I,1),size(I,2));\n B3 = sparse(size(I,1),size(I,2));\n B4 = sparse(size(I,1),size(I,2));\n work_I = I;\n while true\n % Peel off a layer\n [mIf,Jf] = max(work_I,[],2);\n If = find(mIf);\n Jf = Jf(If);\n mIf = mIf(If);\n if isempty(If)\n break\n end\n work_I = work_I - sparse(If,Jf,mIf,size(work_I,1),size(work_I,2));;\n Pf = P(If,:);\n Ff = F(Jf,:);\n switch size(Ff,2)\n case 4\n Bf = barycentric_coordinates(Pf, ...\n V(Ff(:,1),:),V(Ff(:,2),:),V(Ff(:,3),:),V(Ff(:,4),:));\n case 3\n Bf = barycentric_coordinates(Pf,V(Ff(:,1),:),V(Ff(:,2),:),V(Ff(:,3),:));\n case 2\n Bf = barycentric_coordinates(Pf,V(Ff(:,1),:),V(Ff(:,2),:));\n end\n B1(sub2ind(size(B1),If,Jf)) = Bf(:,1);\n B2(sub2ind(size(B2),If,Jf)) = Bf(:,2);\n if size(Bf,2) >= 3\n B3(sub2ind(size(B3),If,Jf)) = Bf(:,3);\n end\n if size(Bf,2) >= 4\n B4(sub2ind(size(B3),If,Jf)) = Bf(:,4);\n end\n end\n end\n\nend\n\n\n", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/z_gptoolbox/mesh/in_element.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321703143954, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5388714558431535}} {"text": "function value = i4_mach ( i )\n\n%*****************************************************************************80\n%\n%% I4_MACH returns integer machine constants.\n%\n% Discussion:\n%\n% Input/output unit numbers.\n%\n% I1MACH(1) = the standard input unit.\n% I1MACH(2) = the standard output unit.\n% I1MACH(3) = the standard punch unit.\n% I1MACH(4) = the standard error message unit.\n%\n% Words.\n%\n% I1MACH(5) = the number of bits per integer storage unit.\n% I1MACH(6) = the number of characters per integer storage unit.\n%\n% Integers.\n%\n% Assume integers are represented in the S digit base A form:\n%\n% Sign * (X(S-1)*A**(S-1) + ... + X(1)*A + X(0))\n%\n% where 0 <= X(1:S-1) < A.\n%\n% I1MACH(7) = A, the base.\n% I1MACH(8) = S, the number of base A digits.\n% I1MACH(9) = A**S-1, the largest integer.\n%\n% Floating point numbers\n%\n% Assume floating point numbers are represented in the T digit\n% base B form:\n%\n% Sign * (B**E) * ((X(1)/B) + ... + (X(T)/B**T) )\n%\n% where 0 <= X(I) < B for I=1 to T, 0 < X(1) and EMIN <= E <= EMAX.\n%\n% I1MACH(10) = B, the base.\n%\n% Single precision\n%\n% I1MACH(11) = T, the number of base B digits.\n% I1MACH(12) = EMIN, the smallest exponent E.\n% I1MACH(13) = EMAX, the largest exponent E.\n%\n% Double precision\n%\n% I1MACH(14) = T, the number of base B digits.\n% I1MACH(15) = EMIN, the smallest exponent E.\n% I1MACH(16) = EMAX, the largest exponent E.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 25 April 2007\n%\n% Author:\n%\n% Original FORTRAN77 version by Phyllis Fox, Andrew Hall, Norman Schryer\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Phyllis Fox, Andrew Hall, Norman Schryer,\n% Algorithm 528,\n% Framework for a Portable Library,\n% ACM Transactions on Mathematical Software,\n% Volume 4, Number 2, June 1978, page 176-188.\n%\n% Parameters:\n%\n% Input, integer I, chooses the parameter to be returned.\n% 1 <= I <= 16.\n%\n% Output, integer VALUE, the value of the chosen parameter.\n%\n if ( i < 1 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'I4_MACH - Fatal error!\\n' );\n fprintf ( 1, ' The input argument I is out of bounds.\\n' );\n fprintf ( 1, ' Legal values satisfy 1 <= I <= 16.\\n' );\n fprintf ( 1, ' I = %d\\n', i );\n value = 0;\n error ( 'I4_MACH - Fatal error!' );\n elseif ( i == 1 )\n value = 5;\n elseif ( i == 2 )\n value = 6;\n elseif ( i == 3 )\n value = 7;\n elseif ( i == 4 )\n value = 6;\n elseif ( i == 5 )\n value = 32;\n elseif ( i == 6 )\n value = 4;\n elseif ( i == 7 )\n value = 2;\n elseif ( i == 8 )\n value = 31;\n elseif ( i == 9 )\n value = 2147483647;\n elseif ( i == 10 )\n value = 2;\n elseif ( i == 11 )\n value = 24;\n elseif ( i == 12 )\n value = -125;\n elseif ( i == 13 )\n value = 128;\n elseif ( i == 14 )\n value = 53;\n elseif ( i == 15 )\n value = -1021;\n elseif ( i == 16 )\n value = 1024;\n elseif ( 16 < i )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'I4_MACH - Fatal error!\\n' );\n fprintf ( 1, ' The input argument I is out of bounds.\\n' );\n fprintf ( 1, ' Legal values satisfy 1 <= I <= 16.\\n' );\n fprintf ( 1, ' I = %d\\n', i );\n value = 0;\n error ( 'I4_MACH - 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/fn/i4_mach.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.7401743735019595, "lm_q1q2_score": 0.5388287718187895}} {"text": "%MTRAJ Multi-axis trajectory between two points\n%\n% [Q,QD,QDD] = MTRAJ(TFUNC, Q0, QF, M) is a multi-axis trajectory (MxN) varying\n% from configuration Q0 (1xN) to QF (1xN) according to the scalar trajectory function \n% TFUNC in M steps. Joint velocity and acceleration can be optionally returned as \n% QD (MxN) and QDD (MxN) respectively. The trajectory outputs have one row per \n% time step, and one column per axis.\n%\n% The shape of the trajectory is given by the scalar trajectory function\n% TFUNC which is applied to each axis:\n% [S,SD,SDD] = TFUNC(S0, SF, M);\n% and possible values of TFUNC include @lspb for a trapezoidal trajectory, or\n% @tpoly for a polynomial trajectory.\n%\n% [Q,QD,QDD] = MTRAJ(TFUNC, Q0, QF, T) as above but T (Mx1) is a time\n% vector which dictates the number of points on the trajectory.\n%\n% Notes::\n% - If no output arguments are specified Q, QD, and QDD are plotted.\n% - When TFUNC is @tpoly the result is functionally equivalent to JTRAJ except \n% that no initial velocities can be specified. JTRAJ is computationally a little\n% more efficient.\n%\n% See also JTRAJ, MSTRAJ, LSPB, TPOLY.\n\n\n\n% Copyright (C) 1993-2017, by Peter I. Corke\n%\n% This file is part of The Robotics Toolbox for MATLAB (RTB).\n% \n% RTB is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Lesser General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% RTB is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU Lesser General Public License for more details.\n% \n% You should have received a copy of the GNU Leser General Public License\n% along with RTB. If not, see .\n%\n% http://www.petercorke.com\n\nfunction [S,Sd,Sdd] = mtraj(tfunc, q0, qf, M)\n\n if ~isa(tfunc, 'function_handle')\n error('first argument must be a function handle');\n end\n\n M0 = M;\n if ~isscalar(M)\n M = length(M);\n end\n if numcols(q0) ~= numcols(qf)\n error('must be same number of columns in q0 and qf')\n end\n\n s = zeros(M, numcols(q0));\n sd = zeros(M, numcols(q0));\n sdd = zeros(M, numcols(q0));\n\n for i=1:numcols(q0)\n % for each axis\n [s(:,i),sd(:,i),sdd(:,i)] = tfunc(q0(i), qf(i), M);\n end\n\n% - If no output arguments are specified S, SD, and SDD are plotted \n% against time.\n\n switch nargout\n case 0\n clf\n\n if isscalar(M0)\n t = [1:M0]';\n else\n t = M0;\n end\n subplot(311)\n plot(t, s); grid; ylabel('s');\n\n subplot(312)\n plot(t, sd); grid; ylabel('sd');\n \n subplot(313)\n plot(t, sdd); grid; ylabel('sdd');\n if ~isscalar(M0)\n xlabel('time')\n else\n for c=get(gcf, 'Children');\n set(c, 'XLim', [1 M0]);\n end\n end\n shg\n case 1\n S = s;\n case 2\n S = s;\n Sd = sd;\n case 3\n S = s;\n Sd = sd;\n Sdd = sdd;\n end\n", "meta": {"author": "petercorke", "repo": "robotics-toolbox-matlab", "sha": "bd7a9d75176c660f43fc799b24d838f70b02250c", "save_path": "github-repos/MATLAB/petercorke-robotics-toolbox-matlab", "path": "github-repos/MATLAB/petercorke-robotics-toolbox-matlab/robotics-toolbox-matlab-bd7a9d75176c660f43fc799b24d838f70b02250c/mtraj.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.7279754430043072, "lm_q1q2_score": 0.5388287591057833}} {"text": "function value = meixner ( n, beta, c, x )\n\n%*****************************************************************************80\n%\n%% MEIXNER evaluates Meixner polynomials at a point.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 23 February 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Walter Gautschi,\n% Orthogonal Polynomials: Computation and Approximation,\n% Oxford, 2004,\n% ISBN: 0-19-850672-4,\n% LC: QA404.5 G3555.\n%\n% Parameters:\n%\n% Input, integer N, the maximum order of the polynomial. \n% N must be at least 0.\n%\n% Input, real BETA, the Beta parameter. 0 < BETA.\n%\n% Input, real C, the C parameter. 0 < C < 1.\n%\n% Input, real X, the evaluation point.\n%\n% Output, real VALUE(N+1), the value of the polynomials at X.\n%\n if ( beta <= 0.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'MEIXNER - Fatal error!\\n' );\n fprintf ( 1, ' Parameter BETA must be positive.\\n' );\n error ( 'MEIXNER - Fatal error!\\n');\n end\n\n if ( c <= 0.0 || 1.0 <= c )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'MEIXNER - Fatal error!\\n' );\n fprintf ( 1, ' Parameter C must be strictly between 0 and 1.\\n' );\n error ( 'MEIXNER - Fatal error!\\n');\n end\n\n if ( n < 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'MEIXNER - Fatal error!\\n' );\n fprintf ( 1, ' Parameter N must be nonnegative.\\n' );\n error ( 'MEIXNER - Fatal error!\\n');\n end\n\n OFFSET = 1;\n\n value(0+OFFSET) = 1.0;\n\n if ( n == 0 )\n return\n end\n\n value(1+OFFSET) = ( c - 1 ) * x / beta / c + 1.0;\n\n if ( n == 1 )\n return\n end\n\n for i = 1 : n - 1\n value(i+1+OFFSET) = ( ...\n ( ( c - 1.0 ) * x + ( 1.0 + c ) * i + beta * c ) * value(i+OFFSET) ...\n - i * value(i-1+OFFSET) ...\n ) / ( i + beta );\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/meixner.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754371026367, "lm_q2_score": 0.7401743620390162, "lm_q1q2_score": 0.5388287547375181}} {"text": "function [dfdx, fx] = VBA_numericDiff(fName, idxArg2Diff, varargin)\n% // VBA toolbox //////////////////////////////////////////////////////////\n%\n% [dfdx, fx] = numericDiff(fname, idxArg2Diff, fArg1, fArg2, ...)\n% numerical evaluation of derivatives\n%\n% This function evaluates numerically the derivatives of the function\n% 'fname' with respect to its 'idxArg2Diff' input argument at the point \n% defined by the input arguments [fArg1, fArg2, ..., fArgN]\n%\n% IN:\n% - fname: handle or name of the function to be differentiated.\n% ie either its name or a function handle. The latter can be very useful\n% if the function is itself a subfunction of a function!\n% - idxArg2Diff: the index of the argument to differentiate the function\n% with (1 <= idxArg2Diff <= numel(varargin))\n% - fArg1, fArg2, ..., fArgN: list of arguments which is required to call\n% the function 'fname', and which defines the ordinate at which the \n% derivative will be numerically evaluated\n%\n% OUT:\n% - dfdx: an m x p matrix containing the numerical differentiation\n% of the function evaluated at {fArg1, ..., fArgN}, where p is the \n% number of elements of the function's first output and m is the number\n% of elements of the idxArg2Diff input argument. If the function output\n% or the differentiated argument are in matrix form, they will be\n% vectorized first.\n% - f: the function evaluation at x\n%\n% NB: Mixed partials can be obtained by recursive call of this routine,\n% e.g. consider:\n%\n% dfdx_idx_j = numericDiff(@numericDiff,i+2,fname,j,arg1,arg2,...,argn)\n% dfdx_idx_j = reshape(dfdx_idx_j,mi,mj,p)\n%\n% The first line evaluates the numerical derivative of the function\n% numericDiff(fname,j,arg1,arg2,...,argn) wrt to its (i+2)th entry, which\n% is arg_i.\n% The second line reshapes the output such that the first dimension is the\n% dimension of argi (mi), the second is of the dimension of argj (mj), and\n% the last dimension is the one of the function output itself (p).\n%\n% /////////////////////////////////////////////////////////////////////////\n\n% perturbation scale\nepsilon = 1e-4;\n\n% shortcut\nfArgs = varargin;\n\n% evaluate function at the specified argument\n% =========================================================================\ntry\n fx = VBA_vec(fName(fArgs{:}));\ncatch \n message = sprintf(...\n '*** VBA_numericDiff: Can not call %s with the provided arguments (nArgs = %d).', ...\n func2str(fName), numel(fArgs));\n error(message);\nend\n\n% evaluate the perturbation df of the function fname in the neighbourhood \n% of the specified argument (ie at x + dx) and calculate the derivative wrt x\n% =========================================================================\n\n% pre-allocate the variables\nm = numel (fArgs{idxArg2Diff});\np = numel (fx);\ndfdx = zeros (m, p);\n\n% loop over the dimension of idxArg2Diff-th argument\ndx = epsilon * fArgs{idxArg2Diff};\ndx (abs(dx) <= eps) = epsilon;\n\n% compute effect of pertubations\nfor i = 1 : m\n xpdx = fArgs;\n xpdx{idxArg2Diff}(i) = xpdx{idxArg2Diff}(i) + dx(i);\n dfdx(i,:) = (VBA_vec (fName (xpdx{:})) - fx)' / dx(i);\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/utils/VBA_numericDiff.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743505760728, "lm_q2_score": 0.7279754430043072, "lm_q1q2_score": 0.538828750761042}} {"text": "function [results]=VBA_Shapley(posterior,out,varargin)\n% [results]=VBA_Shapley(posterior,out,[options])\n%\n% Compute the Shapley values of the model's factors (inputs or paramters). \n% These scores measure the relative influence of these factor on the variaince \n% explained by the model.\n% -------------------------------------------------------------------------\n% IN:\n% - posterior, out: model structures\n% - varargin: list of option/values pairs (see below)\n% OUT:\n% - results: structure of results with the following fields, depending on\n% the chose coalitions\n% .parameters/inputs: \n% Shapley values (first order) of paramters/inputs. This is a n x p\n% matrix where n is the number of factors of interest and p the \n% number of observations in the model.\n% - interaction: Interaction score, ie relative change in Shapley values for a\n% perturbation in respective inputs. It is an array with the same\n% size as the inputs whose elements are similar to sv.\n% -------------------------------------------------------------------------\n% options:\n% coalitions: ('parameters') | 'inputs' | 'interactions'\n% > factor of interest of the analysis. For 'interaction', compute the\n% Shapley value of parameters and their relative change for selective\n% input perturbations.\n% inputPerturbation -> ('zero') | 'average' | 'average_nonzero'\n% > type of perturbation to apply on inputs: set to zero, average\n% accross the experiment, or set non zero inputs to their average\n% paramType -> ('phi') | 'theta'\n% > parameters of interest. \n% paramIdx -> (all) | paramIdx\n% > restrict parameters of interest to the index list paramIdx\n% inputIdx -> (all) | inputIdx\n% > restrict inputs of interest to the index list inputIdx\n% obsIdx -> (all) | ObsIdx\n% > restrict observations of interest to the index list obsIdx\n% -------------------------------------------------------------------------\n\n%% Complete option structure\n% -------------------------------------------------------------------------\n\nif numel(varargin) == 1 && isstruct(varargin{1})\n options = varargin{1};\nelse\n options.coalitions = {'parameters','inputs','interactions'};\n options.inputPerturbation = {'zero','average','average_nonzero'};\n options.paramType = {'phi','theta'};\n options.paramIdx = 1:out.dim.n_phi ;\n options.inputIdx = 1:out.dim.u ;\n if size(out.y,2) == 1 % catch vertical data as unique observation\n options.obsIdx = 0;\n else\n options.obsIdx = 1:out.dim.p ;\n end\n parser = inputParser;\n parser.parse (varargin{:});\n options = parser.Results;\n %options = parseargs(options,varargin{:});\nend\n\n%% Prepare perturbation scheme\n% -------------------------------------------------------------------------\n\n% dimensions\nnu = numel(options.inputIdx);\nnw = numel(options.paramIdx);\nif options.obsIdx==0 % catch vertical data as unique observation\n nResps=1;\nelse\n nResps = numel(options.obsIdx);\nend\n\n% factorial perturbations on coalitions of interest\nswitch options.coalitions\n case 'interactions'\n % factorial perturbation of parmeeters with normal inputs,\n kw = full(VBA_spm_perm_mtx(nw));\n k = [kw ones(2^nw,nu)] ;\n % factorial perturbation of parameters with each input respectively\n % pertrubed \n ku = ones(nu)-eye(nu);\n for i=1:nu\n k = vertcat(k, [kw repmat(ku(i,:),size(kw,1),1)]); \n end\n % plus factorial perturbation of inputs alone\n % (ie 2^nw + nu x 2^nw + 2^nu coalitions)\n k = vertcat(k,[ones(2^nu,nw) full(VBA_spm_perm_mtx(nu))]);\n case 'parameters'\n % factorial perturbation of paramters, normal inputs\n k = full(VBA_spm_perm_mtx(nw));\n k = [k ones(size(k,1),nu)];\n case 'inputs'\n % factorial perturbation of inputs, normal paramters\n k = full(VBA_spm_perm_mtx(nu));\n k = [ones(size(k,1),nw) k];\nend\nnk = size(k,1);\n\n%% Compute explained variances\n% -------------------------------------------------------------------------\n\n% loop over coalitions\nve = nan(nk,nResps);\nparfor t = 1:size(k,1)\n kt = k(t,:);\n w_perm = kt(1:nw);\n u_perm = kt(nw+(1:nu));\n ve(t,:) = explainedVar(posterior,out,options,u_perm,w_perm) ;\nend\n\n% normalize\nve1 = ve(1,:);\nve0 = ve(end,:);\nfor i=1:nResps\n ve(:,i) = (ve(:,i) - ve0(i) )/(ve1(i)-ve0(i)) ;\nend\n\n%% Compute Shapley values\n% -------------------------------------------------------------------------\n\n% restrict coalitions to effects of interest\nswitch options.coalitions\n case 'interactions'\n spl = [2^nw*ones(nu+1,1); 2^nu];\n k = mat2cell(k,spl,nw+nu);\n for i=1:nu+1\n k{i} = k{i}(:,1:nw);\n end\n k{nu+2} = k{nu+2}(:,nw+(1:nu));\n ve = mat2cell(ve,spl,nResps);\n case 'parameters'\n k = {k(:,1:nw)};\n ve = {ve};\n case 'inputs'\n k = {k(:,nw+(1:nu))};\n ve = {ve}; \nend\n\n% compute first order scores\nfor ii = 1:numel(k)\n n = size(k{ii},2);\n nn = factorial(n);\n% v{ii} = nan(n,nResps);\n for m=1:n % loop over players\n % Shapley coeficients\n i = k{ii}(:,m);\n z = sum(k{ii},2);\n coef = (2*i-1).*factorial(z-i).*factorial(n-z-(1-i))/nn;\n % compute shapley values per se\n v{ii}(m,:) = coef'*ve{ii};\n end\nend\n\n% compute interactions if necessary\nsv = v{1};\nif strcmp(options.coalitions,'interactions')\n for iu=1:nu\n svi{iu} = (v{1}-v{iu+1})./v{1};\n end\n % shapley value of inputs\n svu = v{nu+2};\nelse\n svi={};\nend\n\n%% Store results\n% -------------------------------------------------------------------------\nswitch options.coalitions\n case 'parameters'\n results.parameters = sv;\n case 'inputs'\n results.inputs = sv;\n case 'interactions'\n results.parameters = sv;\n results.inputs = svu;\n results.interactions = svi;\nend\n\n \nend\n%% Subfunctions\n% =========================================================================\n\n% -------------------------------------------------------------------------\n% Compute explained variance of the model given by posterior and out, with\n% the inputs and paramters pertrubed according to u_swicth and w_switch\n% respectively (switch = 1 -> normal, switch=0 -> perturbation)\n% -------------------------------------------------------------------------\nfunction v=explainedVar(posterior,out,options,u_switch,w_switch)\n\n % prevent unecessary bells and whistles\n out.options.verbose = 0;\n out.options.DisplayWin = 0;\n out.options.inF{1}.fast = true;\n\n % prepare degraded model\n % ..................................................................... \n \n % == pertub inputs\n % index of inputs to perturb\n inputIdx = options.inputIdx(u_switch==0);\n % apply perturbation\n switch options.inputPerturbation\n case 'zero'\n out.u(inputIdx,:) = 0;\n case 'average'\n out.u(inputIdx,:) = mean(out.u(inputIdx,:),2);\n case 'average_nonzero'\n for iu=inputIdx\n idxNZ = find(out.u(iu,:)~=0); \n out.u(iu,idxNZ) = mean(out.u(iu,idxNZ));\n end\n end\n\n % == perturb parameters\n paramIdx = options.paramIdx(w_switch==0);\n switch options.paramType\n case 'phi'\n posterior.muPhi(paramIdx) = 0*posterior.muPhi(paramIdx);\n case 'theta'\n posterior.muTheta(paramIdx) = 0*posterior.muTheta(paramIdx);\n end\n\n % predict data\n % ..................................................................... \n [yp,~,~,~,er] = VBA_simulate (...\n out.options.dim.n_t,...\n out.options.f_fname,...\n out.options.g_fname,...\n posterior.muTheta,...\n posterior.muPhi,...\n out.u,...\n Inf,...\n Inf,...\n out.options,...\n posterior.muX0);\n g = yp-er;\n y = out.y;\n \n % if vertical data, transpose everything\n if options.obsIdx == 0 \n g = g';\n y = y';\n options.obsIdx = 1;\n out.options.isYout = out.options.isYout';\n end\n\n % compute explained variance\n % ..................................................................... \n v = nan(1,numel(options.obsIdx));\n for i=1:numel(options.obsIdx) % for each observation of interest\n obsIdx = options.obsIdx(i);\n in_idx = find(out.options.isYout(obsIdx,:) == 0);\n v(i) = 1-((var(y(obsIdx,in_idx)-g(obsIdx,in_idx))/var(y(obsIdx,in_idx)))) ;\n end\n\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/utils/VBA_Shapley.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232809, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5387085595169977}} {"text": "function [gout,a,fc,L,info] = waveletfilters(Ls, scales, varargin)\n%WAVELETFILTERS Generates wavelet filters\n% Usage: [gout,a,fc,L,info] = waveletfilters(Ls,scales)\n% [gout,a,fc,L,info] = waveletfilters(Ls,'bins', fs, fmin, fmax, bins)\n% [gout,a,fc,L,info] = waveletfilters(Ls,'linear', fs, fmin, fmax, channels)\n%\n% Input parameters:\n% Ls : System length\n% scales : Vector of wavelet scales\n% Output parameters:\n% gout : Cell arrary of wavelet filters\n% a : Downsampling rate for each channel.\n% fc : Center frequency of each channel.\n% L : Next admissible length suitable for the generated filters.\n% info : Struct with additional outputs\n%\n% `waveletfilters(Ls,scales)` constructs a system of wavelet filters covering \n% scales in the range *scales* for system length *Ls*. A scale of 1 corresponds \n% to a wavelet filter with peak positioned at the frequency 0.1 relative \n% to the Nyquist rate.\n%\n% `[g,a,fc]=waveletfilters(Ls, 'bins', fs,fmin,fmax,bins)` constructs a set of\n% wavelets *g* which cover the required frequency range\n% `fmin`-`fmax` with `bins` filters per octave starting at `fmin`. All\n% filters have (approximately) equal $Q=f_c/f_b$. The\n% frequency interval below fmin not covered by these is captured\n% by additional lowpass filter(s) . The signal length *Ls*\n% is mandatory, since we need to avoid too narrow frequency windows\n%\n% `[g,a,fc]=waveletfilters(Ls, 'linear', fs, fmin, fmax, channels)` constructs \n% a set of wavelets *g* which cover the required frequency range\n% `fmin`-`fmax` with `channels` equidistantly spaced filters starting at `fmin`.\n%\n% Wavelet types\n% --------------------\n%\n% The following wavelets can be passed as a flag:\n%\n% 'cauchy' Cauchy wavelet (default parameters [alpha beta gamma] = [300 0 3])\n%\n% 'morse' Generalized morse wavelet (default parameters [alpha beta gamma] = [300 0 3])\n%\n% 'morlet' Morlet wavelet (default parameters sigma = [4])\n%\n% 'fbsp' Frequency B-spline wavelet (default parameters [order fb] = [4 2])\n%\n% 'analyticsp' Analytic spline wavelet (default parameters [order fb] = [4 2])\n%\n% 'cplxsp' Complex spline wavelet (default parameters [order fb] = [4 2])\n%\n% A scale of 1 corresponds\n% to a wavelet filter with peak positioned at the frequency 0.1 relative\n% to the Nyquist rate. By default, this function does not allow center frequencies\n% exceeding the Nyquist rate, except with the optional parameter 'analytic',\n% see below. This implies that scales below 0.1 (or 0.05 for the 'analytic' scheme)\n% are not supported.\n% For more details on the construction of the wavelets and the available\n% wavelet types, please see |freqwavelet|. \n%\n% By default, wavelet filters are peak normalized before being adjusted\n% to the proposed downsampling factor. The peak normalization can be \n% overridden by forwarding any norm flag accepted by |setnorm|.\n%\n% Downsampling factors\n% --------------------\n%\n% The integer downsampling rates of the channels must all divide the\n% signal length, |filterbank| will only work for input signal lengths\n% being multiples of the least common multiple of the downsampling rates.\n% See the help of |filterbanklength|. \n% The fractional downsampling rates restrict the filterbank to a single\n% length *L=Ls*.\n%\n% `[gout,a]=waveletfilters(...,'regsampling')` constructs a non-uniform\n% filterbank with integer subsampling factors. This is the default.\n%\n% `[gout,a]=waveletfilters(...,'uniform')` constructs a uniform filterbank\n% where the integer downsampling rate is the same for all the channels. This\n% results in the most redundant representation which produces nice plots.\n%\n% `[gout,a]=waveletfilters(...,'fractional')` constructs a filterbank with\n% fractional downsampling rates *a*. \n% This results in the least redundant system.\n%\n% `[gout,a]=waveletfilters(...,'fractionaluniform')` constructs a filterbank \n% with fractional downsampling rates *a*, which are uniform for all filters\n% except the \"filling\" low-pass filter which can have different\n% fractional downsampling rates. This is useful when uniform subsampling\n% and low redundancy at the same time are desirable.\n%\n% Lowpass filters\n% --------------------\n%\n% `[gout,a]=waveletfilters(...,'single')` uses a single lowpass filter\n% for covering the range from zero frequency to the center frequency of the\n% largest scale specified. This is the default.\n%\n% `[gout,a]=waveletfilters(...,'repeat')` constructs frequency-shifted\n% copies of the largest scale wavelet to cover the range from zero frequency \n% to the center frequency of the largest scale specified.\n%\n% `[gout,a]=waveletfilters(...,'none')` foregoes the construction of a\n% lowpass filter. This option cannot be expected to yield an invertible \n% filterbank.\n%\n% Additional parameters\n% ---------------------\n%\n% `waveletfilter` accepts the following optional parameters:\n%\n% 'redmul',redmul Redundancy multiplier. Increasing the value of this\n% will make the system more redundant by lowering the\n% channel downsampling rates. It is only used if the\n% filterbank is a non-uniform filterbank. Default\n% value is *1*. If the value is less than one, the\n% system may no longer be painless.\n% \n% 'redtar',redtar Target redundancy. The downsampling factors will be\n% adjusted to achieve a redundancy as close as possible\n% to 'redtar'.\n%\n% 'trunc_at',trunc_at Applies hard thresholding of the wavelet filters \n% at the specified threshold value to reduce their \n% support size. \n% The default value is *trunc_at=10e-5*. When no \n% truncation is desired, *trunc_at=0* should be chosen.\n%\n% 'delay',delay A scalar, numeric vector of function handle that \n% specifies delays for the wavelet filters. A\n% numeric vector must have at least as many entries\n% as there are filters in the filterbank. A function\n% handle must accept two inputs *(k-1,a(k))*, where \n% *k* is the channel index and *a* are the\n% downsampling rates. If a function handle is given\n% and 'redtar' is specified, delays are computed\n% based on the final value of *a*.\n%\n% 'real' Allows positive scales with center frequencies up \n% to Nyquist. This is the default.\n%\n% 'complex' Allows positive scales with center frequencies up \n% to Nyquist, which are also mirrored to cover\n% negative scales.\n%\n% 'analytic' Allows positive scales with center frequencies up \n% to twice the Nyquist frequency. This setting is\n% suitable for the analysis of analytic signals.\n%\n% 'startfreq' Allows to manually set a starting frequency for\n% the wavelet range. Can not be lower than fmin.\n%\n% Examples:\n% ---------\n%\n% In the first example, we analyze a glockenspiel signal with a\n% regularly sampled wavelet filterbank using a frequency B-spline\n% wavelet of order 4 and with parameter fb=3 and visualize the result:::\n%\n% [f,fs]=gspi; % Get the test signal\n% Ls = length(f);\n% scales = linspace(10,0.1,100);\n% [g,a,fc,L]=waveletfilters(Ls,scales, {'fbsp', 4, 3}, 'repeat');\n% c=filterbank(f,g,a);\n% plotfilterbank(c,a,fc,fs,90);\n%\n% In the second example, we construct a wavelet filterbank with a\n% lowpass channels based on a Cauchy wavelet and verify it.\n% The plot shows the frequency responses of\n% filters used for analysis (top) and synthesis (bottom). :::\n%\n% [f,fs]=greasy; % Get the test signal\n% Ls = length(f);\n% M0 = 511; %Desired number of channels (without 0 Hz-lowpass channel)\n% max_freqDiv10 = 10; % 10 corresponds to the nyquist frequency\n% freq_step = max_freqDiv10/M0;\n% rate = 44100;\n% start_index = 1;\n% min_freqHz = rate/10*freq_step\n% min_scale_freq = min_freqHz*start_index\n% min_freqDiv10 = freq_step*start_index; %1/25; % By default, the reference scale for freqwavelet has center frequency 0.1\n% scales = 1./linspace(min_freqDiv10,max_freqDiv10,M0);\n% alpha = 1-2/(1+sqrt(5)); % 1-1/(goldenratio) delay sequence\n% delays = @(n,a) a*(mod(n*alpha+.5,1)-.5);\n% CauchyAlpha = 600;\n% [g, a,fc,L,info] = waveletfilters(Ls,scales,{'cauchy',CauchyAlpha},'uniform','single','energy', 'delay',delays, 'redtar', 8);\n%\n% c=filterbank(f,{'realdual',g},a);\n% r=2*real(ifilterbank(c,g,a));\n% if length(r) > length(f)\n% norm(r(1:length(f))-f)\n% else\n% norm(r-f(1:length(r)))\n% end\n% % Plot frequency responses of individual filters\n% gd=filterbankrealdual(g,a,L);\n% figure(1);\n% subplot(2,1,1);\n% filterbankfreqz(gd,a,L,fs,'plot','linabs','posfreq');\n%\n% subplot(2,1,2);\n% filterbankfreqz(g,a,L,fs,'plot','linabs','posfreq');\n% \n% See also: freqwavelet, filterbank, setnorm\n\n% AUTHORS: Nicki Holighaus, Zdenek Prusa, Guenther Koliander, Clara Hollomey\n\ncomplainif_notenoughargs(nargin,2,upper(mfilename));\ncomplainif_notposint(Ls,'Ls',upper(mfilename));\n \n%parse input arguments:\nif ~isnumeric(scales)\n fs = varargin{1};\n fmin = varargin{2};\n fmax = varargin{3};\n channels = varargin{4};\n switch scales\n case 'linear'\n definput.flags.inputmode = {'linear', 'logarithmic', 'bins', 'scales'};\n %case 'logarithmic'\n % definput.flags.inputmode = {'logarithmic', 'bins', 'scales', 'linear'};\n case 'bins'\n definput.flags.inputmode = {'bins', 'scales', 'linear', 'logarithmic'};\n otherwise\n error('%s: second argument must either be a scales vector or define the f-mapping.',upper(mfilename))\n end\n %this is a slightly more efficient way to remove the first 4 args from\n %varargin\n varargin = circshift(varargin,-4);\n varargin = varargin(1:end-4);\nelse\n definput.flags.inputmode = {'scales', 'linear', 'logarithmic', 'bins'};\nend\n\ndefinput.import={'setnorm'};\ndefinput.importdefaults={'null'};\ndefinput.flags.real = {'real','complex','analytic'};\ndefinput.flags.lowpass = {'single','repeat','none'};\ndefinput.flags.sampling = {'regsampling','uniform',...\n 'fractional','fractionaluniform'};\ndefinput.flags.wavelettype = getfield(arg_freqwavelet(),'flags','wavelettype');\ndefinput.keyvals.redmul=1;\ndefinput.keyvals.redtar=[];\ndefinput.keyvals.delay = 0;\ndefinput.keyvals.trunc_at = 10^(-5);\ndefinput.keyvals.fs = 2;\ndefinput.keyvals.startfreq = [];%only relevant if 'repeat'\n\n[varargin,winCell] = arghelper_filterswinparser(definput.flags.wavelettype,varargin);\n[flags,kv]=ltfatarghelper({},definput,varargin);\n\nif isempty(winCell), winCell = {flags.wavelettype}; end\n\nif ~isa(kv.delay,'function_handle') && ~isnumeric(kv.delay)\n error('%s: delay must be a function handle or numeric.',upper(mfilename));\nend\n\nif ~isscalar(kv.redmul) || kv.redmul <= 0\n error('%s: redmul must be a positive scalar.',upper(mfilename));\nend\n\nif ~isempty(kv.redtar)\n if ~isscalar(kv.redtar) || kv.redtar <= 0\n error('%s: redtar must be a positive scalar.',upper(mfilename));\n end\nend\n\n%parse the input format: map fmin and fmax to scales according to the input\n%parameter specification\nif ~flags.do_scales\n nf = fs/2;\n if flags.do_linear\n min_freq = fmin/nf *10;%map to freqwavelets nyquist f\n max_freq = fmax/nf * 10;\n scales = 1./linspace(min_freq,max_freq,channels);\n % elseif flags.do_logarithmic\n%\n% fc = 2.^linspace(log2(fmin), log2(fmax), channels); \n% fc = fc/nf * 10; \n% scales = 1./fc;\n \n elseif flags.do_bins\n\n if isscalar(channels)\n % Number of octaves\n b = ceil(log2(fmax/fmin))+1;\n bins = channels*ones(b,1);\n else\n bins = channels;\n end\n \n fc = zeros(sum(bins),1);\n\n ll = 0;\n for kk = 1:length(bins)\n fc(ll+(1:bins(kk))) = ...\n fmin*2.^(((kk-1)*bins(kk):(kk*bins(kk)-1)).'/bins(kk));\n ll = ll+bins(kk);\n end\n\n % Get rid of filters with frequency centers >=fmax and nf\n % This will leave the first bigger than fmax it it is lower than nf\n temp = find(fc>=fmax ,1);\n if fc(temp) >= nf\n fc = fc(1:temp-1);\n else\n fc = fc(1:temp);\n end\n\n channels = length(fc);\n min_freq = fmin/nf *10;%map to freqwavelets nyquist f\n max_freq = fmax/nf * 10;\n scales = 1./linspace(min_freq,max_freq,channels);\n end\n scales_sorted = sort(scales,'descend');\n if ~isempty(kv.startfreq)%set the start frequency\n startfreq = kv.startfreq/nf * 10;\n scales_start = find(1./scales_sorted > startfreq,1,'first');%find first scale whose equiv. f is larger than fmin\n scales = scales(scales_start:end);\n end\nend\n\n\nif ~isnumeric(scales) || any(scales < 0.1)\n error('%s: scales must be positive and numeric.',upper(mfilename));\nend\n \nif size(scales,2)>1\n if size(scales,1)==1\n % scales was a row vector.\n scales=scales(:);\n else\n error('%s: scales must be a vector.',upper(mfilename));\n end\nend\n\n\n%% Generate mother wavelet to determine parameters from\n[~,info] = freqwavelet(winCell,Ls,1,'asfreqfilter','efsuppthr',kv.trunc_at,'basefc',0.1);\nbasea = info.aprecise;\n\n\n%% Determine total number of filters and natural subsampling factor for lowpass\n%[aprecise, M, lowpass_number, lowpass_at_zero] = c_det_lowpass(Ls, scales, basea, flags, kv);\nif numel(scales) < 4 && flags.do_single\n error('%s: Lowpass generation requires at least 4 scales.',upper(mfilename));\nelseif numel(scales) < 2 && flags.do_repeat\n error('%s: Lowpass generation requires at least two scales.',upper(mfilename));\nend\n\n% Get number of scales and sort them\nM = numel(scales);\nscales_sorted = sort(scales,'descend');\n%% Determine total number of filters and natural subsampling factor for lowpass\nif flags.do_repeat\n% Maybe adjust this to not guarantee some distance between first filter and zero frequency.\n lowpass_number = scales_sorted(2)/(scales_sorted(1)-scales_sorted(2)); \n if abs(lowpass_number - round(lowpass_number)) < eps*10^3\n % determine if lowpass is centered around 0 Hz\n lowpass_number = round(lowpass_number);\n lowpass_at_zero = 1;\n else\n lowpass_at_zero = 0;\n end\n lowpass_number = floor(lowpass_number);\n if lowpass_number == 0\n lowpass_number = 1;\n end\n M = M + lowpass_number;\n aprecise = (basea.*scales_sorted(1))*ones(lowpass_number,1);\n\nelseif flags.do_single\n lowpass_number = 1;\n lowpass_at_zero = 1;\n M = M+1;\n %this is an estimated value\n aprecise = (0.2./scales_sorted(4))*Ls; % This depends on how single lowpass is called (l.195ff). Maybe automate. Adapt if necessary!!!\nelse\n lowpass_number = 0;\n lowpass_at_zero = 0;\n aprecise = [];\nend\n\n%% Get subsampling factors\naprecise = [aprecise;basea.*scales];\n\nif any(aprecise<1)\n error(['%s: Bandwidth of at least one of the filters is bigger than fs. '],upper(mfilename));\nend\n\naprecise=aprecise/kv.redmul;\nif any(aprecise<1)\n error('%s: The maximum redundancy mult. for this setting is %5.2f',...\n upper(mfilename), min(basea./scales));\nend\n\n%% Compute the downsampling rate\nif flags.do_regsampling\n a = ones(M,1);\n \n [lower_scale,~] = max(scales);\n [upper_scale,~] = min(scales);\n lower_scale = floor(log2(1/lower_scale));\n upper_scale = floor(log2(1/upper_scale));\n \n % Find minimum a in each octave and floor23 it\n % to shrink \"a\" to the next composite number\n ct=1;\n for kk = lower_scale:upper_scale\n tempidx = find( floor(log2(1./scales)) == kk );\n [~,tempminidx] = min(1/scales(tempidx));\n idx = tempidx(tempminidx);\n \n % Deal the integer subsampling factors\n a(tempidx) = floor23(aprecise(idx));\n ct=ct+1;\n end \n \n % Determine the minimal transform length lcm(a)\n L = filterbanklength(Ls,a);\n \n % Heuristic trying to reduce lcm(a)\n while L>2*Ls && ~(all(a==a(1)))\n maxa = max(a);\n a(a==maxa) = 0;\n a(a==0) = max(a);\n L = filterbanklength(Ls,a);\n end\n\nelseif flags.do_fractional\n L = Ls;\n N=ceil(Ls./aprecise);\n a=[repmat(Ls,M,1),N];\nelseif flags.do_fractionaluniform\n L = Ls;\n if lowpass_at_zero\n aprecise(2:end)= min(aprecise(2:end));\n else \n aprecise= repmat(min(aprecise),numel(aprecise),1);\n end\n N=ceil(Ls./aprecise);\n a=[repmat(Ls,M,1),N];\nelseif flags.do_uniform\n a=floor(min(aprecise));\n L=filterbanklength(Ls,a);\n a = repmat(a,M,1);\nend\n% Get an expanded \"a\" / Convert \"a\" to LTFAT 2-column fractional format\nafull=comp_filterbank_a(a,M,struct());\n\n%if flags.do_uniform\n% a = a(:,1);\n%end\n%==========================================================================\n%% Adjust the downsampling rates in order to achieve 'redtar' \n\nif ~isempty(kv.redtar)\n if size(afull,2) == 2\n a = afull(:,1)./afull(:,2);\n else\n a = afull;\n end\n\n if ~flags.do_real\n org_red = sum(1./a);\n elseif lowpass_at_zero\n org_red = 1./a(1) + sum(2./a(2:end));\n else\n org_red = sum(2./a);\n end\n \n a = floor(a*org_red/kv.redtar);\n a(a==0) = 1;\n \n if ~flags.do_uniform\n N_new=ceil(L./a);\n if flags.do_complex\n N_new = [N_new;N_new(end:-1:2)];\n end\n a=[repmat(L,numel(N_new),1),N_new];\n else \n L = filterbanklength(L,a);\n a=[a,ones(length(a), 1)];\n end\nelse\n a = afull;\nend\n\n%% Compute the scaling of the filters and the numeric delay vector\n% Filters are scaled such that the energy of the subband coefficients\n% remains approximately constant independent of the decimation factor\nif isa(kv.delay,'function_handle')\n delayvec = zeros(M,1);\n for kk = 1:M\n delayvec(kk) = kv.delay(kk-1,a(kk,1)./a(kk,2));\n end\nelseif numel(kv.delay) == 1\n delayvec = repmat(kv.delay,M,1);\nelseif ~isempty(kv.delay) && size(kv.delay,2) > 1\n delayvec = kv.delay(:);\nelse\n error('%s: delay must be scaler or have enough elements to cover all channels.',upper(mfilename));\nend\nscal=sqrt(a(:,1)./a(:,2));\n\nif flags.do_complex\n \n if lowpass_at_zero\n a=[a;flipud(a(2:end,:))];\n scal=[scal;flipud(scal(2:end))];\n delayvec=[delayvec;flipud(delayvec(2:end))];\n else\n a=[a;flipud(a)];\n scal=[scal;flipud(scal)];\n delayvec=[delayvec;flipud(delayvec)];\n end\n \n [gout_positive,info_positive] = freqwavelet(winCell,L,scales,...\n 'asfreqfilter','efsuppthr',kv.trunc_at,'basefc',0.1,...\n 'scal',scal(lowpass_number+1:M),'delay', delayvec(lowpass_number+1:M),flags.norm);\n [gout_negative,info_negative] = freqwavelet(winCell,L,-flipud(scales),...\n 'asfreqfilter','efsuppthr',kv.trunc_at,'basefc',0.1,...\n 'negative','scal',scal(M+1:M+numel(scales)),'delay', delayvec(M+1:M+numel(scales)), flags.norm);\n gout = [gout_positive,gout_negative];\n fields = fieldnames(info_positive);\n info = struct();\n for kk = 1:length(fields)\n info.(fields{kk}) = [info_positive.(fields{kk}),info_negative.(fields{kk})];\n end\nelseif flags.do_analytic\n [gout,info] = freqwavelet(winCell,L,scales,...\n 'asfreqfilter','efsuppthr',kv.trunc_at,'basefc',0.1,...\n 'analytic','scal',scal(lowpass_number+1:M),'delay', delayvec(lowpass_number+1:M),flags.norm);\nelse\n if lowpass_at_zero\n % Scale the lowpass filters\n scal(1)=scal(1)/sqrt(2);\n end\n \n [gout,info] = freqwavelet(winCell,L,scales,'asfreqfilter','efsuppthr',...\n kv.trunc_at,'basefc',0.1,'scal',scal(lowpass_number+1:M),'delay', delayvec(lowpass_number+1:M),flags.norm);\nend\n \n%% Generate lowpass filters if desired\n[gout, info] = comp_fblowpassfilters(winCell, gout, a, L, info, scales, scal, delayvec(1:lowpass_number), lowpass_at_zero, kv, flags);\n\ninfo.lowpassstart = lowpass_number + 1;%startindex of actual wavelets (tentative)\n% Assign fc and adjust for sampling rate \nif flags.do_scales\n fc = (kv.fs/2).*info.fc;\nelse\n fc = nf.*info.fc;\nend\n\nif flags.do_uniform || flags.do_regsampling\n a = a(:,1);\nend\n\n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/filterbank/waveletfilters.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085708384736, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5386819912216729}} {"text": "function [x, infos] = sagmu_nmf(V, rank, in_options)\n% Stochastic averaging gradient multiplicative update for non-negative matrix factorization (SAGMU-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% \"Accelerated stochastic multiplicative update with gradient averaging for nonnegative matrix factorizations,\" \n% EUSIPCO, 2018.\n%\n%\n% This file is part of NMFLibrary.\n%\n% Created by H.Kasai on March 22, 2017\n%\n% Feb. 26, 2018 (Hiroyuki Kasai): Fixed algorithm. \n%\n% Jul. 12, 2022 (Hiroyuki Kasai): Modified code structures.\n%\n\n\n m = size(V, 1);\n n = size(V, 2); \n \n \n % set local options\n local_options.fast_calc = true;\n local_options.permute_on = true;\n local_options.sub_mode = 'STD';\n local_options.accel = false;\n local_options.ls = 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\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 number_of_batches = floor(n/options.batch_size);\n \n if ~isfield(options, 'accel')\n options.accel = false;\n if options.ls\n options.sub_mode = 'LS';\n else\n options.sub_mode = 'STD'; \n end \n else\n if options.accel\n options.sub_mode = 'ACC';\n else\n if options.ls\n options.sub_mode = 'LS';\n else\n options.sub_mode = 'STD'; \n end\n end\n end \n \n if options.accel\n if ~isfield(options, 'h_repeat')\n options.h_repeat = 1;\n else\n end \n \n if ~isfield(options, 'rep_mode')\n options.rep_mode = 'fix';\n else\n end\n else\n options.h_repeat = 1;\n end\n \n if options.h_repeat == 1\n if options.ls\n options.sub_mode = 'LS';\n else\n options.sub_mode = 'STD'; \n end\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 if ~isfield(options, 'x_init')\n Wt = rand(m, rank);\n H = rand(rank, n);\n R = rand(m, n); \n else\n Wt = options.x_init.W;\n H = options.x_init.H;\n R = options.x_init.R; \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 R = R(:, perm_idx); \n\n if options.robust\n mode = 'R-SAGMU-NMF';\n else\n mode = 'SAGMU-NMF'; \n R = zeros(m, n);\n end\n \n % initialize\n method_name = sprintf('%s (%s)', mode, options.sub_mode); \n epoch = 0; \n l = zeros(m, options.batch_size) + options.lambda; \n grad_calc_count = 0;\n\n if options.verbose > 0\n fprintf('# %s: started ...\\n', method_name); \n end \n \n % prepare arrays for vht and Whht \n vht = cell(number_of_batches,1);\n Whht = cell(number_of_batches,1);\n \n % store vht and Whht \n cnt = 0;\n for t=1: options.batch_size : n - 1\n cnt = cnt + 1;\n vt = V(:,t:t+options.batch_size-1);\n ht = H(:,t:t+options.batch_size-1);\n rt = R(:,t:t+options.batch_size-1); \n vht{cnt} = vt * ht';\n Whht{cnt} = (Wt * ht + rt) * ht';\n end \n \n % prepare Delta_minus and Delta_plus\n if options.fast_calc\n Delta_minus = zeros(m, rank);\n Delta_plus = zeros(m, rank); \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, options.sub_mode, f_val, optgap); \n end \n \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 \n cnt = 0;\n % main inner loop\n for t = 1 : options.batch_size : n - 1\n cnt = cnt + 1;\n\n % retrieve vt and ht\n vt = V(:,t:t+options.batch_size-1);\n ht = H(:,t:t+options.batch_size-1);\n \n \n if ~options.robust\n \n % uddate ht\n Wtv = Wt' * vt;\n WtW = Wt' * Wt;\n if strcmp(options.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 % ht = ht .* (Wtv) ./ (Wt' * (Wt * ht + rt));\n % ht = ht + (ht 0\n if options.fast_calc\n delta_minus = Delta_minus/n + (vht{cnt} + Whht_org)/options.batch_size;\n delta_plus = Delta_plus/n + (Whht{cnt} + vht_org)/options.batch_size;\n \n % update Delta_minus and Delta_plus\n Delta_minus = Delta_minus + (vht{cnt} - vht_org);\n Delta_plus = Delta_plus + (Whht{cnt} - Whht_org); \n else\n delta_minus = zeros(m, rank);\n delta_plus = zeros(m, rank);\n\n for jj=1:number_of_batches\n delta_minus = delta_minus + vht{jj};\n delta_plus = delta_plus + Whht{jj};\n end \n \n delta_minus = delta_minus/n;\n delta_plus = delta_plus/n;\n\n delta_minus = delta_minus + (vht{cnt} + Whht_org)/options.batch_size;\n delta_plus = delta_plus + (Whht{cnt} + vht_org)/options.batch_size; \n end\n \n else\n delta_minus = vht{cnt}/options.batch_size;\n delta_plus = Whht{cnt}/options.batch_size; \n \n if options.fast_calc\n % update Delta_minus and Delta_plus\n Delta_minus = Delta_minus + vht{cnt};\n Delta_plus = Delta_plus + Whht{cnt}; \n end\n end\n \n % update W \n if options.stepsize_ratio == 1\n Wt = Wt .* (delta_minus ./ delta_plus);\n else\n Wt = (1-ratio)* Wt + ratio * Wt .* (delta_minus ./ delta_plus); \n end\n\n Wt = Wt + (Wt.\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/Simulation/obj2segs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.746138993030751, "lm_q2_score": 0.721743200312399, "lm_q1q2_score": 0.538520744707885}} {"text": "function [post,nlZ,dnlZ] = infExact_fastrobust(kmax, hyp, mean, cov, lik, x, y, s)\n\n% Fast, robust inference for a GP with Gaussian likelihood. Compute a \n% parametrization of the posterior, the negative log marginal likelihood \n% and its derivatives w.r.t. the hyperparameters. See also \"help infMethods\".\n% \n% To be used in combination with 'fast' covariance functions (e.g.\n% covSEard_fast and such). \n%\n% This implementation also handles badly conditioned covariance matrices, \n% which sometimes become non-positive definite and cause a failure of the \n% Cholesky decomposition. In these cases, the covariance matrix is corrected \n% to the nearest symmetric positive semidefinite (SPD) matrix in Frobenius \n% norm (see [1]; based on an implementation by John d'Errico).\n%\n% [1] Higham NJ, \"Computing a nearest symmetric positive semidefinite \n% matrix\", Linear Algebra Appl, 1988.\n% http://www.sciencedirect.com/science/article/pii/0024379588902236\n%\n% Added support for 'fast' inference and robust Cholesky decomposition by\n% Luigi Acerbi, 2016-01-03.\n% Original code by Carl Edward Rasmussen and Hannes Nickisch, 2015-07-13.\n%\n% See also INFMETHODS.M.\n\nif iscell(lik), likstr = lik{1}; else likstr = lik; end\nif ~ischar(likstr), likstr = func2str(likstr); end\nif strcmp(likstr,'likGauss') % NOTE: no explicit call to likGauss\n henoise_flag = false;\nelseif strcmp(likstr,'likGaussHe')\n henoise_flag = true; % Heteroskedastic noise \nelse\n error('Exact inference only possible with Gaussian likelihood');\nend\n\nif isempty(kmax); kmax = 5; end\n \n[n, D] = size(x);\nif nargout > 2 % do we want derivatives?\n [K,dK] = feval(cov{:}, hyp.cov, x); % evaluate covariance matrix and derivatives\nelse\n K = feval(cov{:}, hyp.cov, x); % evaluate covariance matrix\nend\nm = feval(mean{:}, hyp.mean, x); % evaluate mean vector\n\nsn2_base = exp(2*hyp.lik); % noise variance of likGauss\n\nif henoise_flag && ~isempty(s)\n % if isempty(s); error('Input-dependent vector S is empty.'); end\n sn2 = sn2_base + s.^2; % Vector of observation variance\nelse\n sn2 = sn2_base;\nend\n\nLchol = min(sn2) >= 1e-6; % tiny sn2 can lead to numerical trouble\n\n% smallnoise = sn2 < 1e-6; \nif Lchol\n if isscalar(sn2)\n sn2div = sn2;\n sn2_mat = eye(n);\n else\n sn2div = min(sn2);\n sn2_mat = diag(sn2/sn2div);\n end \n \n M = K/sn2div+sn2_mat; % B matrix\nelse\n if isscalar(sn2)\n sn2_mat = sn2*eye(n);\n else\n sn2_mat = diag(sn2);\n end\n M = K+sn2_mat; % Covariance with noise\nend\n\n[L,p] = chol(M); % Try computing Cholesky factor\n\nif p~=0 % Failed Cholesky decomposition, compute nearest SPD matrix\n if kmax <= 0; error('Cannot compute Cholesky decomposition.'); end\n % Mold = M;\n \n M = (M + M')/2; % Ensure M is symmetric\n [U,Sigma,V] = svd(M);\n H = V*Sigma*V'; % Symmetric polar factor H is SPD\n M = (M+H)/2; \n M = (M + M')/2; % Ensure symmetry again\n [L,p] = chol(M); % Retry Cholesky decomposition\n k = 0;\n while p ~= 0 % Failed again, add a small diagonal component\n k = k + 1;\n % We do not want to change the matrix too much\n if k > kmax-1; error('Cannot compute Cholesky decomposition.'); end \n lambda = eig(M); \n mineig = min(lambda); \n kappa = 0.05; % Sometimes even a small nudge is sufficient\n M = M + kappa*abs(mineig)*k.^2*eye(size(M));\n [L,p] = chol(M);\n end\n \n % [sort(eig(M))'; sort(eig(Mold))']\n \nend\n\nif Lchol\n sl = sn2div;\n pL = L; % L = chol(eye(n)+sW*sW'.*K)\nelse\n sl = 1;\n pL = -solve_chol(L,eye(n)); % L = -inv(K+inv(sW^2))\nend\n\nalpha = solve_chol(L,y-m)/sl;\n\npost.alpha = alpha; % return the posterior parameters\npost.sW = ones(n,1)/sqrt(min(sn2)); % sqrt of noise precision vector\npost.L = pL;\npost.Lchol = Lchol;\n\nif nargout>1 % do we want the marginal likelihood?\n nlZ = (y-m)'*alpha/2 + sum(log(diag(L))) + n*log(2*pi*sl)/2; % -log marg lik\n if nargout>2 % do we want derivatives?\n dnlZ = hyp; % allocate space for derivatives\n Q = solve_chol(L,eye(n))/sl - alpha*alpha'; % precompute for convenience\n for i = 1:numel(hyp.cov)\n dnlZ.cov(i) = sum(sum(Q.*dK(:,:,i)))/2;\n end\n dnlZ.lik = sn2_base*trace(Q);\n for i = 1:numel(hyp.mean)\n dnlZ.mean(i) = -feval(mean{:}, hyp.mean, x, i)'*alpha;\n end\n end\nend\n", "meta": {"author": "acerbilab", "repo": "bads", "sha": "019f0b432b9e157a31defbbd303aadcdf57862e7", "save_path": "github-repos/MATLAB/acerbilab-bads", "path": "github-repos/MATLAB/acerbilab-bads/bads-019f0b432b9e157a31defbbd303aadcdf57862e7/gpml_fast/infExact_fastrobust.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.5384827543066052}} {"text": "function [neighbors] = BuildNonCon2D(NGauss, tol)\n\n% function [neighbors] = BuildNonCon2D(NGauss, tol)\n% Purpose: find element to element connections through non-conforming interfaces\n% (** elements assumed straight sided **)\n\nGlobals2D;\n\n% 1. Build Gauss nodes\n[gz, gw] = JacobiGQ(0, 0, NGauss-1);\n\n% 1.1 Find location of vertices of boundary faces\nvx1 = VX(EToV(:,[1,2,3])); vx2 = VX(EToV(:,[2,3,1]));\nvy1 = VY(EToV(:,[1,2,3])); vy2 = VY(EToV(:,[2,3,1]));\n\nidB = find(EToE==((1:K)'*ones(1,Nfaces)));\nx1 = vx1(idB)'; y1 = vy1(idB)';\nx2 = vx2(idB)'; y2 = vy2(idB)';\n\n% 1.2 Find those element-faces that are on boundary faces\n[elmtsB,facesB] = find(EToE==((1:K)'*ones(1,Nfaces)));\nNbc = length(elmtsB);\n\nsk = 1;\n% 2.1 For each boundary face\nfor b1=1:Nbc \n % 2.2 Find element and face of this boundary face\n k1 = elmtsB(b1); f1 = facesB(b1);\n\n % 2.3 Find end coordinates of b1'th boundary face\n x11 = x1(b1); y11 = y1(b1); x12 = x2(b1); y12 = y2(b1);\n \n % 2.4 Compute areas, lengths and face coordinates used in intersection \n % tests comparing b1'th boundary face with all boundary faces\n area1 = abs((x12-x11)*(y1-y11) - (y12-y11)*(x1-x11)); %scale\n area2 = abs((x12-x11)*(y2-y11) - (y12-y11)*(x2-x11));\n L = (x12-x11)^2 + (y12-y11)^2 ; \n r21 = ((2*x1-x11-x12)*(x12-x11) + (2*y1-y11-y12)*(y12-y11))/L;\n r22 = ((2*x2-x11-x12)*(x12-x11) + (2*y2-y11-y12)*(y12-y11))/L;\n\n % 2.5 Find range of local face coordinate (bracketed between -1 and 1)\n r1 = max(-1,min(r21,r22)); r2 = min(1,max(r21,r22));\n\n % 2.6 Compute flag for overlap of b1 face with all other boundary faces\n flag = area1+area2+(r1<= -1 & r2<= -1)+(r1>=1 & r2>=1)+(r2-r10)\n % 3.1 Find matches\n r1 = r1(matches); r2 = r2(matches); \n\n % 3.2 Find end points of boundary-boundary intersections\n xy11 = 0.5*[x11;y11]*(1-r1) + 0.5*[x12;y12]*(1+r1);\n xy12 = 0.5*[x11;y11]*(1-r2) + 0.5*[x12;y12]*(1+r2);\n\n % 3.3 For each face-face match\n for n=1:Nmatches\n\n % 3.4 Store which elements intersect\n k2 = elmtsB(matches(n)); f2 = facesB(matches(n));\n neighbors{sk}.elmtM = k1; neighbors{sk}.faceM = f1;\n neighbors{sk}.elmtP = k2; neighbors{sk}.faceP = f2;\n\n % 3.5 Build physical Gauss nodes on face fragment\n xg = 0.5*(1-gz)*xy11(1,n) + 0.5*(1+gz)*xy12(1,n);\n yg = 0.5*(1-gz)*xy11(2,n) + 0.5*(1+gz)*xy12(2,n);\n\n % 3.6 Find local coordinates of Gauss nodes\n [rg1,sg1] = FindLocalCoords2D(k1, xg, yg);\n [rg2,sg2] = FindLocalCoords2D(k2, xg, yg);\n\n % 3.7 Build interpolation matrices for volume nodes ->Gauss nodes\n gVM = InterpMatrix2D(rg1,sg1); neighbors{sk}.gVM = gVM;\n gVP = InterpMatrix2D(rg2,sg2); neighbors{sk}.gVP = gVP;\n\n % 3.8 Find face normal \n neighbors{sk}.nx = nx(1+(f1-1)*Nfp,k1);\n neighbors{sk}.ny = ny(1+(f1-1)*Nfp,k1);\n \n % 4.0 Build partial face data lift operator\n\n % 4.1 Compute weights for lifting\n partsJ = sqrt( (xy11(1,n)-xy12(1,n))^2 + (xy11(2,n)-xy12(2,n))^2 )/2;\n dgw = gw*partsJ/J(1,k1); \n \n % 4.2 Build matrix to lift Gauss data to volume data\n neighbors{sk}.lift = V*V'*(gVM')*diag(dgw);\n\n sk = sk+1;\n end\n end\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/BuildNonCon2D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358015, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.5384473446370057}} {"text": "function imgOut = WardHistAdjTMO(img, nBin, LdMin, LdMax, bPlotHistogram, bDownsampling)\n%\n% imgOut = WardHistAdjTMO(img, nBin, LdMin, LdMax, bPlotHistogram, bDownsampling)\n%\n%\n% Input:\n% -img: input HDR image\n% -nBin: number of bins for calculating the histogram (1,+Inf)\n% -LdMin: minimum luminance value of the dispLay\n% -LdMax: maximum luminance value of the dispLay\n% -bPlotHistogram:\n%\n% Output:\n% -imgOut: tone mapped image\n% \n% Copyright (C) 2010-21 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% \"A Visibility Matching Tone Reproduction Operator for High Dynamic Range Scenes\"\n% \t by Gregory Ward Larson, Holly Rushmeier, Christine Piatko\n% in IEEE Transactions on Visualization and Computer Graphics 1997\n%\n\n%is it a gray/three color channels image?\ncheck13Color(img);\n\ncheckNegative(img);\n\nif(~exist('nBin', 'var'))\n nBin = 100;\nend\n\nif(nBin < 1)\n nBin = 100;\nend\n\nif(~exist('LdMin', 'var'))\n LdMin = 1; %cd/m^2\nend\n\nif(LdMin < 0.0)\n LdMin = 1;\nend\n\nif(~exist('LdMax', 'var'))\n LdMax = 100; %cd/m^2\nend\n\nif(LdMax <= 0.0)\n LdMax = 100;\nend\n\nif(LdMax < LdMin)\n tmp = LdMin;\n LdMin = LdMax;\n LdMax = tmp;\nend\n\nif(~exist('bPlotHistogram', 'var'))\n bPlotHistogram = 0;\nend\n\nif(~exist('bDownsampling', 'var'))\n bDownsampling = 0;\nend\n\nepsilon = 1e-6;\n\n%compute luminance channel\nL = lum(img);\n\n%downsample according to fovea...\nif(bDownsampling)\n L2 = WardDownsampling(L + epsilon);\nelse\n L2 = L + 1e-6;\nend\n\n%compute stastistics\nLMin = min(L2(:));\nLMax = max(L2(:));\n\nLlog = log(L2);\n\nLlMin = log(LMin);\nLlMax = log(LMax);\n\nLldMin = log(LdMin + epsilon);\nLldMax = log(LdMax + epsilon);\n\n%compute the histogram H \nH = zeros(nBin, 1);\ndelta = (LlMax - LlMin) / nBin;\n\nfor i=1:nBin\n indx = find(Llog > (delta * (i - 1) + LlMin) & Llog <= (delta * i + LlMin));\n H(i) = numel(indx);\nend\n\n%apply the histogram ceiling\nmaxH = max(H);\nx_vis = LlMin:((LlMax - LlMin) / (nBin -1)):LlMax;\n\nif(bPlotHistogram)\n bar(x_vis, H/maxH);\n hold on;\nend\n\nH = histogram_ceiling(H, delta / (LldMax - LldMin));\n\nif(bPlotHistogram)\n bar(x_vis, H / maxH);\n hold off;\nend\n\n%compute P(x) \nP = cumsum(H);\nP = P / max(P);\n\n%calculate tone mapped luminance\nL(L > LMax) = LMax;\nx = (LlMin:((LlMax - LlMin) / (nBin - 1)):LlMax)';\nP_L = interp1(x , P , real(log(L)), 'linear');\nLd = exp(LldMin + (LldMax - LldMin) * P_L);\n%normalize in [0,1]\nLd = (Ld - LdMin) / (LdMax - LdMin); \n\n%change luminance\nimgOut = ChangeLuminance(img, L, Ld);\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/WardHistAdjTMO.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.822189121808099, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.538447333223695}} {"text": "function [ nr, nt, nc ] = circle_rt_size ( rule )\n\n%*****************************************************************************80\n%\n%% CIRCLE_RT_SIZE sizes an R, THETA product quadrature rule in the unit circle.\n%\n% Discussion:\n%\n% For a given value of RULE, here are the number of points used at the\n% center (NC), the number of points along the radial direction (NR) and\n% the number of points along the theta direction (NT). The total number\n% of points in the rule will be\n%\n% Total = NC + NR * NT.\n%\n% The user, when choosing RULE, must allocate enough space in the arrays\n% RA, RW, TA and TW for the resulting values of NR and NT.\n%\n% RULE NC NR NT Total\n% ---- -- -- -- -----\n% 1 1 0 0 1\n% 2 0 1 4 4\n% 3 1 1 4 5\n% 4 1 1 6 7\n% 5 1 2 4 9\n% 6 0 3 4 12\n% 7 1 2 10 21\n% 8 0 4 16 64\n% 9 0 5 20 120\n%\n% The integral of F(X,Y) over the unit circle is approximated by\n%\n% Integral ( X*X + Y*Y <= 1 ) F(X,Y) dx dy\n% = Integral ( 0 <= R <= 1, 0 <= T <= 2PI ) F(R*cos(T),R*sin(T)) r dr dt\n% = approximately\n% ZW * F(0,0)\n% + sum ( 1 <= I <= NR ) Sum ( 1 <= J <= NT )\n% RW(I) * TW(J) * F ( R(I) * cos ( TA(J) ), R(I) * sin ( TA(J) ) )\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 01 April 2008\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Milton Abramowitz, Irene Stegun,\n% Handbook of Mathematical Functions,\n% National Bureau of Standards, 1964,\n% ISBN: 0-486-61272-4,\n% LC: QA47.A34.\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 RULE, the rule desired.\n%\n% Output, integer NR, the number of R abscissas.\n%\n% Output, integer NT, the number of Theta abscissas.\n%\n% Output, integer NC, the number of center abscissas (0 or 1).\n%\n if ( rule == 1 )\n\n nr = 0;\n nt = 0;\n nc = 1;\n\n elseif ( rule == 2 )\n\n nr = 1;\n nt = 4;\n nc = 0;\n\n elseif ( rule == 3 )\n\n nr = 1;\n nt = 4;\n nc = 1;\n\n elseif ( rule == 4 )\n\n nr = 1;\n nt = 6;\n nc = 1;\n\n elseif ( rule == 5 )\n\n nr = 2;\n nt = 4;\n nc = 1;\n\n elseif ( rule == 6 )\n\n nr = 3;\n nt = 4;\n nc = 0;\n\n elseif ( rule == 7 )\n\n nr = 2;\n nt = 10;\n nc = 1;\n\n elseif ( rule == 8 )\n\n nr = 4;\n nt = 16;\n nc = 0;\n\n elseif ( rule == 9 )\n\n nr = 5;\n nt = 20;\n nc = 0;\n\n else\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CIRCLE_RT_SIZE - Fatal error!\\n' );\n fprintf ( 1, ' There is no rule of index %d\\n', rule );\n error ( 'CIRCLE_RT_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/circle_rt_size.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.5383905173343931}} {"text": "function [Y, X, incrementalCertainty] = ...\n estimate_displacement_based_upon_vector_summation2d(solution,...\n filterDirection,...\n sizeImage,...\n numberOfFilterDirections,...\n dk,ck,...\n t11,t22,t12)\n% ESTIMATE_DISPLACEMENT_BASED_UPON_VECTOR_SUMMATION2D Estimates a displacement field based upon vector summation\n%\n% [Y, X, incrementalCertainty] = ...\n% estimate_displacement_based_upon_vector_summation2d(solution,...\n% filterDirection,...\n% sizeImage,...\n% numberOfFilterDirections,...\n% dk,ck,...\n% t11,t22,t12)\n%\n% INPUT ARGUMENTS\n% solution - Solution to use (6-7)\n% sizeImage - Image size\n% dk - Phase-difference for k different filter\n% directions\n% ck - Corresponding certainties for k different\n% filter directions\n% filterDirection - k filter directions\n% numberOfFilterDirections - Number of filter directions\n% t11 - Tensor element (1,1)\n% t12 - Tensor element (1,2)\n% t22 - Tensor element (2,2)\n% \n% OPTIONAL INPUT ARGUMENTS\n% N/A\n%\n% OUTPUT ARGUMENTS\n% Y\t \t\t\t\t\t\t\t- Displacement along Y\n% X \t\t\t\t\t\t\t- Displacement along X\n% incrementalCertainty \t\t\t- Certainty of displacement\n\n% Copyright (c) 2011 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\nX = zeros(sizeImage);\nY = zeros(sizeImage);\nincrementalCertainty = zeros(sizeImage);\n\nswitch solution\n case 6 %************************************************\n for k = 1:numberOfFilterDirections\n ckprim(:,:,k) = ck(:,:,k).*((filterDirection{k}(1).*t11 + filterDirection{k}(2).*t12).*filterDirection{k}(1)...\n +(filterDirection{k}(1).*t12 + filterDirection{k}(2).*t22).*filterDirection{k}(2));\n end\n \n for k = 1:numberOfFilterDirections\n X = X+ckprim(:,:,k).*dk(:,:,k)*filterDirection{k}(2);\n Y = Y+ckprim(:,:,k).*dk(:,:,k)*filterDirection{k}(1);\n incrementalCertainty = incrementalCertainty+ckprim(:,:,k);\n end\n case 7 %************************************************\n for k = 1:numberOfFilterDirections\n X = X+ck(:,:,k).*dk(:,:,k)*filterDirection{k}(2);\n Y = Y+ck(:,:,k).*dk(:,:,k)*filterDirection{k}(1);\n incrementalCertainty = incrementalCertainty+ck(:,:,k);\n end\nend\n\nincrementalCertainty = incrementalCertainty + eps;\nX = X./incrementalCertainty;\nY = Y./incrementalCertainty;", "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/morphon/estimate_displacement_based_upon_vector_summation2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920116079208, "lm_q2_score": 0.672331705744791, "lm_q1q2_score": 0.5383306259405813}} {"text": "function product_mixed_weight_test ( dim_num, order_1d, order_nd, rule, alpha, beta )\n\n%*****************************************************************************80\n%\n%% PRODUCT_MIXED_WEIGHT_TEST computes the weights of a mixed factor product rule.\n%\n% Discussion:\n%\n% This routine gets the sparse grid indices and determines the\n% corresponding sparse grid weights.\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% 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% 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, real ALPHA(DIM_NUM), BETA(DIM_NUM), parameters used for\n% Generalized Gauss Hermite, Generalized Gauss Laguerre, and Gauss Jacobi rules.\n%\n weight_sum_exact = 1.0;\n\n for dim = 1 : dim_num\n\n if ( rule(dim) == 1 )\n weight_sum_exact = weight_sum_exact * 2.0;\n elseif ( rule(dim) == 2 )\n weight_sum_exact = weight_sum_exact * 2.0;\n elseif ( rule(dim) == 3 )\n weight_sum_exact = weight_sum_exact * 2.0;\n elseif ( rule(dim) == 4 )\n weight_sum_exact = weight_sum_exact * 2.0;\n elseif ( rule(dim) == 5 )\n weight_sum_exact = weight_sum_exact * sqrt ( pi );\n elseif ( rule(dim) == 6 )\n weight_sum_exact = weight_sum_exact * r8_gamma ( 0.5 * ( alpha(dim) + 1.0 ) );\n elseif ( rule(dim) == 7 )\n weight_sum_exact = weight_sum_exact * 1.0;\n elseif ( rule(dim) == 8 )\n weight_sum_exact = weight_sum_exact * r8_gamma ( alpha(dim) + 1.0 );\n elseif ( rule(dim) == 9 )\n arg1 = - alpha(dim);\n arg2 = 1.0;\n arg3 = beta(dim) + 2.0;\n arg4 = - 1.0;\n value1 = r8_hyper_2f1 ( arg1, arg2, arg3, arg4 );\n arg1 = - beta(dim);\n arg2 = 1.0;\n arg3 = alpha(dim) + 2.0;\n arg4 = - 1.0;\n value2 = r8_hyper_2f1 ( arg1, arg2, arg3, arg4 );\n weight_sum_exact = weight_sum_exact * ( ...\n value1 / ( beta(dim) + 1.0 ) + value2 / ( alpha(dim) + 1.0 ) );\n elseif ( rule(dim) == 10 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'PRODUCT_MIXED_WEIGHT_TEST - Fatal error!\\n' );\n fprintf ( 1, ' Do not know how to handle rule 10.\\n' );\n error ( 'PRODUCT_MIXED_WEIGHT_TEST - Fatal error!' );\n elseif ( rule(dim) == 11 )\n weight_sum_exact = weight_sum_exact * 2.0;\n elseif ( rule(dim) == 12 )\n weight_sum_exact = weight_sum_exact * 2.0;\n elseif ( rule(dim) == 13 )\n weight_sum_exact = weight_sum_exact * 2.0;\n elseif ( rule(dim) == 14 )\n weight_sum_exact = weight_sum_exact * 2.0;\n elseif ( rule(dim) == 15 )\n weight_sum_exact = weight_sum_exact * 2.0;\n elseif ( rule(dim) == 16 )\n weight_sum_exact = weight_sum_exact * 2.0;\n elseif ( rule(dim) == 17 )\n weight_sum_exact = weight_sum_exact * 2.0;\n else\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'PRODUCT_MIXED_WEIGHT_TEST - Fatal error!\\n' );\n fprintf ( 1, ' Unexpected value of RULE = %d\\n', rule(dim) );\n error ( 'PRODUCT_MIXED_WEIGHT_TEST - Fatal error!' );\n end\n\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'PRODUCT_MIXED_WEIGHT_TEST:\\n' );\n fprintf ( 1, ' Compute the weights of a mixed factor product grid.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' As a simple test, sum these weights.\\n' );\n fprintf ( 1, ' They should sum to exactly %f\\n', weight_sum_exact );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Spatial dimension DIM_NUM = %d\\n', dim_num );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Dimension Rule Order Alpha Beta\\n' );\n fprintf ( 1, '\\n' );\n\n for dim = 1 : dim_num\n fprintf ( 1, ' %8d %8d %8d', dim, rule(dim), order_1d(dim) );\n if ( rule(dim) == 6 | rule(dim) == 8 | rule(dim) == 9 )\n fprintf ( 1, ' %12e', alpha(dim) );\n end\n if ( rule(dim) == 9 )\n fprintf ( 1, ' %12e', beta(dim) );\n end\n fprintf ( 1, '\\n' );\n end\n%\n% Compute the weights and points.\n%\n weight = product_mixed_weight ( dim_num, order_1d, order_nd, rule, alpha, beta );\n%\n% Sum the weights.\n%\n weight_sum = sum ( weight(1:order_nd) );\n\n weight_sum_error = abs ( weight_sum - weight_sum_exact );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Weight sum Expected sum Difference\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' %14e %14e %14e\\n', ...\n weight_sum, weight_sum_exact, weight_sum_error );\n\n return\nend\n", "meta": {"author": "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/product_mixed_weight_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920116079209, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.5383306259405813}} {"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 f = RegCoeff(S, g, df, B, Nb, Nr)\n% calculates regression coefficients to be used with longstaff-schwartz\n\nv = g(:,end); % start for backward induction\n\nf = zeros(Nb, Nr-1);\n\n% backward induction and regression from t_{Nr-1} up to t_1\nfor i = Nr-1:-1:1\n index = find(g(:,i) > 0); % all ITM paths\n s = S(index,i+1); % values of S at given time point \n v = v * df(i+1); % option value at t_i\n\n Acell = B(s); % evaluate basis function in cell array B \n A = cell2mat(Acell{:,:}); % convert to matrix\n \n f(:,i) = (A'*A)\\(A'*v(index)); % determine coefficients\n c = A*f(:,i); % continuation value\n exercise = g(index,i) >= c; % early exercise\n v(index(exercise)) = g(index(exercise),i);\nend\n\nend", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/37620-american-monte-carlo/AmericanMC/RegCoeff.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038222, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.5383053318053097}} {"text": "function [lb_e, sigma_e, tf_conv] = estimate_MP2(s, pout, gap,...\n niter, nx_target, flag_distance, tf_verbose)\n% fitting with histogram, using L2 or dKL\nif ~exist('pout', 'var')\n pout = 0.5;\nend\nif ~exist('gap', 'var')\n gap = 0.2;\nend\nif ~exist('niter', 'var')\n niter = 10;\nend\nif ~exist('tf_verbose', 'var')\n tf_verbose = false;\nend\nif ~exist('nx_target', 'var')\n nx_target = 3.2;\nend\n\nif ~exist('flag_distance', 'var')\n flag_distance = 'L2';\nend\n\n\nep = 1e-4;\ntol = 1e-3;\nse = sort(s(s>ep),'descend');\n\n% start with the moment estimator\n[lb_e, sigma_e, ~] = estimate_MP(s, pout, gap, 50, false);\nif tf_verbose; display(lb_e, sigma_e); end\ntf_conv = false;\nfor i = 1: niter-1\n lb1_e = (1 + sqrt(lb_e))^2 * sigma_e^2;\n nbulk = sum(se < lb1_e);\n se_bulk = se(se < lb1_e);\n nbin = nbulk / nx_target;\n nbin = max(10, nbin);\n [Ns, bin_edges] = histcounts(se_bulk, ceil(nbin));\n \n bin_centers = (bin_edges(1:end-1) + bin_edges(2:end)) / 2;\n s_pdf = Ns ./ diff(bin_edges) / nbulk;\n \n switch flag_distance\n case 'L2'\n f_dist = @(p2) sum((s_pdf - MPdistr(bin_centers, p2(1), p2(2))).^2);\n case 'dKL'\n f_dist = @(p2) f_dist_dKL(p2, s_spdf, bin_centers);\n end; \n \n [p2_fit, ~] = fminsearch(f_dist, [lb_e, sigma_e], optimset('MaxFunEvals',1e5));\n lb_e_new = p2_fit(1);\n sigma_e_new = p2_fit(2);\n \n if abs(sigma_e_new - sigma_e) < tol && abs(lb_e_new-lb_e) < tol\n tf_conv = true;\n break;\n else\n lb_e = lb_e_new;\n sigma_e = sigma_e_new;\n if tf_verbose; display([lb_e, sigma_e]); end\n end\nend\nend\n\n\n\n\n% Local functions\n% not yet updated...\nfunction d=f_dist_dKL(p2,nf,bin_centers)\nnf_MP=prob_MP_bin(p2(1),p2(2),bin_centers);\nd_list=nf_MP.*log(nf_MP./nf);\nd_list(nf_MP==0)=0;\nd=sum(d_list);\n% % special treatment of nf=0 bins near 0\nif isinf(d)\n d=1e5+sum((nf-prob_MP_bin(p2(1),p2(2),bin_centers)).^2);\nend;\nend\n", "meta": {"author": "xiuyechen", "repo": "FishExplorer", "sha": "c61392cf0835480d64fc03c15f1992935fdc7106", "save_path": "github-repos/MATLAB/xiuyechen-FishExplorer", "path": "github-repos/MATLAB/xiuyechen-FishExplorer/FishExplorer-c61392cf0835480d64fc03c15f1992935fdc7106/old code/Yu Hu's code/pca_pruning_linkage/estimate_MP2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744584140004, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5383053314320179}} {"text": "% Steffen Urban email: steffen.urban@kit.edu\n% Copyright (C) 2014 Steffen Urban\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% 04.03.2014 by Steffen Urban\n% error function for the center of distortion search\n\nfunction [error] = errCenterUrban(x, calib_data)\n\nerror = 0;\nxc = x(1);\nyc = x(2);\n% call calibration function\n[RRfin, ss] = calibrate(calib_data.Xt, calib_data.Yt, calib_data.Xp_abs, ...\n calib_data.Yp_abs, xc,yc, ...\n calib_data.taylor_order, ...\n calib_data.ima_proc);\nlauf = 1;\nM = [calib_data.Xt,calib_data.Yt,ones(size(calib_data.Xt))]; \n\nfor i = 1:size(RRfin,3) \n % if calibration was not possible add a high value\n % to penalize the minimization away from that point\n if calib_data.RRfin(:,:,i)==0\n error= error+sum(ones(length(calib_data.Xp_abs),1)*sqrt( (calib_data.ocam_model.width/2)^2 + (calib_data.ocam_model.height/2)^2));\n else \n Mc = RRfin(:,:,i)*M';\n Xpp=calib_data.Xp_abs(:,:,i);\n Ypp=calib_data.Yp_abs(:,:,i); \n [xp1,yp1] = omni3d2pixel(ss, Mc, calib_data.ocam_model.width, calib_data.ocam_model.height);\n if (isinf(xp1) | isinf(yp1))\n error = error+sum(ones(length(calib_data.Xp_abs),1)*sqrt( (calib_data.ocam_model.width/2)^2 + (calib_data.ocam_model.height/2)^2));\n else \n xp = xp1 + xc; \n yp = yp1 + yc; \n lauf = lauf+length(Xpp);\n error = error + sum((Xpp-xp').^2) + sum((Ypp-yp').^2);\n end\n\n end\nend\nerror = sqrt(error / lauf);\n\nend\n\n", "meta": {"author": "urbste", "repo": "ImprovedOcamCalib", "sha": "164dd8d96b1bee7e4aba9b0b100a85fcb2f0ba4e", "save_path": "github-repos/MATLAB/urbste-ImprovedOcamCalib", "path": "github-repos/MATLAB/urbste-ImprovedOcamCalib/ImprovedOcamCalib-164dd8d96b1bee7e4aba9b0b100a85fcb2f0ba4e/src/errCenterUrban.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835452961425, "lm_q2_score": 0.6442251064863695, "lm_q1q2_score": 0.538239475936017}} {"text": "function [mMLS] = calc_FitComp(mCatalog, fMinRad, fMaxRad, fRadIncr, fX, fY)\n% function [mMLS] = calc_FitComp(mCatalog, fMinRad, fMaxRad, fRadIncr, fX, fY);\n% -----------------------------------------------------------------------------\n%\n% Function to calculate the MLS fit and the Goodness of fit rate to discriminate which\n% method works best exploring increasing radii\n%\n% Incoming variables:\n%\n% Author: J. Woessner\n% woessner@seismo.ifg.ethz.ch\n% last update: 23.01.03\n\n% Initialize\nmMlS = [];\n\n% Start value\nfRadius = fMinRad;\nwhile fRadius <= fMaxRad\n % Create catalog\n vDistances_ = sqrt(((mCatalog(:,1)-fX)*cos(pi/180*fY)*111).^2 + ((mCatalog(:,2)-fY)*111).^2);\n % Select those in between the maximum radius\n vSel = (vDistances_ <= fRadius);\n vCheckDist = vDistances_(vSel, :);\n mRadCatalog = mCatalog(vSel, :);\n % Determine Mc-values\n [result]=sv_NodeCalcMc(mRadCatalog); % For parameters in result see sv_NodeCalcMc\n\n % Calculate normal and lognormal fit\n [mResult, fProbNorm, fMcNorm, vX_resNorm, fNmaxNorm, mDatPredNorm] = calc_McCdfnormal(mRadCatalog, 0.1);\n [mResult2, fProbLog, fMcLog, fMuLog, fSigmaLog, mDatPredLog, vPredBest] = calc_McCdflognormal(mCat, fBinning);\n [fProbExp, fMcExp, vX_resExp, fNmaxExp, mDatPredExp] = calc_McCdfexp(mRadCatalog, 0.1);\n\n % Show data fit below Mc\n vSel = (mDatPredNorm(:,2) < fMcNorm);\n mTmpNorm = mDatPredNorm(vSel,:);\n vSel = (mDatPredLog(:,2) < fMcLog);\n mTmpLog = mDatPredLog(vSel,:);\n vSel = (mDatPredExp(:,2) < fMcExp);\n mTmpExp = mDatPredExp(vSel,:);\n figure;\n plot(mTmpNorm(:,2), mTmpNorm(:,3),'k*',mTmpNorm(:,2), mTmpNorm(:,1),'-b');\n hold on;\n plot(mTmpLog(:,2), mTmpLog(:,1),'-r');\n plot(mTmpExp(:,2), mTmpExp(:,1),'-g');\n legend('Data','Normal CDF', 'Lognorm. CDF', 'Exponential func.');\n sTitlestr = ['McNorm = ' num2str(fMcNorm) ', McLog = ' num2str(fMcLog) ', McExp = ' num2str(fMcExp) ', R = ' num2str(fRadius)];\n title(sTitlestr)\n xlabel('Magnitude')\n drawnow;\n hold off;\n sPrintstr = ['Fit_kobe_1986_92_135.6_35' num2str(fRadius) 'km.eps'];\n print('-deps2c', '-tiff','-r400', sPrintstr);\n\n % Result array\n mMLS = [mMLS; fRadius result.fProbMcNorm result.fProbMcLog fProbExp result.fMc_max result.fMc_90 result.fMc_95...\n result.fMc_com result.fMcNorm result.fMcLog fMcExp];\n\n % Plot Non-cumulative distribution, original and predicted\n % Time period\n [vFMD, vNonCFMD] = calc_FMD(mRadCatalog);\n vNonCFMD = fliplr(vNonCFMD);\n fPeriod1 = max(mRadCatalog(:,3)) - min(mRadCatalog(:,3));\n % figure_w_normalized_uicontrolunits('tag','ncumdist','Name','Best model','Units','normalized','Nextplot','add',...\n % 'Numbertitle','off','visible','on');\n figure;\n semilogy(vNonCFMD(1,:)', vNonCFMD(2,:)', '-k^',mDatPredNorm(:,2) ,mDatPredNorm(:,1).*fPeriod1,'-bo');\n hold on;\n semilogy(mDatPredLog(:,2) ,mDatPredLog(:,1).*fPeriod1,'-r*');\n semilogy(mDatPredExp(:,2) ,mDatPredExp(:,1).*fPeriod1,'-gs');\n legend('Data','Normal CDF', 'Lognorm. CDF', 'Exponential func.');\n sTitlestr = ['McNorm = ' num2str(fMcNorm) ', McLog = ' num2str(fMcLog) ', McExp = ' num2str(fMcExp) ', R = ' num2str(fRadius)];\n title(sTitlestr)\n xlabel('Magnitude')\n ylabel('Non-cumulative FMD')\n drawnow;\n sPrintstr = ['FMD_kobe_1986_92_135.6_35' num2str(fRadius) 'km.eps'];\n print('-deps2c', '-tiff','-r400', sPrintstr);\n % Increase radius\n fRadius = fRadius+fRadIncr;\nend\n\nfigure;\nsubplot(2,1,1);\nplot(mMLS(:,1), mMLS(:,8),'-bd', mMLS(:,1), mMLS(:,9),'-rd', mMLS(:,1), mMLS(:,10),'-gd');\nxlabel('Radius / [km]')\nylabel('Mc')\nlegend('Normal CDF', 'Lognorm. CDF', 'Exponential func.');\nsubplot(2,1,2);\nplot(mMLS(:,1), mMLS(:,2),'-bd', mMLS(:,1), mMLS(:,3),'-rd', mMLS(:,1), mMLS(:,4),'-gd');\nxlabel('Radius / [km]')\nylabel('MLS')\ndrawnow;\nsPrintstr = ['Radius_kobe_1986_92_135.6_35.eps'];\nprint('-deps2c', '-tiff','-r400', sPrintstr);\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/jochen/seisvar/calc/calc_FitComp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107307, "lm_q2_score": 0.6442251133170356, "lm_q1q2_score": 0.5382394710870323}} {"text": "function [x, infos] = div_admm_nmf(V, rank, in_options)\n% Divergence-based ADMM algorithm for non-negative matrix factorization (KL-FPA-NMF).\n%\n% Inputs:\n% matrix V\n% rank rank\n% options options\n% d_beta : parameter of beta divergence \n% (only beta=0 (IS) and beta=1 (KL) are supported)\n% rho : smothing parameter\n% fixed : vector containing the indices of the basis vectors in \n% W to hold fixed (e.g., when W is known a priori)\n% Output:\n% w solution of w\n% infos information\n%\n% References:\n% D.L. Sun and C. Fvotte, \n% \"Alternating direction method of multipliers for non-negative matrix \n% factorization with the beta divergence,\" \n% ICASSP 2014.\n% \n%\n% This file is part of NMFLibrary\n%\n% This file has been ported from \n% nmf_kl_fpa.m at https://github.com/felipeyanez/nmf\n% by Felipe Yanez\n%\n% Copyright (c) 2014-2016 Felipe Yanez\n%\n% Permission is hereby granted, free of charge, to any person obtaining a \n% copy of this software and associated documentation files (the \"Software\"), \n% to deal in the Software without restriction, including without limitation \n% the rights to use, copy, modify, merge, publish, distribute, sublicense, \n% and/or sell copies of the Software, and to permit persons to whom the \n% Software is furnished to do so, subject to the following conditions:\n%\n% The above copyright notice and this permission notice shall be included \n% in all copies or substantial portions of the Software.\n%\n% THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS \n% OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, \n% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL \n% THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR \n% OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, \n% ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR \n% OTHER DEALINGS IN THE SOFTWARE.\n%\n%\n% Ported by M.Horie and H.Kasai on June 30, 2022\n%\n% Change log: \n%\n% Jul. 12, 2022 (Hiroyuki Kasai): Modified code structures.\n%\n\n\n % set dimensions and samples\n [m, n] = size(V);\n \n % set local options\n local_options = []; \n local_options.rho = 1;\n local_options.metric_type = 'beta-div';\n local_options.d_beta = 1; % parameter of beta divergence (only beta=0 (IS) and beta=1 (KL) are supported)\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 = sprintf('Div-ADMM (%s=%.1f)', options.metric_type, options.d_beta); \n epoch = 0; \n grad_calc_count = 0;\n\n if options.verbose > 0\n fprintf('# %s: started ...\\n', method_name); \n end \n\n % initialize for this algorithm\n fixed=[]; \n % get the vector of indices to update\n free = setdiff(1:rank, fixed);\n \n X = W*H;\n Wplus = W;\n Hplus = H;\n alphaX = zeros(size(X));\n alphaW = zeros(size(W));\n alphaH = zeros(size(H)); \n\n if options.d_beta == 0 && ~isfield(in_options, 'rho') % when IS divergence (d_beta == 0), rho should be much higher.\n local_options.rho = 1000;\n end\n \n % store initial info\n clear infos;\n\n %[options.metric_type, options.metric.param] = check_divergence(options); \n \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 % update H\n H = (W'*W + eye(rank)) \\ (W'*X + Hplus + 1/options.rho*(W'*alphaX - alphaH));\n \n % update W\n P = H*H' + eye(rank);\n Q = H*X' + Wplus' + 1/options.rho*(H*alphaX' - alphaW');\n W(:,free) = ( P(:,free) \\ (Q - P(:,fixed)*W(:,fixed)') )';\n \n % update X (this is the only step that depends on beta)\n X_ap = W*H;\n if options.d_beta == 1\n\n b = options.rho*X_ap - alphaX - 1;\n X = (b + sqrt(b.^2 + 4*options.rho*V))/(2*options.rho);\n \n elseif options.d_beta == 0\n\n A = alphaX/options.rho - X_ap;\n B = 1/(3*options.rho) - A.^2/9;\n C = - A.^3/27 + A/(6*options.rho) + V/(2*options.rho);\n D = B.^3 + C.^2;\n\n X(D>=0) = nthroot(C(D>=0)+sqrt(D(D>=0)),3) + ...\n nthroot(C(D>=0)-sqrt(D(D>=0)),3) - ...\n A(D>=0)/3;\n\n phi = acos(C(D<0) ./ ((-B(D<0)).^1.5));\n X(D<0) = 2*sqrt(-B(D<0)).*cos(phi/3) - A(D<0)/3;\n \n else\n error('beta is not currently supported.')\n end\n\n % update for H_+ and W_+\n Hplus = max(H + 1/options.rho * alphaH, 0);\n Wplus = max(W + 1/options.rho * alphaW, 0);\n \n % update for dual variables\n alphaX = alphaX + options.rho * (X - X_ap);\n alphaH = alphaH + options.rho * (H - Hplus);\n alphaW = alphaW + options.rho * (W - Wplus);\n \n \n % measure gradient calc count\n grad_calc_count = grad_calc_count + m*n;\n\n % measure elapsed time\n elapsed_time = toc(start_time); \n\n % update epoch\n epoch = epoch + 1; \n \n % store info\n 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.W(:,free) = Wplus(:,free);\n x.H = Hplus;\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/divergence/div_admm_nmf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339716830606, "lm_q2_score": 0.640635861701035, "lm_q1q2_score": 0.5379636965488102}} {"text": "function value = r4_chu ( a, b, x )\n\n%*****************************************************************************80\n%\n%% R4_CHU evaluates the confluent hypergeometric function of R4 arguments.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 03 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 A, B, the parameters.\n%\n% Input, real X, the argument.\n%\n% Output, real VALUE, the function value.\n%\n persistent eps\n\n if ( isempty ( eps ) )\n eps = r4_mach ( 3 );\n end\n\n if ( x < 0.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R4_CHU - Fatal error!\\n' );\n fprintf ( 1, ' X < 0.\\n' );\n error ( 'R4_CHU - Fatal error!' )\n end\n\n if ( x == 0.0 )\n if ( 1.0 <= b )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R4_CHU - Fatal error!\\n' );\n fprintf ( 1, ' X = 0 and 1 <= B.\\n' );\n error ( 'R4_CHU - Fatal error!' )\n end\n value = r4_gamma ( 1.0 - b ) / r4_gamma ( 1.0 + a - b );\n return\n end\n\n if ( max ( abs ( a ), 1.0 ) * max ( abs ( 1.0 + a - b ), 1.0 ) < 0.99 * abs ( x ) )\n value = x^( - a ) * r4_chu_scaled ( a, b, x );\n return\n end\n%\n% The ascending series will be used, because the descending rational\n% approximation (which is based on the asymptotic series) is unstable.\n%\n if ( b < 0.0 )\n aintb = r4_aint ( b - 0.5 );\n else\n aintb = r4_aint ( b + 0.5 );\n end\n beps = b - aintb;\n n = aintb;\n\n alnx = log ( x );\n xtoeps = exp ( - beps * alnx );\n%\n% Evaluate the finite sum.\n%\n% Consider the case b < 1.0 first.\n%\n if ( n < 1 )\n\n sum = 1.0;\n t = 1.0;\n m = - n;\n for i = 1 : m\n xi1 = i - 1;\n t = t * ( a + xi1 ) * x / ( ( b + xi1 ) * ( xi1 + 1.0 ) );\n sum = sum + t;\n end\n\n sum = r4_poch ( 1.0 + a - b, - a ) * sum;\n%\n% Now consider the case b .ge. 1.0.\n%\n else\n\n sum = 0.0;\n m = n - 2;\n\n if ( 0 <= m )\n\n t = 1.0;\n sum = 1.0;\n\n for i = 1 : m\n xi = i;\n t = t * ( a - b + xi ) * x / ( ( 1.0 - b + xi ) * xi );\n sum = sum + t;\n end\n\n sum = r4_gamma ( b - 1.0 ) * r4_gamr ( a ) ...\n * x^( 1 - n ) * xtoeps * sum;\n\n end\n\n end\n%\n% Now evaluate the infinite sum.\n%\n if ( n < 1 )\n istrt = 1 - n;\n else\n istrt = 0;\n end\n\n xi = istrt;\n\n factor = r4_mop ( n ) * r4_gamr ( 1.0 + a - b ) * x^istrt;\n\n if ( beps ~= 0.0 )\n factor = factor * beps * pi / sin ( beps * pi );\n end\n\n pochai = r4_poch ( a, xi );\n gamri1 = r4_gamr ( xi + 1.0 );\n gamrni = r4_gamr ( aintb + xi );\n b0 = factor * r4_poch ( a, xi - beps ) * gamrni ...\n * r4_gamr ( xi + 1.0 - beps );\n%\n% x^(-beps) is close to 1.0, so we must be careful in evaluating\n% the differences.\n%\n if ( abs ( xtoeps - 1.0 ) <= 0.5 )\n\n pch1ai = r4_poch1 ( a + xi, - beps );\n pch1i = r4_poch1 ( xi + 1.0 - beps, beps );\n c0 = factor * pochai * gamrni * gamri1 * ( ...\n - r4_poch1 ( b + xi, -beps ) + pch1ai ...\n - pch1i + beps * pch1ai * pch1i );\n%\n% xeps1 = (1.0 - x^(-beps)) / beps = (x^(-beps) - 1.0)/(-beps)\n%\n xeps1 = alnx * r4_exprel ( - beps * alnx );\n value = sum + c0 + xeps1 * b0;\n xn = n;\n\n for i = 1 : 1000\n xi = istrt + i;\n xi1 = istrt + i - 1;\n b0 = ( a + xi1 - beps ) * b0 * x ...\n / ( ( xn + xi1 ) * ( xi - beps ) );\n c0 = ( a + xi1 ) * c0 * x / ( ( b + xi1 ) * xi ) ...\n - ( ( a - 1.0 ) * ( xn + 2.0 * xi - 1.0 )...\n + xi * ( xi - beps ) ) * b0 ...\n / ( xi * ( b + xi1 ) * ( a + xi1 - beps ) );\n t = c0 + xeps1 * b0;\n value = value + t;\n if ( abs ( t ) < eps * abs ( value ) )\n return\n end\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R4_CHU - Fatal error!\\n' );\n fprintf ( 1, ' No convergence in 1000 terms.\\n' );\n error ( 'R4_CHU - Fatal error!' )\n\n end\n%\n% x^(-beps) is very different from 1.0, so the straightforward\n% formulation is stable.\n%\n a0 = factor * pochai * r4_gamr ( b + xi ) * gamri1 / beps;\n b0 = xtoeps * b0 / beps;\n\n value = sum + a0 - b0;\n\n for i = 1 : 1000\n xi = istrt + i;\n xi1 = istrt + i - 1;\n a0 = ( a + xi1 ) * a0 * x / ( ( b + xi1 ) * xi );\n b0 = ( a + xi1 - beps ) * b0 * x ...\n / ( ( aintb + xi1 ) * ( xi - beps ) );\n t = a0 - b0;\n value = value + t;\n if ( abs ( t ) < eps * abs ( value ) )\n return\n end\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R4_CHU - Fatal error!\\n' );\n fprintf ( 1, ' No convergence in 1000 terms.'\\n' );\n\n error ( 'R4_CHU - 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/r4_chu.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339716830605, "lm_q2_score": 0.640635847978761, "lm_q1q2_score": 0.5379636850257504}} {"text": "% Residue Curve Map for Reactive Systems / Methyl Acetate Chemistry\n% Author's Data: Housam BINOUS\n% Department of Chemical Engineering\n% National Institute of Applied Sciences and Technology\n% Tunis, TUNISIA\n% Email: binoushousam@yahoo.com \n\nc=rand(50,3);\n\nfor i=0:9,\n\nxO1=0.00867394;\nx02=0.608674;\nx03=0.191326;\nx04=0.191326;\n\nT0=330;\ny01=0.00025;\n\nX01=0.1*i;\nX02=0.1*(9-i);\n\ntf=20;\n\nx0 = [xO1 x02 x03 x04 y01 T0 X01 X02];\n\nopts = odeset('Mass','M','MassSingular','yes');\n\n[t,x] = ode15s('RCM_MethylAcetate',[0 tf],x0,opts);\n\n\nx1=x(:,7);\nx2=x(:,8);\n\nfigure(1);\nx1=x(:,7);\nx2=x(:,8);\n\nAXIS([0 1 0 1])\nhold on\n\nplot(x1,x2,'color',[c(i+1,1) c(i+1,2) c(i+1,3)],'LineWidth',2);\n\nend\n\nfor i=0:9,\n\nxO1=0.00867394;\nx02=0.608674;\nx03=0.191326;\nx04=0.191326;\n\nT0=330;\ny01=0.00025;\n\nX01=0.1*i;\nX02=0.1*(9-i);\n\ntf=20;\n\nx0 = [xO1 x02 x03 x04 y01 T0 X01 X02];\n\nopts = odeset('Mass','M','MassSingular','yes');\n\n[t,x] = ode15s('RCM_MethylAcetate2',[0 tf],x0,opts);\n\n\nx1=x(:,7);\nx2=x(:,8);\n\nfigure(1);\nx1=x(:,7);\nx2=x(:,8);\n\nAXIS([0 1 0 1])\nhold on\n\nplot(x1,x2,'color',[c(i+1,1) c(i+1,2) c(i+1,3)],'LineWidth',2); \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/8456-residue-curve-map-for-homogeneous-reactive-quaternary-mixtures/binous/RCM_Main_Methyl_Acetate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.6406358479787609, "lm_q1q2_score": 0.5379636824562745}} {"text": "function [mResult] = calc_GridMcBboot(vResults, nMethod)\n% function [mResult] = calc_GridMcBboot(vResults, nMethod)\n% --------------------------------------------------------\n% Calculate Mc and b-value using the bootstrap mean value for an already\n% existing grid with another Mc method\n%\n% Incoming variables:\n% vResults : Struct array from grid calculated with sv_calcMc / sv_calc\n% nMethod : Method to calculate Mc\n%\n% Outgoing variables:\n% mResult : [nNodeGridPoint fMc fStd_Mc fBvalue fStd_B fAvalue fStd_A]\n% Standard deviations by bootstrap\n% fMc, fBvalue, fAvalue are mean values from the bootstrap\n%\n% J. Woessner: woessner@seismo.ifg.ethz.ch\n% last update: 25.11.03\n\nmResult = [];\n\nfor nNodeGridPoint=1:length(vResults.mPolygon(:,1))\n % Get the data for the grid node\n mNodeCatalog_ = vResults.mCatalog(vResults.caNodeIndices{nNodeGridPoint}, :);\n % Create the frequency magnitude distribution\n [vFMD, vNonCFMD] = calc_FMD(mNodeCatalog_);\n [nY,nX]=size(mNodeCatalog_);\n if nY > vResults.nMinimumNumber\n [fMc, fStd_Mc, fBvalue, fStd_B, fAvalue, fStd_A, vMc, mBvalue] = calc_McBboot(mNodeCatalog_,vResults.fBinning, vResults.fBstnum, nMethod);\n mResult = [mResult; nNodeGridPoint fMc fStd_Mc fBvalue fStd_B fAvalue fStd_A];\n else\n mResult = [mResult; nNodeGridPoint NaN NaN NaN NaN NaN NaN];\n end\n if rem(nNodeGridPoint,500) == 0\n save(['result' num2str(nNodeGridPoint) '.mat'],'mResult');\n end\nend\nsave(['result' num2str(nNodeGridPoint) '.mat'],'mResult');\n", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/zmap_deprecated/orphaned/src/jochen/seisvar/calc/calc_GridMcBboot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339756938818, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.5379636818336963}} {"text": "% DEMO_VBRFA - A simple comparison of VB PCA and two robust extensions.\n%\n% The algorithms do not use ARD prior for the loadings W in order to keep\n% the visualizations of the subspaces more clear. In addition, it helps\n% avoiding pruning out relevant components too easily.\n%\n% NOTE: The robust algorithms might be less sensitive to the initialization\n% if they estimate many components. With only one estimated component, they\n% might kill all the components.\n%\n% This demo doesn't always show good results for robust algorithms. You may\n% want to run a few times. In addition, sometimes there are several good\n% interpretations of the data and the robust algorithms pick one.\n\n% Last modified 2010-06-10\n% Copyright (c) Jaakko Luttinen (jaakko.luttinen@tkk.fi)\n\nfunction Q = demo_vbrfa(seed)\n\nn = 50;\nm = 2;\nd = 1;\ndh = d + 0; % number of components to estimate\n\nif nargin >= 1\n randn('state', seed);\n rand('state', seed);\nend\n\nmu = [10;20];\nW = [2; 1];\nX = orth(randn(d,n)')' * sqrt(n);\ns2 = 0.1;\n\n% Generate normal data\nY = W*X + repmat(mu,1,n);\n\n% Add noise\nYn = Y + sqrt(s2)*randn(m,n);\n\n% Generate some outliers\nYno = Yn;\np = (rand(m,n) < 0.05);\nYno(p) = Yno(p) + (5 + 8 * rand(sum(p(:)),1));\n\n% Generate some missing values\nYnom = Yno;\npmv = (rand(m,n) < 0.0);\nYnom(pmv) = NaN;\n\n% Run different algorithms\noptions.init.tau = 1e1*ones(m,1); % the initialization of this can be crucial..\noptions.init.nu = 1;\noptions.prior.a_alpha = 1e10; % \"fix\" w to non-informative for W by\noptions.prior.b_alpha = 1e15; % setting strong prior for w\noptions.update_nu = 1;\noptions.update_alpha = 1;\noptions.update_beta = 1;\noptions.rotate = false;\noptions.common_nu = false;\noptions.common_tau = true;\noptions.maxiter = 100;\n\n% PCA\ndisp('Run PCA')\noptions.robustness = 'none';\nresults_p = vbrfa(Ynom, dh, options);\nW_p = results_p.W;\nX_p = results_p.X;\nMu_p = results_p.Mu;\nnu_p = results_p.nu;\n\n% Robust PCA with multivariate Student-t\ndisp('Run robust PCA with multivariate Student-t')\noptions.robustness = 'multivariate-t';\nresults_rp = vbrfa(Ynom, dh, options);\nW_rp = results_rp.W;\nX_rp = results_rp.X;\nMu_rp = results_rp.Mu;\nnu_rp = results_rp.nu;\n\noptions.maxiter = 1000;\n\n% Robust PCA with independent Student-t\ndisp('Run robust PCA with independent Student-t')\noptions.robustness = 'independent-t';\nresults_rvb = vbrfa(Ynom, dh, options);\nW_rvb = results_rvb.W;\nX_rvb = results_rvb.X;\nMu_rvb = results_rvb.Mu;\nnu_rvb = results_rvb.nu;\n\n% Reconstruct\nY_p = bsxfun(@plus, W_p*X_p, Mu_p);\nY_rp = bsxfun(@plus, W_rp*X_rp, Mu_rp);\nY_rvb = bsxfun(@plus, W_rvb*X_rvb, Mu_rvb);\n\nplot_results(Ynom, []);\nplot_results(Ynom, Y_p)\nplot_results(Ynom, Y_rp)\nplot_results(Ynom, Y_rvb)\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%55\nfunction plot_results(Y, Yh)\n%subspace2d(Yh, [], Y)\nfigure\nplot(Y(1,:), Y(2,:), 'x', 'markersize', 5, 'color', [.2 .2 .2]);\nif ~isempty(Yh)\n hold on\n plot(Yh(1,:), Yh(2,:), 'ko', 'markersize', 3);\n nans = nan*ones(1,size(Y,2));\n plot([Y(1,:);Yh(1,:);nans], [Y(2,:);Yh(2,:);nans], ':', 'color', [.0 .0 .0]);\nend\nset(gca, 'DataAspectRatioMode', 'manual');\nset(gca, 'DataAspectRatio', [1 1 1]);\nset(gca, 'XTick', [], 'YTick', []);\nset(gcf, 'units', 'centimeters');\n% $$$ pos = get(gcf, 'position');\n% $$$ set(gcf, 'position', [pos(1), pos(2), 5 5])\n% $$$ set(gcf, 'PaperPositionMode', 'auto', 'paperunits', 'centimeters', 'PaperSize', [5 5]);\n\nxmg = 0.05 * (max(Y(1,:)) - min(Y(1,:)));\nymg = 0.05 * (max(Y(2,:)) - min(Y(2,:)));\nxl = [min(Y(1,:))-xmg, max(Y(1,:))+xmg];\nyl = [min(Y(2,:))-ymg, max(Y(2,:))+ymg];\nset(gca, 'xlim', xl, 'ylim', yl);\n\n% $$$ % Mark outliers\n% $$$ hold on\n% $$$ indeces = sum(p,1)>0;\n% $$$ plot(VYno(1,indeces), VYno(2, indeces), 'go', 'MarkerSize', 8);\n\n% $$$ % Mark observations with missing values\n% $$$ indeces = sum(pmv,1)>0;\n% $$$ scatter(VYno(1,indeces), VYno(2, indeces), 'yo');\n\nreturn\n\n", "meta": {"author": "jluttine", "repo": "matlab", "sha": "63406c7782b0869948f06e1dbc594460c165d24e", "save_path": "github-repos/MATLAB/jluttine-matlab", "path": "github-repos/MATLAB/jluttine-matlab/matlab-63406c7782b0869948f06e1dbc594460c165d24e/pca/demo_vbrfa.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.5378211437577476}} {"text": "function fx = p12_fun ( option, nvar, x )\n\n%*****************************************************************************80\n%\n%% P12_FUN evaluates the function for problem 12.\n%\n% Title:\n%\n% Materially nonlinear problem.\n%\n% Description:\n%\n% The problem is the two point boundary value problem\n%\n% U'' + LAMBDA * SIN ( U + U**2 + U**3 ) = 0\n%\n% with boundary conditions\n%\n% U(0) = 0.0\n% U(1) = 0.0\n%\n% U is approximated by piecewise polynomials whose coefficients are\n% the unknowns U(1), ..., U(NVAR-1), and the value of LAMBDA is\n% stored as U(NVAR).\n%\n% Options:\n%\n% OPTION Polynomials Continuity\n% 1 linear 1\n% 2 cubic 1\n% 3 cubic 2\n% 4 quintic 1\n% 5 quintic 2\n% 6 quintic 3\n%\n% All options use 8 intervals.\n%\n% Comments:\n%\n% The current program has zero as solution for all X(nvar).\n% Must find bifurcation branch and jump on to it.\n% Perhaps add X(nvar+1) a perturbation to right hand side.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 03 September 2008\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Ivo Babuska, Werner Rheinboldt,\n% Reliable Error Estimations and Mesh Adaptation for the Finite\n% Element Method,\n% in International Conference on Computational Methods\n% in Nonlinear Mechanics,\n% edited by John Oden,\n% Elsevier, 1980,\n% ISBN: 0444853820,\n% LC: QA808.I57.\n%\n% Parameters:\n%\n% Input, integer OPTION, the option index.\n%\n% Input, integer NVAR, the number of variables.\n%\n% Input, real X(NVAR), the argument of the function.\n%\n% Output, real FX(NVAR-1), the value of the function at X.\n%\n nbco = 1;\n nbcz = 1;\n nint = 8;\n maxpolys = 6;\n\n bcone(1) = 0.0;\n bczero(1) = 0.0;\n\n fx(1:nvar-1) = 0.0;\n\n if ( option == 1 )\n npolys = 2;\n nderiv = 1;\n elseif ( option == 2 )\n npolys = 4;\n nderiv = 1;\n elseif ( option == 3 )\n npolys = 4;\n nderiv = 2;\n elseif ( option == 4 )\n npolys = 6;\n nderiv = 1;\n elseif ( option == 5 )\n npolys = 6;\n nderiv = 2;\n elseif ( option == 6 )\n npolys = 6;;\n nderiv = 3;\n end\n\n nvary = nint * npolys;\n%\n% Get the Gauss quadrature rule.\n%\n [ gcoef, gpoint ] = p12_gauss8 ( );\n%\n% Set up the terms A * Y involving the bivariate form\n%\n% For each interval I:\n%\n for i = 1 : nint\n\n iskip = ( i - 1 ) * npolys;\n xl = ( i - 1 ) / nint;\n xr = i / nint;\n dtdx = 2.0 / ( xr - xl );\n%\n% For each Gauss point, J, evaluate the integrand.\n%\n for j = 1 : 8\n\n t = gpoint(j);\n coef = gcoef(j) * ( xr - xl ) / 2.0;\n [ pl, pld ] = p12_legendre_val ( t, dtdx, npolys );\n\n u = 0.0;\n uprym = 0.0;\n for k = 1 : npolys\n u = u + x(iskip+k) * pl(k);\n uprym = uprym + x(iskip+k) * pld(k);\n end\n\n phi = - uprym;\n psi = x(nvar) * sin ( u * ( 1.0 + u * ( 1.0 + u ) ) );\n lskip = iskip;\n%\n% Project onto each test function L.\n%\n for l = 1 : npolys\n ieqn = lskip + l;\n fx(ieqn) = fx(ieqn) + coef * ( psi * pl(l) + phi * pld(l) );\n end\n\n lskip = lskip + npolys;\n\n end\n\n end\n%\n% 2. Add the terms B * Z for the continuity of the test functions.\n%\n% For each interval I:\n%\n for i = 1 : nint\n\n if ( i == 1 )\n ncl = nvary;\n else\n ncl = nvary + nbcz + ( i - 2 ) * nderiv;\n end\n\n ncr = nvary + nbcz + ( i - 1 ) * nderiv;\n xl = ( i - 1 ) / nint;\n xr = i / nint;\n dtdx = 2.0 / ( xr - xl );\n%\n% Count conditions at the left endpoint, LHIL, and at right, LHIR.\n% If we are in the first or last interval, one of\n% these will be boundary conditions.\n%\n if ( i == 1 )\n lhil = nbcz;\n else\n lhil = nderiv;\n end\n\n if ( i == nint )\n lhir = nbco;\n else\n lhir = nderiv;\n end\n%\n% For each test function PL(K):\n%\n for k = 1 : npolys\n\n s = r8_mop ( k + 1 );\n ieqn = ( i - 1 ) * npolys + k;\n%\n% Apply the boundary conditions.\n%\n h2i = 1.0;\n for l = 1 : lhil\n s = - s;\n ivar = ncl + l;\n fx(ieqn) = fx(ieqn) + s * x(ivar) * h2i * p12_theta ( l, k );\n h2i = h2i * dtdx;\n end\n\n h2i = 1.0;\n for l = 1 : lhir\n ivar = ncr + l;\n fx(ieqn) = fx(ieqn) + x(ivar) * h2i * p12_theta ( l, k );\n h2i = h2i * dtdx;\n end\n\n end\n\n end\n%\n% 3. Create the C * Y terms for U and its derivatives.\n% One equation is generated for component and condition.\n%\n npsum = 0;\n dtdxr = 0.0;\n dtdxl = 0.0;\n%\n% For each node:\n%\n ndsum = nvary;\n\n for i = 1 : nint + 1\n\n if ( 1 < i )\n xl = ( i - 2 ) / nint;\n end\n\n xc = ( i - 1 ) / nint;\n\n if ( i < nint + 1 )\n xr = i / ( nint );\n end\n\n if ( xc ~= xl )\n dtdxl = 2.0 / ( xc - xl );\n end\n\n if ( xr ~= xc )\n dtdxr = 2.0 / ( xr - xc );\n end\n\n h2il = 1.0;\n h2ir = 1.0;\n%\n% Count the conditions:\n%\n if ( i == 1 )\n khi = nbcz;\n elseif ( i < nint + 1 )\n khi = nderiv;\n elseif ( i == nint + 1 )\n khi = nbco;\n end\n\n for k = 1 : khi\n\n s = r8_mop ( k + 1 );\n%\n% Set up the term from the left hand interval.\n%\n ieqn = ndsum + k;\n\n if ( i == 1 )\n\n fx(ieqn) = fx(ieqn) + bczero(k);\n\n else\n\n for l = 1 : npolys\n ivar = npsum + l - npolys;\n fx(ieqn) = fx(ieqn) + x(ivar) * h2il * p12_theta ( k, l );\n end\n\n end\n%\n% Set up the term from the right hand interval.\n%\n if ( i == nint + 1 )\n\n fx(ieqn) = fx(ieqn) - bcone(k);\n\n else\n\n for l = 1 : npolys\n ivar = npsum + l;\n s = - s;\n fx(ieqn) = fx(ieqn) + s * x(ivar) * h2ir * p12_theta(k,l);\n end\n end\n\n h2il = h2il * dtdxl;\n h2ir = h2ir * dtdxr;\n\n end\n\n ndsum = ndsum + khi;\n npsum = npsum + npolys;\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_con/p12_fun.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802476562641, "lm_q2_score": 0.6992544210587586, "lm_q1q2_score": 0.5377827633226077}} {"text": "% inverse dynamics (recursive Newton-Euler) using spatial vector notation\nfunction tau = ID( model, q, qd, qdd )\n \n a_grav = SpatialAcceleration([0;0;-9.81;0;0;0]);\n \n for i = 1:model.NB\n [ XJ, S(:,i) ] = jcalc( model.pitch(i), q(i) );\n XJ\n S(:,i)\n vJ = SpatialVelocity(S(:,i)*qd(i));\n Xup(i) = XJ*model.Xtree(i);\n if model.parent(i) == 0\n v(i) = vJ;\n a(i) = Xup(i)*(-a_grav) + SpatialAcceleration(S(:,i)*qdd(i));\n a\n else\n v(i) = Xup(i)*v(model.parent(i)) + vJ;\n a(i) = Xup(i)*a(model.parent(i)) ...\n + SpatialAcceleration(S(:,i)*qdd(i)) ...\n + cross(v(i),vJ);\n end\n f(i) = model.I(i)*a(i) + cross( v(i), model.I(i)*v(i) );\n end\n\n v\n a\n f\n \n for i = model.NB:-1:1\n tau(i,1) = S(:,i)' * double(f(i));\n if model.parent(i) ~= 0\n f(model.parent(i)) = f(model.parent(i)) + Xup(i)*f(i);\n end\n end\nend\n\nfunction [Xj,S] = jcalc( pitch, q ) %FIXED VW ORDER\n \n % jcalc Calculate joint transform and motion subspace.\n % [Xj,S]=jcalc(pitch,q) calculates the joint transform and motion subspace\n % matrices for a revolute (pitch==0), prismatic (pitch==inf) or helical\n % (pitch==any other value) joint. For revolute and helical joints, q is\n % the joint angle. For prismatic joints, q is the linear displacement.\n \n if pitch == 0\t\t\t\t% revolute joint\n Xj = Twist(SE3.Rz(q));\n S = [0;0;0;0;0;1];\n elseif pitch == inf\t\t\t% prismatic joint\n Xj = Twist(SE3([0 0 q]));\n S = [0;0;1;0;0;0];\n else\t\t\t\t\t% helical joint\n Xj = Twist(SE3.Rz(q) * SE3([0 0 q*pitch]));\n S = [0;0;pitch0;0;1;];\n end\nend\n", "meta": {"author": "petercorke", "repo": "spatialmath-matlab", "sha": "6eeff4a79f14286705560b84f1fe72e0b7e0e7f7", "save_path": "github-repos/MATLAB/petercorke-spatialmath-matlab", "path": "github-repos/MATLAB/petercorke-spatialmath-matlab/spatialmath-matlab-6eeff4a79f14286705560b84f1fe72e0b7e0e7f7/unit_test/featherstone_test/ID.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127566694178, "lm_q2_score": 0.6297746074044135, "lm_q1q2_score": 0.537772571089103}} {"text": "function [Q_k,T_k,r,anorm,ierr,work] = lanpro(A,nin,kmax,r,options,...\n Q_k,T_k,anorm)\n \n%LANPRO Lanczos tridiagonalization with partial reorthogonalization\n% LANPRO computes the Lanczos tridiagonalization of a real symmetric \n% matrix using the symmetric Lanczos algorithm with partial \n% reorthogonalization. \n%\n% [Q_K,T_K,R,ANORM,IERR,WORK] = LANPRO(A,K,R0,OPTIONS,Q_old,T_old)\n% [Q_K,T_K,R,ANORM,IERR,WORK] = LANPRO('Afun',N,K,R0,OPTIONS,Q_old,T_old)\n%\n% Computes K steps of the Lanczos algorithm with starting vector R0, \n% and returns the K x K tridiagonal T_K, the N x K matrix Q_K \n% with semiorthonormal columns and the residual vector R such that \n%\n% A*Q_K = Q_K*T_K + R .\n%\n% Partial reorthogonalization is used to keep the columns of Q_K \n% semiorthogonal:\n% MAX(DIAG((eye(k) - Q_K'*Q_K))) <= OPTIONS.delta.\n%\n%\n% The first input argument is either a real symmetric matrix, a struct with\n% components A.L and A.U or a string containing the name of an M-file which \n% applies a linear operator to the columns of a given matrix. In the latter\n% case, the second input argument must be N, the order of the problem.\n%\n% If A is a struct with components A.L and A.U, such that \n% L*U = (A - sigma*I), a shift-and-invert Lanczos iteration is performed\n%\n% The OPTIONS structure is used to control the reorthogonalization:\n% OPTIONS.delta: Desired level of orthogonality \n% (default = sqrt(eps/K)).\n% OPTIONS.eta : Level of orthogonality after reorthogonalization \n% (default = eps^(3/4)/sqrt(K)).\n% OPTIONS.cgs : Flag for switching between different reorthogonalization\n% algorithms:\n% 0 = iterated modified Gram-Schmidt (default)\n% 1 = iterated classical Gram-Schmidt \n% OPTIONS.elr : If OPTIONS.elr = 1 (default) then extended local\n% reorthogonalization is enforced.\n% OPTIONS.Y : The lanczos vectors are reorthogonalized against\n% the columns of the matrix OPTIONS.Y.\n%\n% If both R0, Q_old and T_old are provided, they must contain \n% a partial Lanczos tridiagonalization of A on the form\n%\n% A Q_old = Q_old T_old + R0 . \n%\n% In this case the factorization is extended to dimension K x K by\n% continuing the Lanczos algorithm with R0 as starting vector.\n%\n% On exit ANORM contains an approximation to ||A||_2. \n% IERR = 0 : K steps were performed succesfully.\n% IERR > 0 : K steps were performed succesfully, but the algorithm\n% switched to full reorthogonalization after IERR steps.\n% IERR < 0 : Iteration was terminated after -IERR steps because an\n% invariant subspace was found, and 3 deflation attempts \n% were unsuccessful.\n% On exit WORK(1) contains the number of reorthogonalizations performed, and\n% WORK(2) contains the number of inner products performed in the\n% reorthogonalizations.\n%\n% See also LANEIG, REORTH, COMPUTE_INT\n\n% References: \n% R.M. Larsen, Ph.D. Thesis, Aarhus University, 1998.\n%\n% G. H. Golub & C. F. Van Loan, \"Matrix Computations\",\n% 3. Ed., Johns Hopkins, 1996. Chapter 9.\n%\n% B. N. Parlett, ``The Symmetric Eigenvalue Problem'', \n% Prentice-Hall, Englewood Cliffs, NJ, 1980.\n%\n% H. D. Simon, ``The Lanczos algorithm with partial reorthogonalization'',\n% Math. Comp. 42 (1984), no. 165, 115--142.\n\n% Rasmus Munk Larsen, DAIMI, 1998\n\n\n% Check input arguments.\nif nargin<1, error('Not enough input arguments.'); end\nif isnumeric(A) | isstruct(A)\n if isnumeric(A)\n [m n] = size(A);\n if m~=n | ~isequal(A,A') | ~isreal(A)\n error('A must be real symmetric')\n end \n elseif isstruct(A)\n [m n] = size(A.L);\n end\n \n if nargin<7 | isempty(T_k), \n anorm = []; est_anorm=1; \n else\n anorm = T_k; est_anorm=0; \n end\n if nargin<6, Q_k=[]; T_k=[]; else, T_k = Q_k; Q_k = options; end\n if nargin<4 | isempty(r), options = []; else, options = r; end\n if nargin<3 | isempty(kmax), \n r = rand(n,1)-0.5;\n else\n r = kmax;\n end\n if nargin<2 | isempty(nin); kmax = max(10,n/10); else, kmax = nin; end \nelse\n if nargin<2\n error('Not enough input arguments.');\n end\n % Check input functions and parse to create an internal object\n % if an explicit expression is given.\n [A, msg] = fcnchk(A);\n if ~isempty(msg)\n error(msg);\n end \n n = nin;\n if nargin<8 | isempty(anorm), anorm = []; est_anorm=1; else est_anorm=0; end\n if nargin<7, Q_k=[]; T_k=[]; end\n if nargin<5 | isempty(options), options = []; end\n if nargin<4 | isempty(r), r = rand(n,1)-0.5; end\n if nargin<3 | isempty(kmax); kmax = max(10,n/10); end\nend\n \n% Set options. \ndelta = sqrt(eps/kmax); % Desired level of orthogonality.\neta = eps^(3/4)/sqrt(kmax); % Level of orth. after reorthogonalization.\ncgs = 0; % Flag for switching between iterated CGS and MGS.\nelr = 1; % Flag for switching extended local \n % reorthogonalization on and off.\ndeflate = 0; % Flag for deflation against OPTIONS.Y\n\t\t\t\n% Parse options struct\nif ~isempty(options) & isstruct(options)\n c = fieldnames(options);\n for i=1:length(c)\n if strmatch(c(i),'delta'), delta = getfield(options,'delta'); end\n if strmatch(c(i),'eta'), eta = getfield(options,'eta'); end\n if strmatch(c(i),'cgs'), cgs = getfield(options,'cgs'); end\n if strmatch(c(i),'elr'), elr = getfield(options,'elr'); end\n if strmatch(c(i),'Y'), deflate = ~isempty(options.Y); end\n end\nend\n\nnp = 0; nr = 0; ierr=0;\n\n% Rule-of-thumb estimate on the size of round-off terms:\neps1 = sqrt(n)*eps/2; % Notice that {\\bf u} == eps/2.\ngamma = 1/sqrt(2);\n\n% Prepare Lanczos iteration\nif isempty(Q_k) % New Lanczos tridiagonalization.\n % Allocate space \n alpha = zeros(kmax+1,1); beta = zeros(kmax+1,1);\n Q_k = zeros(n,kmax);\n q = zeros(n,1); beta(1)=norm(r);\n omega = zeros(kmax,1); omega_max = omega; omega_old = omega;\n omega(1) = 0; force_reorth= 0; \n j0 = 1;\nelse % Extending existing Lanczos tridiagonalization.\n j = size(Q_k,2); % Size of existing factorization\n % Allocate space\n Q_k = [Q_k zeros(n,kmax-j)]; \n alpha = zeros(kmax+1,1); beta = zeros(kmax+1,1);\n alpha(1:j) = diag(T_k); \n if j>1\n beta(2:j) = diag(T_k,-1);\n end\n q = Q_k(:,j);\n % Reorthogonalize r.\n beta(j+1) = norm(r);\n if j1\n t1 = q_old'*r;\n t2 = q'*r;\n r = r - (q_old*t1 + q*t2); % Add small terms together first to\n if beta(j)~=0 % reduce risk of cancellation.\n\tbeta(j) = beta(j) + t1;\n end\n alpha(j) = alpha(j) + t2;\n end \n beta(j+1) = sqrt(r'*r); % Quick and dirty estimate.\n end\n\n % Update Gersgorin estimate of ||T_k|| if required\n% if est_anorm & beta(j+1)~=0\n% T_k = spdiags([[beta(2:j);0] alpha(1:j) beta(1:j)],-1:1,j,j);\n% anorm = sqrt(norm(T_k'*T_k,1))\n% end\n if est_anorm & beta(j+1)~=0\n anorm = update_gbound(anorm,alpha,beta,j);\n end\n\n % Update omega-recurrence\n if j>1 & ~fro & beta(j+1)~=0\n [omega,omega_old] = update_omega(omega,omega_old,j,alpha,beta,...\n\teps1,anorm);\n omega_max(j) = max(abs(omega));\n end\n\n % Reorthogonalize if required\n if j>1 & (fro | force_reorth | omega_max(j)>delta) & beta(j+1)~=0\n if fro\n int = 1:j;\n else\n if force_reorth == 0\n\tforce_reorth= 1; % Do forced reorth to avoid spill-over from q_{j-1}.\n\tint = compute_int(omega,j,delta,eta,0,0,0);\n else\n\tforce_reorth= 0; \n end\n end\n [r,beta(j+1),rr] = reorth(Q_k,r,beta(j+1),int,gamma,cgs);\n omega(int) = eps1;\n np = np + rr*length(int(:)); nr = nr + 1;\n else\n beta(j+1) = norm(r); % compute norm accurately.\n end\n\n if deflate \n [r,beta(j+1),rr] = reorth(options.Y,r,beta(j+1),1:size(options.Y,2), ...\n\t\t\t gamma,cgs);\n end\n \n if j 0\n\t% A vector numerically orthogonal to span(Q_k(:,1:j)) was found. \n\t% Continue iteration.\n\tbailout=0;\n\tbreak;\n end\n end\n if bailout\n ierr = -j;\n break;\n else\n r=r/nrmnew; % Continue with new normalized r as starting vector.\n force_reorth = 1;\n if delta>0\n\tfro = 0; % Turn off full reorthogonalization.\n end\n end \n elseif j delta then omega(j+1) will \n % immediately exceed delta, and thus forcing a reorth. to occur at the\n % next step. The components of omega will mainly be determined\n % by the initial value and not the recurrence, and therefore we \n % cannot tell reliably which components exceed eta => we might \n % as well switch to full reorthogonalization to avoid trouble.\n % The user is probably trying to determine pathologically\n % small ( < sqrt(eps)*||A||_2 ) eigenvalues. \n % warning(['Semiorthogonality cannot be maintained at iteration ', ...\n %\t num2str(j),'. The matrix is probably ill-conditioned.', ...\n %\t ' Switching to full reorthogonalization.'])\n fro = 1;\n ierr = j;\n end\nend\n\n% Set up tridiagonal T_k in sparse matrix data structure.\nT_k = spdiags([[beta(2:j);0] alpha(1:j) beta(1:j)],-1:1,j,j);\nif nargout<2\n Q_k = T_k;\nelseif j~=size(Q_k,2)\n Q_k = Q_k(:,1:j);\nend\nwork = [nr np];\n\n\nfunction [omega,omega_old] = update_omega(omega, omega_old, j, ...\n alpha,beta,eps1,anorm)\n% UPDATE_OMEGA: Update Simon's omega_recurrence for the Lanczos vectors.\n%\n% [omega,omega_old] = update_omega(omega, omega_old,j,eps1,alpha,beta,anorm)\n% \n\n% Rasmus Munk Larsen, DAIMI, 1998.\n\n% Estimate of contribution to roundoff errors from A*v \n% fl(A*v) = A*v + f, \n% where ||f|| \\approx eps1*||A||.\n% For a full matrix A, a rule-of-thumb estimate is eps1 = sqrt(n)*eps.\nT = eps1*anorm;\nbinv = 1/beta(j+1);\n\nomega_old = omega;\n% Update omega(1) using omega(0)==0.\nomega_old(1)= beta(2)*omega(2)+ (alpha(1)-alpha(j))*omega(1) - ...\n beta(j)*omega_old(1);\nomega_old(1) = binv*(omega_old(1) + sign(omega_old(1))*T);\n% Update remaining components.\nk=2:j-2;\nomega_old(k) = beta(k+1).*omega(k+1) + (alpha(k)-alpha(j)).*omega(k) ...\n + beta(k).*omega(k-1) - beta(j)*omega_old(k);\nomega_old(k) = binv*(omega_old(k) + sign(omega_old(k))*T); \nomega_old(j-1) = binv*T;\n% Swap omega and omega_old.\ntemp = omega;\nomega = omega_old;\nomega_old = omega;\nomega(j) = eps1;\n\n\nfunction anorm = update_gbound(anorm,alpha,beta,j)\n%UPDATE_GBOUND Update Gerscgorin estimate of 2-norm \n% ANORM = UPDATE_GBOUND(ANORM,ALPHA,BETA,J) updates the Gerscgorin bound\n% for the tridiagonal in the Lanczos process after the J'th step.\n% Applies Gerscgorins circles to T_K'*T_k instead of T_k itself\n% since this gives a tighter bound.\n\nif j==1 % Apply Gerscgorin circles to T_k'*T_k to estimate || A ||_2\n i=j; \n % scale to avoid overflow\n scale = max(abs(alpha(i)),abs(beta(i+1)));\n alpha(i) = alpha(i)/scale;\n beta(i+1) = beta(i+1)/scale;\n anorm = 1.01*scale*sqrt(alpha(i)^2+beta(i+1)^2 + abs(alpha(i)*beta(i+1)));\nelseif j==2\n i=1;\n % scale to avoid overflow\n scale = max(max(abs(alpha(1:2)),max(abs(beta(2:3)))));\n alpha(1:2) = alpha(1:2)/scale;\n beta(2:3) = beta(2:3)/scale;\n \n anorm = max(anorm, scale*sqrt(alpha(i)^2+beta(i+1)^2 + ...\n abs(alpha(i)*beta(i+1) + alpha(i+1)*beta(i+1)) + ...\n abs(beta(i+1)*beta(i+2))));\n i=2;\n anorm = max(anorm,scale*sqrt(abs(beta(i)*alpha(i-1) + alpha(i)*beta(i)) + ...\n beta(i)^2+alpha(i)^2+beta(i+1)^2 + ...\n abs(alpha(i)*beta(i+1))) );\nelseif j==3\n % scale to avoid overflow\n scale = max(max(abs(alpha(1:3)),max(abs(beta(2:4)))));\n alpha(1:3) = alpha(1:3)/scale;\n beta(2:4) = beta(2:4)/scale;\n i=2;\n anorm = max(anorm,scale*sqrt(abs(beta(i)*alpha(i-1) + alpha(i)*beta(i)) + ...\n beta(i)^2+alpha(i)^2+beta(i+1)^2 + ...\n abs(alpha(i)*beta(i+1) + alpha(i+1)*beta(i+1)) + ...\n abs(beta(i+1)*beta(i+2))) );\n i=3;\n anorm = max(anorm,scale*sqrt(abs(beta(i)*beta(i-1)) + ...\n abs(beta(i)*alpha(i-1) + alpha(i)*beta(i)) + ...\n beta(i)^2+alpha(i)^2+beta(i+1)^2 + ...\n abs(alpha(i)*beta(i+1))) );\nelse\n % scale to avoid overflow\n % scale = max(max(abs(alpha(j-2:j)),max(abs(beta(j-2:j+1)))));\n % alpha(j-2:j) = alpha(j-2:j)/scale;\n % beta(j-2:j+1) = beta(j-2:j+1)/scale;\n \n % Avoid scaling, which is slow. At j>3 the estimate is usually quite good\n % so just make sure that anorm is not made infinite by overflow.\n i = j-1;\n anorm1 = sqrt(abs(beta(i)*beta(i-1)) + ...\n abs(beta(i)*alpha(i-1) + alpha(i)*beta(i)) + ...\n beta(i)^2+alpha(i)^2+beta(i+1)^2 + ...\n abs(alpha(i)*beta(i+1) + alpha(i+1)*beta(i+1)) + ...\n abs(beta(i+1)*beta(i+2)));\n if isfinite(anorm1)\n anorm = max(anorm,anorm1);\n end\n i = j;\n anorm1 = sqrt(abs(beta(i)*beta(i-1)) + ...\n abs(beta(i)*alpha(i-1) + alpha(i)*beta(i)) + ...\n beta(i)^2+alpha(i)^2+beta(i+1)^2 + ...\n abs(alpha(i)*beta(i+1)));\n if isfinite(anorm1)\n anorm = max(anorm,anorm1);\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/algorithms/mc/SVP/private/lanpro.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8080672135527631, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.5376964614367882}} {"text": "function A = slkfd(K, nums, varargin)\n%SLKFD Perform Kernelized Fisher Discriminant Analysis\n%\n% $ Syntax $\n% - A = slkfd(K, nums, ...)\n%\n% $ Arguments $\n% - K: the kernel gram matrix of the training samples\n% - nums: the numbers of samples in all classes\n% - A: the projection coefficient matrix \n% \n% $ Description $\n% - A = slkfd(K, nums, ...) performs Kernerlized Fisher discriminant \n% analysis on the samples X according to the specified properties. \n% \\*\n% \\t Table 1. The properties of Fisher Discriminant Analysis \\\\\n% \\h name & description \\\\\n% 'sol' & The cell containing the arguments for solving\n% the generalized eigen-problem by slsymgeig. \n% default = {}. \\\\\n% 'dimset' & The cell containing the arguments for determining\n% the output feature dimension. default = {}.\n% (refer to sldim_by_eigval). \\\\\n% 'Sb' & The pre-computed kernelized between-class \n% scattering matrix or the cell containing \n% the arguments for computing the kernelized \n% scatter matrix in the form {type, ...}, \n% which is input to slkernelscatter. \\\\\n% 'Sw' & The pre-computed kernelized within-class \n% scattering matrix or the cell containing \n% the arguments for computing the scatter \n% matrix in the form {type, ...}, which is \n% input to slkernelscatter. \\\\\n% 'weights' & The sample weights. default = []. \\\\\n% \\* \n%\n% $ History $\n% - Created by Dahua Lin on May 03, 2006\n%\n\n%% parse and verify input arguments\n\nif nargin < 2\n raise_lackinput('slkfd', 2);\nend\n\n% for K\nn = size(K, 1);\nif ~isequal(size(K), [n, n])\n error('sltoolbox:invaliddims', ...\n 'K should be a square matrix');\nend\n\n% for nums\nnc = length(nums);\nif ~isequal(size(nums), [1 nc])\n error('sltoolbox:sizmismatch', ...\n 'nums should be a 1 x nc row vector');\nend\n\n% for options\n\nopts.sol = {};\nopts.dimset = {};\nopts.Sb = {'Sb'};\nopts.Sw = {'Sw'};\nopts.weights = [];\nopts = slparseprops(opts, varargin{:});\n\nhas_Sb = ~isempty(opts.Sb) && isnumeric(opts.Sb);\nhas_Sw = ~isempty(opts.Sw) && isnumeric(opts.Sw);\nif has_Sb\n Sb = opts.Sb;\n if ~isequal(size(Sb), [n n])\n error('sltoolbox:sizmismatch', ...\n 'Sb should be a n x n matrix');\n end\nend\nif has_Sw\n Sw = opts.Sw;\n if ~isequal(size(Sw), [n n])\n error('sltoolbox:sizmismatch', ...\n 'Sw should be a n x n matrix');\n end\nend\n\nif ~isempty(opts.weights)\n w = opts.weights;\n if ~isequal(size(w), [1 n])\n error('sltoolbox:sizmismatch', ...\n 'The weights should be a 1 x n row vector');\n end\nelse\n w = [];\nend\n\n\n%% Compute \n\n%% Step 1: Construct the eigen-problem\n\nif ~has_Sb\n Sb = slscatter(K, opts.Sb{:}, 'sweights', w, 'nums', nums);\nend\n\nif ~has_Sw\n Sw = slscatter(K, opts.Sw{:}, 'sweights', w, 'nums', nums);\nend\n\n\n%% Step 2: Resolve the eigen-problem\n\n[evs, A] = slsymgeig(Sb, Sw, opts.sol{:});\n\nrk = sldim_by_eigval(evs, opts.dimset{:});\nA = A(:, 1:rk);\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/kernel/slkfd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.808067204308405, "lm_q2_score": 0.6654105653819835, "lm_q1q2_score": 0.5376964552854945}} {"text": "function [C,S,a,c]=getEMMCoeffs(M,year,fullyNormalize)\n%%GETEMMCOEFFS Obtain spherical harmonic coefficients for the 2017 \n% version of the National Oceanic and Atmospheric\n% Administration's (NOAA's) Enchaned Magnetic Model (EMM) at a\n% particular time or at the reference epoch (2017). The model\n% is considered valid down to 10km underground.\n%\n%INPUTS: M The integer maximum order of the spherical harmonic coefficients\n% obtained. This is a value between 1 and 740. If this parameter\n% is omitted, the default value is 740. If one wishes to load all\n% coefficients, one can also just pass Inf.\n% year A decimal number indicating a year in the Gregorian calendar as\n% specified by universal coordinated time (UTC). For example,\n% halfway through the year 2017 would be represented as 2017.5.\n% The precision of the model is not sufficiently fine that leap\n% seconds matter. If this parameter is omitted, then the\n% reference year of the EMM model is used. In this instance,\n% 2017.0.\n% fullyNormalize Geomagnetic models are normally given in terms of Schmidt\n% semi-normalized Legendre functions. If fullyNormalize=true, then\n% the coefficients are converted for use with fully normalized\n% associated Legendre functions, as are commonly used with\n% spherical harmonic algorithms for gravitational models. If this\n% parameter is omitted, the default value is true.\n%\n%OUTPUTS: C An array holding the coefficient terms that are multiplied by\n% cosines in the harmonic expansion. This can be given to a\n% CountingClusterSet so that C(n+1,m+1) is the coefficient of\n% degree n and order m. The coefficients have units of Tesla. The\n% coefficients are normalized according to the fullyNormalize\n% term.\n% S An array holding the coefficient terms that are multiplied by\n% sines in the harmonic expansion. The format of S is the same as\n% that of C.\n% a The numerator in the (a/r)^n term in the spherical harmonic sum\n% having units of meters.\n% c The constant value by which the spherical harmonic series is\n% multiplied, having units of squared meters.\n%\n%Details on the normalization of the coefficients is given in the comments\n%to the function spherHarmonicEval.\n%\n%This function first checks for a .mat file with the coefficients in it.\n%The .mat file is small and can be read quite quickly. However, if one does\n%not exist, then it tries to read the EMM2015.COF and EMM2015SV.COF text\n%files that one can obtain directly from the NOAA. Reading from the text\n%files is very slow.\n%\n%Documentation is in [1] and [2]. Documentation as well as some code\n%containing containing the coefficients is available at\n%http://www.ngdc.noaa.gov/geomag/EMM/\n%Being created by the U.S. government, the model is not subject to\n%copyright.\n%\n%The data is kept in zipped files in the ./data folder. If all of the data\n%is being loaded for a particular year (M=Inf), then a .mat file will be\n%created in the ./data folder with the data for that year so that it can be\n%loaded more quickly in the future.\n%\n%REFERENCES:\n%[1] S. Maus, \"An ellipsoidal harmonic representation of Earth's\n% lithospheric magnetic field to degree and order 720,\" Geochemistry,\n% Geophysics, Geosystems, vol. 11, no. 6, Jun. 2010.\n%[2] Information on Schmidt semi-normalized Legendre functions is given in\n% D. E. Winch, D. J. Ivers, J. P. R. Turner, and R. J. Stening,\n% \"Geomagnetism and Schmidt quasi-normalization,\" Geophysical Journal\n% International, vol. 160, no. 2, pp. 487-504, Feb. 2005.\n%\n%June 2015 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin<1||isempty(M))\n M=Inf;%Load all of the coefficients.\nend\n\nyearRef=2015.0;\nif(nargin<2||isempty(year))\n year=yearRef;\nend\n\nif(nargin<3||isempty(fullyNormalize))\n fullyNormalize=true;\nend\n\nsaveMatFile=(M==Inf);\n\n%The EMM2015 magnetic coefficient data file, should be located in a data \n%folder that is in the same folder as this file. This find the path to this\n%file.\nScriptPath=mfilename('fullpath');\nScriptFolder=fileparts(ScriptPath);\n\n%We have to load the version of the EMM that predicts for the year\n%given. To know which one to load, we will see which years are in the\n%zip archive. The years are given in the filenames.\nfilePathAndName=fileNamesInZipArchive([ScriptFolder,'/data/EMM_Coefficients.zip']);\nsecVarFilePathAndName=fileNamesInZipArchive([ScriptFolder,'/data/EMM_Secular_Variations.zip']);\n\nnumFiles=length(filePathAndName);\nEMMYears=zeros(numFiles,1);\nfor curFile=1:numFiles\n [~,fileName] = fileparts(filePathAndName{curFile});\n %The filenames all begin with EMM, so skip the first three\n %characters to get the years.\n EMMYears(curFile)=sscanf(fileName(4:end),'%f',1);\nend\n\n%We have to find the EMM model year that is equal to the integer part\n%of year. If there is none, then we have to find the closest year.\nyearIdx2Load=find(EMMYears==fix(year),1);\nif(isempty(yearIdx2Load)||yearIdx2Load~=year)\n [~,yearIdx2Load]=min(abs(EMMYears-fix(year)));\nend\nyearRef=EMMYears(yearIdx2Load);\n\n%First, see if a .mat file with all of the data for the appropriate year\n%exists. If so, then use that to load the coefficients from which\n%interpolation must be performed.\nmatFile=[ScriptFolder,'/data/EMM',int2str(yearRef),'.mat'];\n\nif(exist(matFile,'file'))\n load(matFile,'CCoeffs','SCoeffs','C1Coeffs','S1Coeffs');\n\n %Keep only as many coefficients as the maximum order provided.\n totalNumCoeffs=(M+1)*(M+2)/2;\n if(length(CCoeffs)0.5\n i(e2)=d; j(e2)=c; \t%flip edge c-d with 50% probability\n c=i(e2); d=j(e2); \t%to explore all potential rewirings\n end\n \n %rewiring condition\n if ~(R(a,d) || R(c,b))\n %lattice condition\n if (D(a,b)*R(a,b)+D(c,d)*R(c,d))>=(D(a,d)*R(a,b)+D(c,b)*R(c,d))\n R(a,d)=R(a,b); R(a,b)=0;\n R(d,a)=R(b,a); R(b,a)=0;\n R(c,b)=R(c,d); R(c,d)=0;\n R(b,c)=R(d,c); R(d,c)=0;\n\n j(e1) = d; %reassign edge indices\n j(e2) = b;\n eff = eff+1;\n break;\n end %lattice condition\n end %rewiring condition\n att=att+1;\n end %while not rewired\nend %iterations\n\n% lattice in node order used for latticization\nRrp = R;\n% reverse random permutation of nodes\n[~,ind_rp_reverse] = sort(ind_rp);\nRlatt = Rrp(ind_rp_reverse,ind_rp_reverse);\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/bct/latmio_und.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631541, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5376775785367507}} {"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 : nrtFfmBuilderFem.m |\n%| # | VERSION : 0.61 |\n%| _#_ | AUTHOR(S) : Matthieu Aussal |\n%| ( # ) | CREATION : 14.03.2019 |\n%| / 0 \\ | LAST MODIF : 05.09.2019 |\n%| ( === ) | SYNOPSIS : Non regression test for convolution using |\n%| `---' | arbitrary kenel integral galerkin formulation |\n%+========================================================================+\n\n% Cleaning\nclear all\nclose all\nclc\n\n% Gypsilab path\nrun('../../addpathGypsilab.m')\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% DEFINITIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\ndisp('~~~~~~~~~~~~~ DEFINITIONS ~~~~~~~~~~~~~')\n\n% Dimensions\nNx = 1e3\nNy = 2e3\n\n% Accuracy\ntol = 1e-3\n\n% Meshes\nXmsh = mshSphere(Nx,1);\nYmsh = mshCube(Ny,2*[1 1 1]);\nYmsh = Ymsh.bnd;\n\n% Domain\nXdom = dom(Xmsh,3);\nYdom = dom(Ymsh,3);\n\n% Finite element\nXfem = fem(Xmsh,'P1');\nYfem = fem(Ymsh,'P1');\n\n% Wave number or frequency (Hz)\nstp = Xmsh.stp;\nk = 5\n\n% Green kernel\ngreen = '[exp(ikr)/r]'\nGxy = @(X,Y) femGreenKernel(X,Y,green,k);\n\n% Charges\nV = (-1+2*rand(length(Yfem),1)) + (-1+2i*rand(length(Yfem),1));\n\n% Spatial representation of particles\nfigure\nplot(Xmsh,'b')\nhold on\nplot(Ymsh,'r')\nalpha(0.5)\naxis equal \n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FULL PRODUCT %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\ndisp('~~~~~~~~~~~~~ FULL PRODUCT ~~~~~~~~~~~~~')\n\n% Full Matrix\ntic\nM = integral(Xdom,Ydom,Xfem,Gxy,Yfem); \ntoc\n\n% Matrix-vector product\ntic\nref = M * V;\ntoc\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FFM PRODUCT %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\ndisp('~~~~~~~~~~~~~ FFM PRODUCT ~~~~~~~~~~~~~')\n\n% FFM\ntic\nMv = integral(Xdom,Ydom,Xfem,green,k,Yfem,tol); \ntoc\n\n% FFM Matrix-vector product\ntic\nsol = Mv * V;\ntoc\n\n% Error\nnorm(ref-sol)/norm(ref)\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/fastFreeMemory/nrtFfmBuilderFem.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220292, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.5376770245375102}} {"text": "function [y,Jyl,Jyr,ilocl,ilocr,evalcnt]=greedy2_cross(n, fun, tol, varargin)\n% Two-site greedy cross interpolation scheme.\n% [y,Jyl,Jyr,ilocl,ilocr]=greedy2_cross(n, fun, tol, varargin)\n% Tries to interpolate the tensor with mode sizes n specified by the\n% function fun up to the accuracy tol using the \"basic\" greedy restricted \n% cross interpolation algorithm in the TT format.\n% The method sequentially adds one pivot to each superblock in a forward\n% DMRG-type half-sweep (k=1,...,d).\n% \n% The input n should be a vector of mode sizes of length d,\n% fun = @(ind)fun(ind) is a sought function of index ind.\n% By default, ind is an array of d indices, and the function fun should\n% return one value of the corresponding tensor entry.\n% To speed up the computations, set the optional parameter 'vec' to true,\n% and provide the function which takes ind as an array of sizes M x d, and\n% returns an array of M values.\n%\n% In addition to the indexwise function, one may provide the value-wise\n% function of another tt_tensor (funcrs style) via optional parameters \n% 'aux', 'auxfun' (see below).\n% The resulting tensor is the sum y(ind)=fun(ind) + auxfun(aux(ind)).\n%\n% The first output parameter is the computed tt_tensor, the rest four\n% parameters return the pivot indices (left-global, right-global, left-local, right-local) for\n% testing purposes.\n%\n% Optional arguments are provided in the form\n% 'PropertyName1',PropertyValue1,'PropertyName2',PropertyValue2 and so on. \n% The list of option names and default values:\n% o nswp - maximal number of sweeps [20]\n% o tol_exit - stopping difference between consecutive iterations [tol]\n% o verb - verbosity level, 0-silent, 1-sweep info, 2-block info [1]\n% o vec - whether fun can accept and return vectorized values [false]\n% o aux - set of tt_tensors for auxiliary funcrs contribution []\n% o auxfun - an auxiliary function defined pointwise at the elements\n% of aux []\n% o 'locsearch' - an algorithm for the error pivoting in superblocks:\n% try a lottery of n*r random elements ('lot'), or\n% conduct two-dimensional maxvol ALS iteration ('als').\n% The first one uses less evaluations, but may be costly due to a\n% nonvectorized MATLAB loop ['lot']\n%\n% \n% This procedure implements Algorithm 2 from \n% D. Savostyanov, Quasioptimality of maximum-volume cross interpolation of tensors, Linear Algebra Applications 458, pp 217-244, 2014. \n% http://dx.doi.org/10.1016/j.laa.2014.06.006\n% Please cite this paper if your research benefits from the use of this code.\n% Development of the MATLAB version: S. Dolgov.\n% Please send feedback to: {dmitry.savostyanov,sergey.v.dolgov}@gmail.com\n%\n%---------------------------\n\nif (~isempty(varargin))\n v1 = varargin{1};\n if (isa(v1, 'cell'))\n varargin=v1;\n end;\nend;\nvars = varargin;\n\nnswp = 20;\ntol_exit = tol;\nverb = 1;\nvec = false;\naux = []; % Extra tt_tensors to pass into this cross\nauxfun = []; % the total function equals fun(ind)+auxfun(aux(ind)), since simple aux(ind) via tt_tensor/subsref suxx.\n% locsearch = 'als';\nlocsearch = 'lot';\ny0 = [];\n\ni = 1;\nwhile (i1) \n cry1 = reshape(cry1, ry(i), n(i)*ry(i+1));\n [v,ilocr{i}] = max(abs(cry1.'));\n ilocr{i} = ilocr{i}(:);\n mid_inv{i,1} = 1/cry1(:,ilocr{i});\n mid_inv{i,2} = 1;\n Jyr{i} = indexmerge((1:n(i))', Jyr{i+1});\n Jyr{i} = Jyr{i}(ilocr{i},:);\n \n if (~isempty(aux))\n for j=1:Raux\n phiauxr{i,j} = reshape(aux{i,j}, raux(i,j)*n(i), raux(i+1,j));\n phiauxr{i,j} = phiauxr{i,j}*phiauxr{i+1,j};\n phiauxr{i,j} = reshape(phiauxr{i,j}, raux(i,j), n(i)*ry(i+1));\n phiauxr{i,j} = phiauxr{i,j}(:, ilocr{i});\n end;\n end;\n end;\n \n y{i} = reshape(cry1, ry(i), n(i), ry(i+1));\nend;\nfor i=1:d\n J = indexmerge(Jyl{i}, (1:n(i))', Jyr{i+1});\n evalcnt = evalcnt + size(J,1);\n cry1 = autovecfun(fun, J, vec);\n if (~isempty(aux))\n craux = zeros(ry(i)*n(i)*ry(i+1), Raux);\n for j=1:Raux\n craux1 = reshape(aux{i,j}, raux(i,j), n(i)*raux(i+1,j));\n craux1 = phiauxl{i,j}*craux1;\n craux1 = reshape(craux1, ry(i)*n(i), raux(i+1,j));\n craux1 = craux1*phiauxr{i+1,j};\n craux(:,j) = reshape(craux1, ry(i)*n(i)*ry(i+1), 1);\n end;\n cry1 = cry1+auxfun(craux);\n end;\n \n if (inumel(cind1)*numel(cind2))=numel(cind1)*numel(cind2);\n tind(tind<1)=1;\n tind = unique(tind);\n testsz = size(tind,1);\n end;\n \n if (~isempty(aux))\n craux1 = cell(1,Raux);\n craux2 = cell(1,Raux);\n for j=1:Raux\n craux = reshape(aux{i,j}, raux(i,j), n(i)*raux(i+1,j));\n craux = phiauxl{i,j}*craux;\n craux1{j} = reshape(craux, ry(i)*n(i), raux(i+1,j));\n craux = reshape(aux{i+1,j}, raux(i+1,j)*n(i+1), raux(i+2,j));\n craux = craux*phiauxr{i+2,j};\n craux2{j} = reshape(craux, raux(i+1,j), n(i+1)*ry(i+2));\n end;\n end;\n \n % Check that we are not in the full rank case\n if (testsz>0)\n if (strcmp(locsearch, 'als'))\n % 2D ALS cross\n % Evaluate y at tind\n cry1 = reshape(y{i}, ry(i)*n(i), ry(i+1));\n cry2 = reshape(y{i+1}, ry(i+1), n(i+1)*ry(i+2));\n ys1 = cry1*mid_inv{i+1,1};\n ys1 = ys1(cind1,:);\n ys2 = mid_inv{i+1,2}*cry2;\n ys2 = ys2(:,cind2);\n % Full indices\n J1 = indexmerge(Jyl{i}, (1:n(i))');\n J1c = J1(cind1,:);\n J2 = indexmerge((1:n(i+1))', Jyr{i+2});\n J2c = J2(cind2,:);\n rz = 2;\n cre2 = randn(numel(cind2), rz);\n [cre2,rv]=qr(cre2,0);\n indr = maxvol2(cre2);\n Jr = J2c(indr,:);\n Ye2 = ys2(:,indr);\n \n J = indexmerge(J1c,Jr);\n evalcnt = evalcnt + size(J,1);\n cre1 = autovecfun(fun, J, vec);\n if (~isempty(aux))\n craux = zeros(numel(cind1)*numel(indr), Raux);\n for j=1:Raux\n craux(:,j) = reshape(craux1{j}(cind1,:)*craux2{j}(:,cind2(indr)), [], 1);\n end;\n craux = auxfun(craux);\n cre1 = cre1+craux;\n end;\n maxy = max(maxy, max(abs(cre1)));\n cre1 = reshape(cre1, numel(cind1), rz);\n cre1 = cre1-ys1*Ye2;\n [zmax1,imaxnew]=max(abs(cre1(:)));\n imaxnew = tt_ind2sub([numel(cind1), rz], imaxnew);\n imax1 = imaxnew(1);\n [cre1,rv]=qr(cre1,0);\n indl = maxvol2(cre1);\n Jl = J1c(indl,:);\n Ye1 = ys1(indl,:);\n \n J = indexmerge(Jl,J2c);\n evalcnt = evalcnt + size(J,1);\n cre2 = autovecfun(fun, J, vec);\n if (~isempty(aux))\n craux = zeros(numel(indl)*numel(cind2), Raux);\n for j=1:Raux \n craux(:,j) = reshape(craux1{j}(cind1(indl),:)*craux2{j}(:,cind2), [], 1);\n end;\n craux = auxfun(craux);\n cre2 = cre2+craux;\n end;\n maxy = max(maxy, max(abs(cre2)));\n cre2 = reshape(cre2, rz, numel(cind2));\n cre2 = cre2-Ye1*ys2;\n [zmax2,imaxnew]=max(abs(cre2(:)));\n imaxnew = tt_ind2sub([rz, numel(cind2)], imaxnew);\n imax2 = imaxnew(2);\n imax1 = cind1(imax1);\n imax2 = cind2(imax2);\n emax = max(zmax1,zmax2);\n else\n %%% % rn Lottery\n tind = tt_ind2sub([numel(cind1), numel(cind2)], tind);\n tind = [cind1(tind(:,1)), cind2(tind(:,2))];\n % Full indices\n J1 = indexmerge(Jyl{i}, (1:n(i))');\n J1c = J1(tind(:,1),:);\n J2 = indexmerge((1:n(i+1))', Jyr{i+2});\n J2c = J2(tind(:,2),:);\n J = [J1c,J2c];\n % Evaluate the function\n evalcnt = evalcnt + testsz;\n crt = autovecfun(fun, J, vec);\n if (~isempty(aux))\n craux = zeros(testsz, Raux);\n for k=1:Raux\n for j=1:testsz\n craux(j,k) = craux1{k}(tind(j,1),:)*craux2{k}(:,tind(j,2));\n end;\n end;\n crt = crt+auxfun(craux);\n end;\n maxy = max(maxy, max(abs(crt)));\n % Evaluate y at tind\n cry1 = reshape(y{i}, ry(i)*n(i), ry(i+1));\n cry2 = reshape(y{i+1}, ry(i+1), n(i+1)*ry(i+2));\n % Subtract the current approx.\n cry = zeros(testsz, 1);\n % Apply the inverse interp at the middle\n cre1 = cry1*mid_inv{i+1,1};\n cre2 = mid_inv{i+1,2}*cry2;\n for j=1:testsz\n cry(j) = cre1(tind(j,1),:)*cre2(:,tind(j,2));\n end;\n cre = crt-cry;\n % Take the max-err index to enrich\n [emax,imax2] = max(abs(cre));\n \n % All again: at (:,tind(imax,2)), run the error maximization\n J1c = J1(cind1,:);\n J = indexmerge(J1c, J2c(imax2,:));\n evalcnt = evalcnt + size(J,1);\n crt = autovecfun(fun, J, vec);\n if (~isempty(aux))\n craux = zeros(numel(cind1), Raux);\n for j=1:Raux\n craux(:,j) = craux1{j}(cind1,:)*craux2{j}(:,tind(imax2,2));\n end;\n crt = crt+auxfun(craux);\n end;\n maxy = max(maxy, max(abs(crt)));\n % Subtract the current approx.\n cry = cre1(cind1,:)*cre2(:,tind(imax2,2));\n cre = crt-cry;\n % Take the max-err index to enrich\n [emax,imax1] = max(abs(cre));\n imax1 = cind1(imax1);\n imax2 = tind(imax2,2);\n % imax1 samples from ry(i)*n(i)\n % imax2 samples from n(i+1)*ry(i+2)\n end;\n \n dx = emax/maxy;\n max_dx = max(max_dx,dx);\n if (verb>1)\n fprintf('=greedy_cross= i=%d, swp=%d, testsz=%d, emax=%3.3e, dx=%3.3e, cond=[%3.3e,%3.3e]\\n', i, swp, testsz, emax, dx, cond(mid_inv{i+1,1}), cond(mid_inv{i+1,2}));\n end;\n \n if (dx>tol)\n % Now evaluate new factors\n J1m = J1(imax1,:);\n J2m = J2(imax2,:);\n % Generate a full index = [Jl, (1:n)', Jr]\n % Jyl to lowest index n(i) to the middle one, Jyr to the senior index\n Jl = indexmerge(J1, J2m);\n Jr = indexmerge(J1m, J2);\n \n evalcnt = evalcnt + size(Jl,1);\n cre1 = autovecfun(fun, Jl, vec);\n if (~isempty(aux))\n craux = zeros(ry(i)*n(i), Raux);\n for j=1:Raux\n craux(:,j) = craux1{j}*craux2{j}(:,imax2);\n end;\n cre1 = cre1+auxfun(craux);\n end;\n \n evalcnt = evalcnt + size(Jr,1);\n cre2 = autovecfun(fun, Jr, vec);\n if (~isempty(aux))\n craux = zeros(n(i+1)*ry(i+2), Raux);\n for j=1:Raux\n craux(:,j) = craux1{j}(imax1,:)*craux2{j};\n end;\n cre2 = cre2+auxfun(craux);\n end; \n \n cre1 = reshape(cre1, ry(i)*n(i), 1);\n cre2 = reshape(cre2, 1, n(i+1)*ry(i+2));\n \n % Expand blocks\n y{i} = [cry1, cre1];\n y{i+1} = [cry2; cre2];\n ry(i+1)=ry(i+1)+1;\n % ilocl{i+2} is smashed now, since ry(i+1) changed. Recover...\n if (i0)\n if (exist('xtru'))\n ytest=formtensor(y,mid_inv,d,ry,n);\n fprintf('=greedy_cross= swp=%d, max_dx=%3.3e, max_rank=%d, cum#evals=%d, err_tru=%3.3e\\n', swp, max_dx, max(ry), evalcnt, norm(ytest-xtru)/norm(xtru));\n else\n fprintf('=greedy_cross= swp=%d, max_dx=%3.3e, max_rank=%d, cum#evals=%d\\n', swp, max_dx, max(ry), evalcnt);\n end;\n end;\n \n if (max_dx M x 1\nelse\n % They can't -- run a loop manually\n sz = size(J,1);\n y = zeros(sz, 1);\n for j=1:sz\n y(j) = fun(J(j,:));\n end;\nend;\nend\n\n\nfunction [J]=indexmerge(varargin)\n% Merges two or three indices in the little-endian manner\nsz1 = max(size(varargin{1},1),1);\nsz2 = max(size(varargin{2},1),1);\nsz3 = 1;\nif (nargin>2) % Currently allows only 3\n sz3 = max(size(varargin{3}, 1), 1);\nend;\n% J1 goes to the fastest index, just copy it\nJ1 = repmat(varargin{1}, sz2*sz3, 1);\n% J2 goes to the middle\nJ2 = reshape(varargin{2}, 1, []);\nJ2 = repmat(J2, sz1, 1); % now sz1 ones will be the fastest\nJ2 = reshape(J2, sz1*sz2, []);\nJ2 = repmat(J2, sz3, 1);\nJ = [J1,J2];\nif (nargin>2)\n % J3 goes to the slowest\n J3 = reshape(varargin{3}, 1, []);\n J3 = repmat(J3, sz1*sz2, 1); % now sz1 ones will be the fastest\n J3 = reshape(J3, sz1*sz2*sz3, []);\n J = [J,J3];\nend;\nend\n\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/cross/greedy2_cross.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7549149868676284, "lm_q2_score": 0.7122321964553657, "lm_q1q2_score": 0.5376747592338045}} {"text": "function [rep_motion motion_vector] = fastMV(im1, im2, w)\n% Author: Arash Jalalian\n% E-mail: arash.jalalian@gmail.com\n% Arguments: [rep_motion motion_vector] = fastMV(im1, im2, w)\n% This is the simplified block matching algorithm(BMA) which is proposed by\n% L. Hao. I've simplified this algorithm for use it in a real-time problem.\n% We have a dynamic search pattern during finding the motion vector. \n% 1. check with big diamond.\n% 2. check with one of the hexagon subject to previous results.\n% 3. check with small diamond.\n% 'im1' is base frame of a video and 'im2' is the second frame. and 'w' is \n% the window size. 'rep_motion' is the representative motion vector and\n% 'motion_vector' declare motion vectors for each block of image.\n% Example:\n% im1 = imread('frame001.jpg');\n% im2 = imread('frame002.jpg');\n% w = 16;\n% [rep_m m_vector] = fastMV(im1, im2, w);\n\n% clear all\n% close all\n% clc\n% im1 = imread('img_1057.pgm');\n% im2 = imread('img_1058.pgm');\n% % dis = 2;\n% w = 8;\n\n\n% initialization\n[r1 c1] = size(im1);\n[r2 c2] = size(im2);\nif r1 ~= r2 || c1 ~= c2 \n error('The images must be in a same size')\nend\n\npat.org = [0; 0];\npat.diam1 = [2 0 -2 0; 0 2 0 -2];%big diamond\npat.diam2 = [1 0 -1 0; 0 1 0 -1];%small diamond\npat.hexver = [2 1 -1 -2 -1 1; 0 2 2 0 -2 -2];\npat.hexhor = [2 0 -2 -2 0 2 ;1 2 1 -1 -2 -1];\n\nr_time = int16(floor(r1 ./ w));\nc_time = int16(floor(c1 ./ w));\n\n% for preventing index exceeding from end of image. 4 is the maximum\n% Magnitude of the motion vector\nif mod(r1, w) < 4 \n r_time = r_time -1;\nend\nif mod(c1, w) < 4\n c_time = c_time -1;\nend\nslice1 = cell(r_time, c_time);\nslice2 = cell(r_time, c_time);\nmotion_vector = cell(r_time, c_time);\n\n% creating slices with cell array of slices\nfor i = 1:r_time\n for j = 1:c_time\n slice1{i, j} = im1(((i-1) * w) + 1:i * w, ((j-1) * w) + 1:j * w);\n slice2{i, j} = im2(((i-1) * w) + 1:i * w, ((j-1) * w) + 1:j * w);\n end\nend\n\n% first step checking with 4 points of big diamond and the origin\nmad_org = zeros(r_time, c_time);\nmin_mad = zeros(r_time, c_time);\nidx_min_mad = zeros(r_time, c_time);\nfor i = 1:r_time\n for j = 1:c_time \n s_h_r = ((i-1) * w) + 1;%slice head row\n s_h_c = ((j-1) * w) + 1;%slice head column\n diff.org{i, j} = abs(slice2{i, j} - slice1{i, j});\n [r_diam c_diam] = size(pat.diam1);\n for k = 1:c_diam\n if s_h_r + pat.diam1(1, k) > 0 && s_h_c + pat.diam1(2, k) > 0\n diff.diam1{1, k} = abs(slice1{i, j}- im2(s_h_r + pat.diam1(1, k):...\n i *w + pat.diam1(1, k),...\n s_h_c + pat.diam1(2, k):...\n j * w + pat.diam1(2, k)));\n % calculating MAD = Mean Absolute Difference\n diff.diam1{2, k} = sum(sum(diff.diam1{1,k})) / (w ^ 2);% insert each MAD below each Pat\n mad(k) = sum(sum(diff.diam1{1,k})) / (w ^ 2);\n else\n diff.diam1{1, k} = 9999999999999;\n diff.diam1{2, k} = 9999999999999;\n mad(k) = sum(sum(diff.diam1{1,k})) / (w ^ 2);\n end\n end\n % calculating minimum of mad in 4 pat and the origin and inserting\n % them into a min_mad(i, j). where i, j decler the position of the\n % slice in the image\n mad_org(i , j) = sum(sum(diff.org{i,j})) / (w ^ 2);\n mad = [mad mad_org(i, j)];\n [min_mad(i, j) idx_min_mad(i, j)] = min(mad);\n clear mad\n \n end\nend \n% if the idx_min_mad == 5 it means that the origin has the minimum value of\n% mad (between 4 big diamond points and the origin the orogin has the\n% minimum value) otherwise the index in idx_min_mad shows the pat index that\n% has the min mad value.\nidx_min_mad2 = zeros(r_time, c_time);\nmin_mad2 = zeros(r_time, c_time);\nfor i = 1:r_time\n for j = 1:c_time\n clear mad\n if idx_min_mad(i, j) == 5\n % it means this point didn't moved and it's better to do not use\n % any motion vectors so we must put [0; 0] for these points as a\n % motion vector.accourding to the paper for any slices that \n % idx_min_mad(i, j) ==5 we must use anothe four points as new\n % pat and check the slices with these i and j for mad. and the\n % final solution for these slices is these mad. here we must\n % use pat.diam2 as new patterns and repeat thise process again.\n s_h_r = ((i-1) * w) + 1;%slice head row\n s_h_c = ((j-1) * w) + 1;%slice head column\n% diff.org{i, j} = abs(slice2{i, j} - slice1{i, j});\n [r_diam c_diam] = size(pat.diam1);\n for k = 1:c_diam\n if s_h_r + pat.diam2(1, k) > 0 && s_h_c + pat.diam2(2, k) > 0\n diff.diam2{1, k} = abs(slice1{i, j}- im2(s_h_r + pat.diam2(1, k):...\n i *w + pat.diam2(1, k),...\n s_h_c + pat.diam2(2, k):...\n j * w + pat.diam2(2, k)));\n % calculating MAD = Mean Absolute Diffrence\n diff.diam2{2, k} = sum(sum(diff.diam2{1,k})) / (w ^ 2);% insert each MAD below each Pat\n mad(k) = sum(sum(diff.diam2{1,k})) / (w ^ 2);\n else\n diff.diam2{1, k} = 9999999999999;\n diff.diam2{2, k} = 9999999999999;\n mad(k) = sum(sum(diff.diam2{1,k})) / (w ^ 2);\n end\n end\n % calculating minimum of mad in 4 pat and the origin and inserting\n % them into a min_mad(i, j). where i, j decler the position of the\n % slice in the image\n% mad_org(i , j) = sum(sum(diff.org{i,j})) / (w ^ 2);\n% mad = [mad mad_org(i, j)];\n [min_mad2(i, j) idx_min_mad2(i, j)] = min(mad);\n\n end\n end\nend\nfor i = 1:r_time\n for j = 1:c_time\n if idx_min_mad2(i, j) ~= 0\n motion_vector{i , j} = pat.diam2(:, idx_min_mad2(i, j));\n end\n end\nend\n\n% other points that their minimum mads idx ~= 5. it means that these slices\n% are closer to farder slices.\nidx_min_mad3 = zeros(r_time, c_time);\nmin_mad3 = zeros(r_time, c_time);\nfor i = 1:r_time\n for j = 1:c_time\n clear mad\n if idx_min_mad(i, j) ~= 5\n s_h_r = ((i-1) * w) + 1;%slice head row\n s_h_c = ((j-1) * w) + 1;%slice head column\n% diff.org{i, j} = abs(slice2{i, j} - slice1{i, j});\n [r_hex c_hex] = size(pat.hexhor);\n for k = 1:c_hex\n if s_h_r + pat.hexhor(1, k) > 0 && s_h_c + pat.hexhor(2, k) > 0 && (idx_min_mad(i, j) == 1 || idx_min_mad(i, j) == 3)\n diff.hex{1, k} = abs(slice1{i, j}- im2(s_h_r + pat.hexhor(1, k):...\n i *w + pat.hexhor(1, k),...\n s_h_c + pat.hexhor(2, k):...\n j * w + pat.hexhor(2, k)));\n % calculating MAD = Mean Absolute Diffrence\n diff.hex{2, k} = sum(sum(diff.hex{1,k})) / (w ^ 2);% insert each MAD below each Pat\n mad(k) = sum(sum(diff.hex{1,k})) / (w ^ 2);\n elseif s_h_r + pat.hexver(1, k) > 0 && s_h_c + pat.hexver(2, k) > 0 && (idx_min_mad(i, j) == 2 || idx_min_mad(i, j) == 4)\n diff.hex{1, k} = abs(slice1{i, j}- im2(s_h_r + pat.hexver(1, k):...\n i *w + pat.hexver(1, k),...\n s_h_c + pat.hexver(2, k):...\n j * w + pat.hexver(2, k)));\n % calculating MAD = Mean Absolute Diffrence\n diff.hex{2, k} = sum(sum(diff.hex{1,k})) / (w ^ 2);% insert each MAD below each Pat\n mad(k) = sum(sum(diff.hex{1,k})) / (w ^ 2);\n else\n diff.hex{1, k} = 9999999999999;\n diff.hex{2, k} = 9999999999999;\n mad(k) = sum(sum(diff.hex{1,k})) / (w ^ 2);\n end\n end\n % calculating minimum of mad in 4 pat and inserting\n % them into a min_mad(i, j). where i, j decler the position of the\n % slice in the image\n% mad_org(i , j) = sum(sum(diff.org{i,j})) / (w ^ 2);\n% mad = [mad mad_org(i, j)];\n [min_mad3(i, j) idx_min_mad3(i, j)] = min(mad);\n\n end\n end\nend\n% org_mov declare the movement vector for new pattern origins.\norg_mov = cell(r_time, c_time);\nfor i = 1:r_time\n for j = 1:c_time\n if idx_min_mad3(i, j) ~= 0 && (idx_min_mad(i, j) == 1 || idx_min_mad(i, j) == 3)\n org_mov{i , j} = pat.hexhor(:, idx_min_mad3(i, j));\n elseif idx_min_mad3(i, j) ~= 0 && (idx_min_mad(i, j) == 2 || idx_min_mad(i, j) == 4)\n org_mov{i , j} = pat.hexver(:, idx_min_mad3(i, j));\n end\n end\nend\n% now we must go the theird step. the minimum mad point found in the\n% previous search step is repositioned as the center point to form a new\n% hexagon nad only three new non overlaped points will be checked as\n% candidates each time. so we must define new pattern. this time our\n% patterns must have a dynamic behavior. and also these pattern must be\n% created based on the old pat.hexver and pat.hexhor\n[r_mov c_mov] = size(org_mov);\nidx_min_mad4 = zeros(r_mov, c_mov);\nmin_mad4 = zeros(r_mov, c_mov);\nfor i = 1:r_mov\n for j = 1:c_mov\n clear mad\n nu = sparse(org_mov{i, j});\n [r_nu c_nu] = size(nu);\n if r_nu ~= 0 || c_nu ~= 0\n for z = 1:c_hex\n pat.hexver_new(:, z) = pat.hexver(:, z) + org_mov{i, j};\n pat.hexhor_new(:, z) = pat.hexhor(:, z) + org_mov{i, j};\n end\n s_h_r = ((i-1) * w) + 1;%slice head row\n s_h_c = ((j-1) * w) + 1;%slice head column\n% diff.org{i, j} = abs(slice2{i, j} - slice1{i, j});\n [r_hex c_hex] = size(pat.hexhor_new);\n for k = 1:c_hex\n% clear mad\n if s_h_r + pat.hexhor_new(1, k) > 0 && s_h_c + pat.hexhor_new(2, k) > 0 && (idx_min_mad(i, j) == 1 || idx_min_mad(i, j) == 3)\n diff.hex{1, k} = abs(slice1{i, j}- im2(s_h_r + pat.hexhor_new(1, k):...\n i *w + pat.hexhor_new(1, k),...\n s_h_c + pat.hexhor_new(2, k):...\n j * w + pat.hexhor_new(2, k)));\n % calculating MAD = Mean Absolute Diffrence\n diff.hex{2, k} = sum(sum(diff.hex{1,k})) / (w ^ 2);% insert each MAD below each Pat\n mad(k) = sum(sum(diff.hex{1,k})) / (w ^ 2);\n elseif s_h_r + pat.hexver_new(1, k) > 0 && s_h_c + pat.hexver_new(2, k) > 0 && (idx_min_mad(i, j) == 2 || idx_min_mad(i, j) == 4)\n diff.hex{1, k} = abs(slice1{i, j}- im2(s_h_r + pat.hexver_new(1, k):...\n i *w + pat.hexver_new(1, k),...\n s_h_c + pat.hexver_new(2, k):...\n j * w + pat.hexver_new(2, k)));\n % calculating MAD = Mean Absolute Diffrence\n diff.hex{2, k} = sum(sum(diff.hex{1,k})) / (w ^ 2);% insert each MAD below each Pat\n mad(k) = sum(sum(diff.hex{1,k})) / (w ^ 2);\n else\n diff.hex{1, k} = 9999999999999;\n diff.hex{2, k} = 9999999999999;\n mad(k) = sum(sum(diff.hex{1,k})) / (w ^ 2);\n end\n end\n % calculating minimum of mad in 4 pat and inserting\n % them into a min_mad(i, j). where i, j declare the position of the\n % slice in the image\n% mad_org(i , j) = sum(sum(diff.org{i,j})) / (w ^ 2);\n mad = [mad mad_org(i, j)];\n [min_mad4(i, j) idx_min_mad4(i, j)] = min(mad);\n% clear mad\n end\n end\nend\n% org_mov declare the movement vector for new pattern origins.\n% final motion vector calculation\nfor i = 1:r_mov\n for j = 1:c_mov\n if idx_min_mad4(i, j) == 7 \n motion_vector{i, j} = pat.org;\n elseif idx_min_mad4(i, j) ~= 0 && (idx_min_mad(i, j) == 1 || idx_min_mad(i, j) == 3)\n motion_vector{i , j} = pat.hexhor_new(:, idx_min_mad4(i, j));\n elseif idx_min_mad4(i, j) ~= 0 && (idx_min_mad(i, j) == 2 || idx_min_mad(i, j) == 4)\n motion_vector{i , j} = pat.hexver_new(:, idx_min_mad3(i, j));\n end\n end\nend\n\n% now we want to find rep_motion vector\nmotion_vectors = cat(2, motion_vector{:});\nmost_motion_vector = zeros(1, r_time .* c_time);\nclear temp\ntemp = motion_vectors;\nfor i=1:r_time .* c_time\n my_count = 0;\n element(:, 1) = temp(:, i);\n for k = i+1:r_time .* c_time\n if temp(:, k) == element(:, 1)\n my_count = my_count+1;\n% temp(:, k) = [];\n end\n end\n most_motion_vector(i) = my_count;\nend\n[value, idx] = max(most_motion_vector);\nrep_motion= motion_vectors(:, idx);", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/15767-fast-motion-detectionbugs-fixed/fastMV.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.6893056231680121, "lm_q1q2_score": 0.5376534921762822}} {"text": "function y = vl_nnloss(x,c,varargin)\n%VL_NNLOSS CNN categorical or attribute loss.\n% Y = VL_NNLOSS(X, C) computes the loss incurred by the prediction\n% scores X given the categorical labels C.\n%\n% The prediction scores X are organised as a field of prediction\n% vectors, represented by a H x W x D x N array. The first two\n% dimensions, H and W, are spatial and correspond to the height and\n% width of the field; the third dimension D is the number of\n% categories or classes; finally, the dimension N is the number of\n% data items (images) packed in the array.\n%\n% While often one has H = W = 1, the case W, H > 1 is useful in\n% dense labelling problems such as image segmentation. In the latter\n% case, the loss is summed across pixels (contributions can be\n% weighed using the `InstanceWeights` option described below).\n%\n% The array C contains the categorical labels. In the simplest case,\n% C is an array of integers in the range [1, D] with N elements\n% specifying one label for each of the N images. If H, W > 1, the\n% same label is implicitly applied to all spatial locations.\n%\n% In the second form, C has dimension H x W x 1 x N and specifies a\n% categorical label for each spatial location.\n%\n% In the third form, C has dimension H x W x D x N and specifies\n% attributes rather than categories. Here elements in C are either\n% +1 or -1 and C, where +1 denotes that an attribute is present and\n% -1 that it is not. The key difference is that multiple attributes\n% can be active at the same time, while categories are mutually\n% exclusive. By default, the loss is *summed* across attributes\n% (unless otherwise specified using the `InstanceWeights` option\n% described below).\n%\n% DZDX = VL_NNLOSS(X, C, DZDY) computes the derivative of the block\n% projected onto the output derivative DZDY. DZDX and DZDY have the\n% same dimensions as X and Y respectively.\n%\n% VL_NNLOSS() supports several loss functions, which can be selected\n% by using the option `type` described below. When each scalar c in\n% C is interpreted as a categorical label (first two forms above),\n% the following losses can be used:\n%\n% Classification error:: `classerror`\n% L(X,c) = (argmax_q X(q) ~= c). Note that the classification\n% error derivative is flat; therefore this loss is useful for\n% assessment, but not for training a model.\n%\n% Top-K classification error:: `topkerror`\n% L(X,c) = (rank X(c) in X <= K). The top rank is the one with\n% highest score. For K=1, this is the same as the\n% classification error. K is controlled by the `topK` option.\n%\n% Log loss:: `log`\n% L(X,c) = - log(X(c)). This function assumes that X(c) is the\n% predicted probability of class c (hence the vector X must be non\n% negative and sum to one).\n%\n% Softmax log loss (multinomial logistic loss):: `softmaxlog`\n% L(X,c) = - log(P(c)) where P(c) = exp(X(c)) / sum_q exp(X(q)).\n% This is the same as the `log` loss, but renormalizes the\n% predictions using the softmax function.\n%\n% Multiclass hinge loss:: `mhinge`\n% L(X,c) = max{0, 1 - X(c)}. This function assumes that X(c) is\n% the score margin for class c against the other classes. See\n% also the `mmhinge` loss below.\n%\n% Multiclass structured hinge loss:: `mshinge`\n% L(X,c) = max{0, 1 - M(c)} where M(c) = X(c) - max_{q ~= c}\n% X(q). This is the same as the `mhinge` loss, but computes the\n% margin between the prediction scores first. This is also known\n% the Crammer-Singer loss, an example of a structured prediction\n% loss.\n%\n% When C is a vector of binary attribures c in (+1,-1), each scalar\n% prediction score x is interpreted as voting for the presence or\n% absence of a particular attribute. The following losses can be\n% used:\n%\n% Binary classification error:: `binaryerror`\n% L(x,c) = (sign(x - t) ~= c). t is a threshold that can be\n% specified using the `threshold` option and defaults to zero. If\n% x is a probability, it should be set to 0.5.\n%\n% Binary log loss:: `binarylog`\n% L(x,c) = - log(c(x-0.5) + 0.5). x is assumed to be the\n% probability that the attribute is active (c=+1). Hence x must be\n% a number in the range [0,1]. This is the binary version of the\n% `log` loss.\n%\n% Logistic log loss:: `logistic`\n% L(x,c) = log(1 + exp(- cx)). This is the same as the `binarylog`\n% loss, but implicitly normalizes the score x into a probability\n% using the logistic (sigmoid) function: p = sigmoid(x) = 1 / (1 +\n% exp(-x)). This is also equivalent to `softmaxlog` loss where\n% class c=+1 is assigned score x and class c=-1 is assigned score\n% 0.\n%\n% Hinge loss:: `hinge`\n% L(x,c) = max{0, 1 - cx}. This is the standard hinge loss for\n% binary classification. This is equivalent to the `mshinge` loss\n% if class c=+1 is assigned score x and class c=-1 is assigned\n% score 0.\n%\n% VL_NNLOSS(...,'OPT', VALUE, ...) supports these additionals\n% options:\n%\n% InstanceWeights:: []\n% Allows to weight the loss as L'(x,c) = WGT L(x,c), where WGT is\n% a per-instance weight extracted from the array\n% `InstanceWeights`. For categorical losses, this is either a H x\n% W x 1 or a H x W x 1 x N array. For attribute losses, this is\n% either a H x W x D or a H x W x D x N array.\n%\n% TopK:: 5\n% Top-K value for the top-K error. Note that K should not\n% exceed the number of labels.\n%\n% See also: VL_NNSOFTMAX().\n\n% Copyright (C) 2014-15 Andrea Vedaldi.\n% Copyright (C) 2016 Karel Lenc.\n% All rights reserved.\n%\n% This file is part of the VLFeat library and is made available under\n% the terms of the BSD license (see the COPYING file).\n\nif ~isempty(varargin) && ~ischar(varargin{1}) % passed in dzdy\n dzdy = varargin{1} ;\n varargin(1) = [] ;\nelse\n dzdy = [] ;\nend\n\nopts.instanceWeights = [] ;\nopts.classWeights = [] ;\nopts.threshold = 0 ;\nopts.loss = 'softmaxlog' ;\nopts.topK = 5 ;\nopts = vl_argparse(opts, varargin, 'nonrecursive') ;\n\ninputSize = [size(x,1) size(x,2) size(x,3) size(x,4)] ;\n\n% Form 1: C has one label per image. In this case, get C in form 2 or\n% form 3.\nc = gather(c) ;\nif numel(c) == inputSize(4)\n c = reshape(c, [1 1 1 inputSize(4)]) ;\n c = repmat(c, inputSize(1:2)) ;\nend\n\nhasIgnoreLabel = any(c(:) == 0);\n\n% --------------------------------------------------------------------\n% Spatial weighting\n% --------------------------------------------------------------------\n\n% work around a bug in MATLAB, where native cast() would slow\n% progressively\nif isa(x, 'gpuArray')\n switch classUnderlying(x) ;\n case 'single', cast = @(z) single(z) ;\n case 'double', cast = @(z) double(z) ;\n end\nelse\n switch class(x)\n case 'single', cast = @(z) single(z) ;\n case 'double', cast = @(z) double(z) ;\n end\nend\n\nlabelSize = [size(c,1) size(c,2) size(c,3) size(c,4)] ;\nassert(isequal(labelSize(1:2), inputSize(1:2))) ;\nassert(labelSize(4) == inputSize(4)) ;\ninstanceWeights = [] ;\nswitch lower(opts.loss)\n case {'classerror', 'topkerror', 'log', 'softmaxlog', 'mhinge', 'mshinge'}\n % there must be one categorical label per prediction vector\n assert(labelSize(3) == 1) ;\n\n if hasIgnoreLabel\n % null labels denote instances that should be skipped\n instanceWeights = cast(c(:,:,1,:) ~= 0) ;\n end\n\n case {'binaryerror', 'binarylog', 'logistic', 'hinge'}\n\n % there must be one categorical label per prediction scalar\n assert(labelSize(3) == inputSize(3)) ;\n\n if hasIgnoreLabel\n % null labels denote instances that should be skipped\n instanceWeights = cast(c ~= 0) ;\n end\n\n otherwise\n error('Unknown loss ''%s''.', opts.loss) ;\nend\n\nif ~isempty(opts.instanceWeights)\n % important: this code needs to broadcast opts.instanceWeights to\n % an array of the same size as c\n if isempty(instanceWeights)\n instanceWeights = bsxfun(@times, onesLike(c), opts.instanceWeights) ;\n else\n instanceWeights = bsxfun(@times, instanceWeights, opts.instanceWeights);\n end\nend\n\n% --------------------------------------------------------------------\n% Do the work\n% --------------------------------------------------------------------\n\nswitch lower(opts.loss)\n case {'log', 'softmaxlog', 'mhinge', 'mshinge'}\n % from category labels to indexes\n numPixelsPerImage = prod(inputSize(1:2)) ;\n numPixels = numPixelsPerImage * inputSize(4) ;\n imageVolume = numPixelsPerImage * inputSize(3) ;\n\n n = reshape(0:numPixels-1,labelSize) ;\n offset = 1 + mod(n, numPixelsPerImage) + ...\n imageVolume * fix(n / numPixelsPerImage) ;\n ci = offset + numPixelsPerImage * max(c - 1,0) ;\nend\n\nif nargin <= 2 || isempty(dzdy)\n switch lower(opts.loss)\n case 'classerror'\n [~,chat] = max(x,[],3) ;\n t = cast(c ~= chat) ;\n case 'topkerror'\n [~,predictions] = sort(x,3,'descend') ;\n t = 1 - sum(bsxfun(@eq, c, predictions(:,:,1:opts.topK,:)), 3) ;\n case 'log'\n t = - log(x(ci)) ;\n case 'softmaxlog'\n Xmax = max(x,[],3) ;\n ex = exp(bsxfun(@minus, x, Xmax)) ;\n t = Xmax + log(sum(ex,3)) - x(ci) ;\n case 'mhinge'\n t = max(0, 1 - x(ci)) ;\n case 'mshinge'\n Q = x ;\n Q(ci) = -inf ;\n t = max(0, 1 - x(ci) + max(Q,[],3)) ;\n case 'binaryerror'\n t = cast(sign(x - opts.threshold) ~= c) ;\n case 'binarylog'\n t = -log(c.*(x-0.5) + 0.5) ;\n case 'logistic'\n %t = log(1 + exp(-c.*X)) ;\n a = -c.*x ;\n b = max(0, a) ;\n t = b + log(exp(-b) + exp(a-b)) ;\n case 'hinge'\n t = max(0, 1 - c.*x) ;\n end\n if ~isempty(instanceWeights)\n y = instanceWeights(:)' * t(:) ;\n else\n y = sum(t(:));\n end\nelse\n if ~isempty(instanceWeights)\n dzdy = dzdy * instanceWeights ;\n end\n switch lower(opts.loss)\n case {'classerror', 'topkerror'}\n y = zerosLike(x) ;\n case 'log'\n y = zerosLike(x) ;\n y(ci) = - dzdy ./ max(x(ci), 1e-8) ;\n case 'softmaxlog'\n Xmax = max(x,[],3) ;\n ex = exp(bsxfun(@minus, x, Xmax)) ;\n y = bsxfun(@rdivide, ex, sum(ex,3)) ;\n y(ci) = y(ci) - 1 ;\n y = bsxfun(@times, dzdy, y) ;\n case 'mhinge'\n y = zerosLike(x) ;\n y(ci) = - dzdy .* (x(ci) < 1) ;\n case 'mshinge'\n Q = x ;\n Q(ci) = -inf ;\n [~, q] = max(Q,[],3) ;\n qi = offset + numPixelsPerImage * (q - 1) ;\n W = dzdy .* (x(ci) - x(qi) < 1) ;\n y = zerosLike(x) ;\n y(ci) = - W ;\n y(qi) = + W ;\n case 'binaryerror'\n y = zerosLike(x) ;\n case 'binarylog'\n y = - dzdy ./ (x + (c-1)*0.5) ;\n case 'logistic'\n % t = exp(-Y.*X) / (1 + exp(-Y.*X)) .* (-Y)\n % t = 1 / (1 + exp(Y.*X)) .* (-Y)\n y = - dzdy .* c ./ (1 + exp(c.*x)) ;\n case 'hinge'\n y = - dzdy .* c .* (c.*x < 1) ;\n end\nend\n\n% --------------------------------------------------------------------\nfunction y = zerosLike(x)\n% --------------------------------------------------------------------\nif isa(x,'gpuArray')\n y = gpuArray.zeros(size(x),classUnderlying(x)) ;\nelse\n y = zeros(size(x),'like',x) ;\nend\n\n% --------------------------------------------------------------------\nfunction y = onesLike(x)\n% --------------------------------------------------------------------\nif isa(x,'gpuArray')\n y = gpuArray.ones(size(x),classUnderlying(x)) ;\nelse\n y = ones(size(x),'like',x) ;\nend\n", "meta": {"author": "phoenix104104", "repo": "LapSRN", "sha": "95154bba82a3aab9bdaec8e0eedd4187babc5ed2", "save_path": "github-repos/MATLAB/phoenix104104-LapSRN", "path": "github-repos/MATLAB/phoenix104104-LapSRN/LapSRN-95154bba82a3aab9bdaec8e0eedd4187babc5ed2/matconvnet/matlab/vl_nnloss.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928900257127, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.5376534851257927}} {"text": "function cae = caenumgradcheck(cae, x, y)\n epsilon = 1e-4;\n er = 1e-6;\n disp('performing numerical gradient checking...')\n for i = 1 : numel(cae.o)\n p_cae = cae; p_cae.c{i} = p_cae.c{i} + epsilon;\n m_cae = cae; m_cae.c{i} = m_cae.c{i} - epsilon;\n\n [m_cae, p_cae] = caerun(m_cae, p_cae, x, y);\n d = (p_cae.L - m_cae.L) / (2 * epsilon);\n\n e = abs(d - cae.dc{i});\n if e > er\n disp('OUTPUT BIAS numerical gradient checking failed');\n disp(e);\n disp(d / cae.dc{i});\n keyboard\n end\n end\n\n for a = 1 : numel(cae.a)\n\n p_cae = cae; p_cae.b{a} = p_cae.b{a} + epsilon;\n m_cae = cae; m_cae.b{a} = m_cae.b{a} - epsilon;\n\n [m_cae, p_cae] = caerun(m_cae, p_cae, x, y);\n d = (p_cae.L - m_cae.L) / (2 * epsilon);\n% cae.dok{i}{a}(u) = d;\n e = abs(d - cae.db{a});\n if e > er\n disp('BIAS numerical gradient checking failed');\n disp(e);\n disp(d / cae.db{a});\n keyboard\n end\n\n for i = 1 : numel(cae.o)\n for u = 1 : numel(cae.ok{i}{a})\n p_cae = cae; p_cae.ok{i}{a}(u) = p_cae.ok{i}{a}(u) + epsilon;\n m_cae = cae; m_cae.ok{i}{a}(u) = m_cae.ok{i}{a}(u) - epsilon;\n\n [m_cae, p_cae] = caerun(m_cae, p_cae, x, y);\n d = (p_cae.L - m_cae.L) / (2 * epsilon);\n% cae.dok{i}{a}(u) = d;\n e = abs(d - cae.dok{i}{a}(u));\n if e > er\n disp('OUTPUT KERNEL numerical gradient checking failed');\n disp(e);\n disp(d / cae.dok{i}{a}(u));\n% keyboard\n end\n end\n end\n\n for i = 1 : numel(cae.i)\n for u = 1 : numel(cae.ik{i}{a})\n p_cae = cae; \n m_cae = cae;\n p_cae.ik{i}{a}(u) = p_cae.ik{i}{a}(u) + epsilon;\n m_cae.ik{i}{a}(u) = m_cae.ik{i}{a}(u) - epsilon;\n [m_cae, p_cae] = caerun(m_cae, p_cae, x, y);\n d = (p_cae.L - m_cae.L) / (2 * epsilon);\n% cae.dik{i}{a}(u) = d;\n e = abs(d - cae.dik{i}{a}(u));\n if e > er\n disp('INPUT KERNEL numerical gradient checking failed');\n disp(e);\n disp(d / cae.dik{i}{a}(u));\n end\n end\n end\n end\n\n disp('done')\n\nend\n\nfunction [m_cae, p_cae] = caerun(m_cae, p_cae, x, y)\n m_cae = caeup(m_cae, x); m_cae = caedown(m_cae); m_cae = caebp(m_cae, y);\n p_cae = caeup(p_cae, x); p_cae = caedown(p_cae); p_cae = caebp(p_cae, y);\nend\n\n%function checknumgrad(cae,what,x,y)\n% epsilon = 1e-4;\n% er = 1e-9;\n%\n% for i = 1 : numel(eval(what))\n% if iscell(eval(['cae.' what]))\n% checknumgrad(cae,[what '{' num2str(i) '}'], x, y)\n% else\n% p_cae = cae;\n% m_cae = cae;\n% eval(['p_cae.' what '(' num2str(i) ')']) = eval([what '(' num2str(i) ')']) + epsilon;\n% eval(['m_cae.' what '(' num2str(i) ')']) = eval([what '(' num2str(i) ')']) - epsilon;\n%\n% m_cae = caeff(m_cae, x); m_cae = caedown(m_cae); m_cae = caebp(m_cae, y);\n% p_cae = caeff(p_cae, x); p_cae = caedown(p_cae); p_cae = caebp(p_cae, y);\n%\n% d = (p_cae.L - m_cae.L) / (2 * epsilon);\n% e = abs(d - eval(['cae.d' what '(' num2str(i) ')']));\n% if e > er\n% error('numerical gradient checking failed');\n% end\n% end\n% end\n%\n% end\n", "meta": {"author": "rasmusbergpalm", "repo": "DeepLearnToolbox", "sha": "5df2801f2196a2afddb7a87f800e63e153c34995", "save_path": "github-repos/MATLAB/rasmusbergpalm-DeepLearnToolbox", "path": "github-repos/MATLAB/rasmusbergpalm-DeepLearnToolbox/DeepLearnToolbox-5df2801f2196a2afddb7a87f800e63e153c34995/CAE/caenumgradcheck.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.6893056104028797, "lm_q1q2_score": 0.5376534822195697}} {"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 [yc,dy,para] = getTrafoFromInstationaryVelocityRK4(vc,yc,varargin)\n%\n% compute transformation yc by integrating velocity field in time using a\n% Runge-Kutta 4 method with fixed time steps. Velocity is time dependent\n% here and assumed to be nodal in time. For stationary velocities, use \n% getTrafoFromVelocityRK4.m\n%\n% For more details see Sec. 3 of the paper:\n%\n% @article{MangRuthotto2017,\n% Title = {A {L}agrangian {G}auss--{N}ewton--{K}rylov solver for mass- and intensity-preserving diffeomorphic image registration},\n% Year = {2017},\n% Journal = {SIAM Journal on Scientific Computing},\n% Author = {A. Mang, L. Ruthotto},\n% }\n%\n% Input:\n% vc - discrete velocity field (nodal, cell-centered, or staggered in space / nodal in time)\n% yc - particle positions\n%\n% Additional REQUIRED Input (provided through varargin)\n%\n% omega - spatial domain (required!)\n% m - number of cells in each direction (required!)\n%\n% Optional Input (provided through varargin)\n%\n% doDerivative - compute derivative w.r.t. velocity\n% tspan - time interval (default: [0 1]) \n% N - number of time steps (default: 5)\n% nt - number of time points for velocity (default: compute from input)\n% storeInter - store intermediate transformation (e.g., for visualization)\n%\n% Output:\n%\n% yc - end point of characteristics\n% dy - derivative w.r.t. vc\n% para - struct containing info\n%\n% =========================================================================\nfunction [yc,dy,para] = getTrafoFromInstationaryVelocityRK4(vc,yc,varargin)\n\nif nargin==0,\n runMinimalExample\n return;\nend\ndoDerivative = (nargout>1);\nomega = [];\nm = [];\ntspan = [0,1];\nN = 5;\nnt = [];\nstoreInter = false;\nfor k=1:2:length(varargin) % overwrites default parameter\n eval([varargin{k},'=varargin{',int2str(k+1),'};']);\nend;\nif isempty(omega) || isempty(m)\n error('%s - omega and m must be provided through varargin or trafo(''set'',''omega'',omega,''m'',m')\nend\ndim = numel(omega)/2;\nif isempty(nt) % roughly estimate nt\n nt = round(numel(vc)/(prod(m)*dim))-1;\nend\nht = (tspan(2)-tspan(1))/nt;\ntspan = (linspace(tspan(1),tspan(2),N)-min(tspan))/abs(ht)+1; % map to nodal indices\ndt = diff(tspan);\ndt = dt(1);\ndy = [];\nif doDerivative\n dy = cell(nt+1,1);\n for j=1:nt+1, dy{j} = sparse(numel(yc),prod(m)*dim); end;\n dyi = dy;\nend\n\npara = struct('dt',dt,'N',N,'nt',nt,'omega',omega,'m',m);\nif storeInter\n para.YC = zeros(numel(yc),N);\n para.YC(:,1) = yc;\nend\n\nvc = reshape(vc,[],nt+1);\nfor k=1:N-1\n % get v1 = v(yc,t(k));\n tk = tspan(k);\n p = floor(tk); x = tk-p; % split x into integer/remainder\n dvi = zeros(nt+1,1);\n dvi(p) = 1-x;\n if p> pac(x,y,srate);\n% >> [coh,timesout,freqsout1,freqsout2,cohboot] ...\n% = pac(x,y,srate,'key1', 'val1', 'key2', val2' ...);\n% Inputs:\n% x = [float array] 2-D data array of size (times,trials) or\n% 3-D (1,times,trials)\n% y = [float array] 2-D or 3-d data array\n% srate = data sampling rate (Hz)\n%\n% Most important optional inputs\n% 'method' = ['mod'|'corrsin'|'corrcos'|'latphase'] modulation\n% method or correlation of amplitude with sine or cosine of \n% angle (see ref). 'laphase' compute the phase\n% histogram at a specific time and requires the\n% 'powerlat' option to be set.\n% 'freqs' = [min max] frequency limits. Default [minfreq 50], \n% minfreq being determined by the number of data points, \n% cycles and sampling frequency. Use 0 for minimum frequency\n% to compute default minfreq. You may also enter an \n% array of frequencies for the spectral decomposition\n% (for FFT, closest computed frequency will be returned; use\n% 'padratio' to change FFT freq. resolution).\n% 'freqs2' = [float array] array of frequencies for the second\n% argument. 'freqs' is used for the first argument. \n% By default it is the same as 'freqs'.\n% 'wavelet' = 0 -> Use FFTs (with constant window length) { Default } \n% = >0 -> Number of cycles in each analysis wavelet \n% = [cycles expfactor] -> if 0 < expfactor < 1, the number \n% of wavelet cycles expands with frequency from cycles\n% If expfactor = 1, no expansion; if = 0, constant\n% window length (as in FFT) {default wavelet: 0}\n% = [cycles array] -> cycle for each frequency. Size of array\n% must be the same as the number of frequencies \n% {default cycles: 0}\n% 'wavelet2' = same as 'wavelet' for the second argument. Default is\n% same as cycles. Note that if the lowest frequency for X\n% and Y are different and cycle is [cycles expfactor], it\n% may result in discrepancies in the number of cycles at\n% the same frequencies for X and Y.\n% 'ntimesout' = Number of output times (int0: *longest* window length to use. This\n% determines the lowest output frequency. Note that this\n% parameter is overwritten if the minimum frequency has been set\n% manually and requires a longer time window {~frames/8}\n% 'padratio' = FFT-length/winframes (2^k) {2}\n% Multiplies the number of output frequencies by dividing\n% their spacing (standard FFT padding). When cycles~=0, \n% frequency spacing is divided by padratio.\n% 'nfreqs' = number of output frequencies. For FFT, closest computed\n% frequency will be returned. Overwrite 'padratio' effects\n% for wavelets. Default: use 'padratio'.\n% 'freqscale' = ['log'|'linear'] frequency scale. Default is 'linear'.\n% Note that for obtaining 'log' spaced freqs using FFT, \n% closest correspondent frequencies in the 'linear' space \n% are returned.\n% 'subitc' = ['on'|'off'] subtract stimulus locked Inter-Trial Coherence \n% (ITC) from x and y. This computes the 'intrinsic' coherence\n% x and y not arising from common synchronization to \n% experimental events. See notes. {default: 'off'}\n% 'itctype' = ['coher'|'phasecoher'] For use with 'subitc', see TIMEF\n% for more details {default: 'phasecoher'}.\n% 'subwin' = [min max] sub time window in ms (this windowing is\n% performed after the spectral decomposition).\n%\n% Outputs: \n% pac = Matrix (nfreqs1,nfreqs2,timesout) of coherence (complex).\n% Use 20*log(abs(crossfcoh)) to visualize log spectral diffs. \n% timesout = Vector of output times (window centers) (ms).\n% freqsout1 = Vector of frequency bin centers for first argument (Hz).\n% freqsout2 = Vector of frequency bin centers for second argument (Hz).\n% alltfX = single trial spectral decomposition of X\n% alltfY = single trial spectral decomposition of Y\n%\n% Author: Arnaud Delorme, SCCN/INC, UCSD 2005-\n%\n% Ref: Testing for Nested Oscilations (2008) J Neuro Methods 174(1):50-61\n%\n% See also: TIMEFREQ, CROSSF\n\n% Copyright (C) 2002 Arnaud Delorme, Salk Institute, arno@salk.edu\n%\n% This file is part of EEGLAB, see http://www.eeglab.org\n% for the documentation and details.\n%\n% Redistribution and use in source and binary forms, with or without\n% modification, are permitted provided that the following conditions are met:\n%\n% 1. Redistributions of source code must retain the above copyright notice,\n% this list of conditions and the following disclaimer.\n%\n% 2. Redistributions in binary form must reproduce the above copyright notice,\n% this list of conditions and the following disclaimer in the documentation\n% and/or other materials provided with the distribution.\n%\n% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF\n% THE POSSIBILITY OF SUCH DAMAGE.\n\nfunction [crossfcoh, timesout1, freqs1, freqs2, crossfcohall, alltfX, alltfY] = pac(X, Y, srate, varargin);\n \nif nargin < 1\n help pac; \n return; \nend\n\n% deal with 3-D inputs\n% --------------------\nif ndims(X) == 3, X = reshape(X, size(X,2), size(X,3)); end\nif ndims(Y) == 3, Y = reshape(Y, size(Y,2), size(Y,3)); end\nframe = size(X,2);\n\ng = finputcheck(varargin, ...\n { 'alpha' 'real' [0 0.2] [];\n 'baseboot' 'float' [] 0;\n 'boottype' 'string' {'times','trials','timestrials'} 'timestrials';\n 'detrend' 'string' {'on','off'} 'off';\n 'freqs' 'real' [0 Inf] [0 srate/2];\n 'freqs2' 'real' [0 Inf] [];\n 'freqscale' 'string' { 'linear','log' } 'linear';\n 'itctype' 'string' {'phasecoher','phasecoher2','coher'} 'phasecoher';\n 'nfreqs' 'integer' [0 Inf] [];\n 'lowmem' 'string' {'on','off'} 'off';\n 'method' 'string' { 'mod','corrsin','corrcos','latphase' } 'mod';\n 'naccu' 'integer' [1 Inf] 250;\n 'newfig' 'string' {'on','off'} 'on';\n 'padratio' 'integer' [1 Inf] 2;\n 'rmerp' 'string' {'on','off'} 'off';\n 'rboot' 'real' [] [];\n 'subitc' 'string' {'on','off'} 'off';\n 'subwin' 'real' [] []; ...\n 'gammapowerlim' 'real' [] []; ...\n 'powerlim' 'real' [] []; ...\n 'powerlat' 'real' [] []; ...\n 'gammabase' 'real' [] []; ...\n 'timesout' 'real' [] []; ...\n 'ntimesout' 'integer' [] 200; ...\n 'tlimits' 'real' [] [0 frame/srate];\n 'title' 'string' [] '';\n 'vert' { 'real','cell' } [] [];\n 'wavelet' 'real' [0 Inf] 0;\n 'wavelet2' 'real' [0 Inf] [];\n 'winsize' 'integer' [0 Inf] max(pow2(nextpow2(frame)-3),4) }, 'pac');\n\nif ischar(g), error(g); end\n\n% more defaults\n% -------------\nif isempty(g.wavelet2), g.wavelet2 = g.wavelet; end\nif isempty(g.freqs2), g.freqs2 = g.freqs; end\n\n% remove ERP if necessary\n% -----------------------\nX = squeeze(X);\nY = squeeze(Y);X = squeeze(X);\ntrials = size(X,2);\nif strcmpi(g.rmerp, 'on')\n X = X - repmat(mean(X,2), [1 trials]);\n Y = Y - repmat(mean(Y,2), [1 trials]);\nend\n\n% perform timefreq decomposition\n% ------------------------------\n[alltfX freqs1 timesout1] = timefreq(X, srate, 'ntimesout', g.ntimesout, 'timesout', g.timesout, 'winsize', g.winsize, ...\n 'tlimits', g.tlimits, 'detrend', g.detrend, 'itctype', g.itctype, ...\n 'subitc', g.subitc, 'wavelet', g.wavelet, 'padratio', g.padratio, ...\n 'freqs', g.freqs, 'freqscale', g.freqscale, 'nfreqs', g.nfreqs); \n[alltfY freqs2 timesout2] = timefreq(Y, srate, 'ntimesout', g.ntimesout, 'timesout', g.timesout, 'winsize', g.winsize, ...\n 'tlimits', g.tlimits, 'detrend', g.detrend, 'itctype', g.itctype, ...\n 'subitc', g.subitc, 'wavelet', g.wavelet2, 'padratio', g.padratio, ...\n 'freqs', g.freqs2, 'freqscale', g.freqscale, 'nfreqs', g.nfreqs); \n\n% check time limits\n% -----------------\nif ~isempty(g.subwin)\n ind1 = find(timesout1 > g.subwin(1) & timesout1 < g.subwin(2));\n ind2 = find(timesout2 > g.subwin(1) & timesout2 < g.subwin(2));\n alltfX = alltfX(:, ind1, :);\n alltfY = alltfY(:, ind2, :);\n timesout1 = timesout1(ind1);\n timesout2 = timesout2(ind2);\nend\nif length(timesout1) ~= length(timesout2) || any( timesout1 ~= timesout2)\n disp('Warning: Time points are different for X and Y. Use ''timesout'' to specify common time points');\n [vals ind1 ind2 ] = intersect_bc(timesout1, timesout2);\n fprintf('Searching for common time points: %d found\\n', length(vals));\n if length(vals) < 10, error('Less than 10 common data points'); end\n timesout1 = vals;\n timesout2 = vals;\n alltfX = alltfX(:, ind1, :);\n alltfY = alltfY(:, ind2, :);\nend\n\n% scan across frequency and time\n% -------------------------------\n%if isempty(g.alpha)\n% disp('Warning: if significance mask is not applied, result might be slightly')\n% disp('different (since angle is not made uniform and amplitude interpolated)')\n%end\n\ncohboot =[];\nif ~strcmpi(g.method, 'latphase')\n for find1 = 1:length(freqs1)\n for find2 = 1:length(freqs2) \n for ti = 1:length(timesout1)\n\n % get data\n % --------\n tmpalltfx = squeeze(alltfX(find1,ti,:)); \n tmpalltfy = squeeze(alltfY(find2,ti,:));\n\n %if ~isempty(g.alpha)\n % tmpalltfy = angle(tmpalltfy);\n % tmpalltfx = abs( tmpalltfx);\n % [ tmp cohboot(find1,find2,ti,:) newamp newangle ] = ...\n % bootcircle(tmpalltfx, tmpalltfy, 'naccu', g.naccu); \n % crossfcoh(find1,find2,ti) = sum ( newamp .* exp(j*newangle) );\n %else \n tmpalltfy = angle(tmpalltfy);\n tmpalltfx = abs( tmpalltfx);\n if strcmpi(g.method, 'mod')\n crossfcoh(find1,find2,ti) = sum( tmpalltfx .* exp(j*tmpalltfy) );\n elseif strcmpi(g.method, 'corrsin')\n tmp = corrcoef( sin(tmpalltfy), tmpalltfx);\n crossfcoh(find1,find2,ti) = tmp(2);\n else\n tmp = corrcoef( cos(tmpalltfy), tmpalltfx);\n crossfcoh(find1,find2,ti) = tmp(2);\n end\n end\n end\n end\nelseif 1\n % this option computes power at a given latency\n % then computes the same as above (vectors)\n \n %if isempty(g.powerlat)\n % error('You need to specify a latency for the ''powerlat'' option');\n %end\n \n gammapower = mean(10*log10(alltfX(:,:,:).*conj(alltfX)),1); % average all frequencies for power\n if isempty(g.gammapowerlim)\n g.gammapowerlim = [ min(gammapower(:)) max(gammapower(:)) ];\n end\n fprintf('Gamma power limits: %3.2f to %3.2f\\n', g.gammapowerlim(1), g.gammapowerlim(2)); \n power = 10*log10(alltfY(:,:,:).*conj(alltfY));\n if isempty(g.powerlim)\n for freq = 1:size(power,1)\n g.powerlim(freq,:) = [ min(power(freq,:)) max(power(freq,:)) ];\n end\n end\n for freq = 1:size(power,1)\n fprintf('Freq %d power limits: %3.2f to %3.2f\\n', freqs2(freq), g.powerlim(freq,1), g.powerlim(freq,2)); \n end\n \n % power plot\n %figure; plot(timesout2/1000, (mean(power(9,:,:),3)-mean(power(9,:)))/50);\n %hold on; plot(linspace(0, length(Y)/srate, length(Y)), mean(Y'), 'g');\n\n % phase with power\n % figure; plot(timesout2/1000, (mean(phaseangle(9,:,:),3)-mean(phaseangle(9,:)))/50);\n % hold on; plot(timesout1/1000, (mean(gammapower,3)-mean(gammapower(:)))/100, 'r');\n %figure; plot((mean(phaseangle(9,:,:),3)-mean(phaseangle(9,:)))/50+j*(mean(gammapower,3)-mean(gammapower(:)))/100, '.');\n \n matsize = 32;\n matcenter = (matsize-1)/2+1;\n matrixfinalgammapower = zeros(size(alltfY,1),size(alltfX,3),matsize,matsize);\n matrixfinalcount = zeros(size(alltfY,1),size(alltfX,3),matsize,matsize); \n \n % get power indices\n if isempty(g.gammabase)\n g.gammabase = mean(gammapower(:));\n end\n fprintf('Gamma power average: %3.2f\\n', g.gammabase); \n gammapoweradd = gammapower-g.gammabase;\n gammapower = floor((gammapower-g.gammapowerlim(1))/(g.gammapowerlim(2)-g.gammapowerlim(1))*(matsize-2))+1;\n phaseangle = angle(alltfY);\n posx = zeros(size(power));\n posy = zeros(size(power));\n for freq = 1:length(freqs2)\n fprintf('Processing frequency %3.2f\\n', freqs2(freq));\n power(freq,:,:) = (power(freq,:,:)-g.powerlim(freq,1))/(g.powerlim(freq,2)-g.powerlim(freq,1))*(matsize-3)/2+1;\n complexval = power(freq,:,:).*exp(j*phaseangle(freq,:,:));\n posx(freq,:,:) = round(real(complexval)+matcenter);\n posy(freq,:,:) = round(imag(complexval)+matcenter);\n for trial = 1:size(alltfX,3) % scan trials\n for time = 1:size(alltfX,2)\n %matrixfinal(freq,posx(freq,time,trial),posy(freq,time,trial),gammapower(1,time,trial)) = ...\n % matrixfinal(freq,posx(freq,time,trial),posy(freq,time,trial),gammapower(1,time,trial))+1;\n matrixfinalgammapower(freq,trial,posx(freq,time,trial),posy(freq,time,trial)) = ...\n matrixfinalgammapower(freq,trial,posx(freq,time,trial),posy(freq,time,trial))+gammapoweradd(1,time,trial);\n matrixfinalcount(freq,trial,posx(freq,time,trial),posy(freq,time,trial)) = ...\n matrixfinalcount(freq,trial,posx(freq,time,trial),posy(freq,time,trial))+1;\n end\n end\n %matrixfinal(freq,:,:,:) = convn(squeeze(matrixfinal(freq,:,:,:)), gs, 'same');\n %tmpmat = posx(index,:)+(posy(index,:)-1)*64+(gammapower(:)-1)*64*64;\n matrixfinalcount(freq, find(matrixfinalcount(freq,:) == 0)) = 1;\n matrixfinalgammapower(freq,:,:,:) = matrixfinalgammapower(freq,:,:,:)./matrixfinalcount(freq,:,:,:);\n end\n \n % average and smooth\n matrixfinalgammapowermean = squeeze(mean(matrixfinalgammapower,2));\n for freq = 1:length(freqs2)\n matrixfinalgammapowermean(freq,:,:) = conv2(squeeze(matrixfinalgammapowermean(freq,:,:)), gauss2d(5,5), 'same');\n end\n %matrixfinalgammapower = matrixfinalgammapower/size(alltfX,3)/size(alltfX,2);\n \n %vect = linspace(-pi,pi,50); \n %for f = 1:length(freqs2)\n % crossfcoh(f,:) = hist(tmpalltfy(f,:), vect);\n %end\n \n % smoothing of output image\n % -------------------------\n %gs = gauss2d(6, 6, 6);\n %crossfcoh = convn(crossfcoh, gs, 'same');\n %freqs1 = freqs2;\n %timesout1 = linspace(-180, 180, size(crossfcoh,2));\n\n crossfcoh = matrixfinalgammapowermean;\n crossfcohall = matrixfinalgammapower;\n \nelse\n % this option computes power at a given latency\n % then computes the same as above (vectors)\n \n %if isempty(g.powerlat)\n % error('You need to specify a latency for the ''powerlat'' option');\n %end\n \n gammapower = mean(10*log10(alltfX(:,:,:).*conj(alltfX)),1); % average all frequencies for power\n if isempty(g.gammapowerlim)\n g.gammapowerlim = [ min(gammapower(:)) max(gammapower(:)) ];\n end\n power = 10*log10(alltfY(:,:,:).*conj(alltfY));\n if isempty(g.powerlim)\n for freq = 1:size(power,1)\n g.powerlim(freq,:) = [ min(power(freq,:)) max(power(freq,:)) ];\n end\n end\n\n % power plot\n %figure; plot(timesout2/1000, (mean(power(9,:,:),3)-mean(power(9,:)))/50);\n %hold on; plot(linspace(0, length(Y)/srate, length(Y)), mean(Y'), 'g');\n\n % phase with power\n % figure; plot(timesout2/1000, (mean(phaseangle(9,:,:),3)-mean(phaseangle(9,:)))/50);\n % hold on; plot(timesout1/1000, (mean(gammapower,3)-mean(gammapower(:)))/100, 'r');\n %figure; plot((mean(phaseangle(9,:,:),3)-mean(phaseangle(9,:)))/50+j*(mean(gammapower,3)-mean(gammapower(:)))/100, '.');\n \n matsize = 64;\n matcenter = (matsize-1)/2+1;\n matrixfinal = zeros(size(alltfY,1),64,64,64);\n matrixfinalgammapower = zeros(size(alltfY,1),matsize,matsize);\n matrixfinalcount = zeros(size(alltfY,1),matsize,matsize); \n \n % get power indices\n gammapoweradd = gammapower-mean(gammapower(:));\n gammapower = floor((gammapower-g.gammapowerlim(1))/(g.gammapowerlim(2)-g.gammapowerlim(1))*(matsize-1))+1;\n phaseangle = angle(alltfY);\n posx = zeros(size(power));\n posy = zeros(size(power));\n gs = gauss3d(6, 6, 6);\n for freq = 1:size(alltfY)\n fprintf('Processing frequency %3.2f\\n', freqs2(freq));\n power(freq,:,:) = (power(freq,:,:)-g.powerlim(freq,1))/(g.powerlim(freq,2)-g.powerlim(freq,1))*(matsize-2)/2;\n complexval = power(freq,:,:).*exp(j*phaseangle(freq,:,:));\n posx(freq,:,:) = round(real(complexval)+matcenter);\n posy(freq,:,:) = round(imag(complexval)+matcenter);\n for trial = 1:size(alltfX,3) % scan trials\n for time = 1:size(alltfX,2)\n %matrixfinal(freq,posx(freq,time,trial),posy(freq,time,trial),gammapower(1,time,trial)) = ...\n % matrixfinal(freq,posx(freq,time,trial),posy(freq,time,trial),gammapower(1,time,trial))+1;\n matrixfinalgammapower(freq,posx(freq,time,trial),posy(freq,time,trial)) = ...\n matrixfinalgammapower(freq,posx(freq,time,trial),posy(freq,time,trial))+gammapoweradd(1,time,trial);\n matrixfinalcount(freq,posx(freq,time,trial),posy(freq,time,trial)) = ...\n matrixfinalcount(freq,posx(freq,time,trial),posy(freq,time,trial))+1;\n end\n end\n %matrixfinal(freq,:,:,:) = convn(squeeze(matrixfinal(freq,:,:,:)), gs, 'same');\n %tmpmat = posx(index,:)+(posy(index,:)-1)*64+(gammapower(:)-1)*64*64;\n matrixfinalcount(freq, find(matrixfinalcount(freq,:) == 0)) = 1;\n matrixfinalgammapower(freq,:,:) = matrixfinalgammapower(freq,:,:)./matrixfinalcount(freq, :,:);\n matrixfinalgammapower(freq,:,:) = conv2(squeeze(matrixfinalgammapower(freq,:,:)), gauss2d(5,5), 'same');\n end\n %matrixfinalgammapower = matrixfinalgammapower/size(alltfX,3)/size(alltfX,2);\n \n %vect = linspace(-pi,pi,50); \n %for f = 1:length(freqs2)\n % crossfcoh(f,:) = hist(tmpalltfy(f,:), vect);\n %end\n \n % smoothing of output image\n % -------------------------\n %gs = gauss2d(6, 6, 6);\n %crossfcoh = convn(crossfcoh, gs, 'same');\n %freqs1 = freqs2;\n %timesout1 = linspace(-180, 180, size(crossfcoh,2));\n\n crossfcoh = matrixfinalgammapower;\n \nend\n\n% 7/31/2014 Ramon: crossfcohall sometimes does not exist depending on choice of input options\nif ~exist('crossfcohall', 'var')\n crossfcohall = [];\nend \n\n\n", "meta": {"author": "sccn", "repo": "eeglab", "sha": "36d3982a63cde83fb279ab465b7a026ec2807c0a", "save_path": "github-repos/MATLAB/sccn-eeglab", "path": "github-repos/MATLAB/sccn-eeglab/eeglab-36d3982a63cde83fb279ab465b7a026ec2807c0a/functions/timefreqfunc/pac.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.5375871726404459}} {"text": "% LAPPLOT - Compute the discrete laplacian of EEG scalp distribution(s)\n% \n% Usage:\n% >> laplace = lapplot(map,eloc_file,draw)\n% \n% Inputs:\n% map - Activity levels, size (nelectrodes,nmaps)\n% eloc_file\t- Electrode location filename (.loc file) \n% For format, see >> topoplot example \n% draw - If defined, draw the map(s) {default: no}\n%\n% Output:\n% laplace - Laplacian map, size (nelectrodes,nmaps)\n%\n% Note: uses DEL2\n%\n% Author: Scott Makeig, SCCN/INC/UCSD, La Jolla, 1998 \n%\n% See also: TOPOPLOT, GRADPLOT\n\n% Copyright (C) Scott Makeig, SCCN/INC/UCSD, La Jolla, 1998 \n%\n% This file is part of EEGLAB, see http://www.eeglab.org\n% for the documentation and details.\n%\n% Redistribution and use in source and binary forms, with or without\n% modification, are permitted provided that the following conditions are met:\n%\n% 1. Redistributions of source code must retain the above copyright notice,\n% this list of conditions and the following disclaimer.\n%\n% 2. Redistributions in binary form must reproduce the above copyright notice,\n% this list of conditions and the following disclaimer in the documentation\n% and/or other materials provided with the distribution.\n%\n% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF\n% THE POSSIBILITY OF SUCH DAMAGE.\n\n% 01-25-02 reformated help & license, added links -ad \n\nfunction [laplac] = lapplot(map,filename,draw)\n\nif nargin < 2\n\thelp lapplot;\n\treturn;\nend\n\nMAXCHANS = size(map,1);\nGRID_SCALE = 2*MAXCHANS+5;\nMAX_RADIUS = 0.5;\n\n% ---------------------\n% Read the channel file\n% ---------------------\nif ischar( filename )\n\tfid = fopen(filename); \n\tlocations = fscanf(fid,'%d %f %f %s',[7 MAXCHANS]);\n\tfclose(fid);\n\tlocations = locations';\n\tTh = pi/180*locations(:,2); % convert degrees to rads\n\tRd = locations(:,3);\n\tii = find(Rd <= MAX_RADIUS); % interpolate on-scalp channels only\n\tTh = Th(ii);\n\tRd = Rd(ii);\n\t[x,y] = pol2cart(Th,Rd);\nelse\n\tx = real(filename);\n\ty = imag(filename);\nend;\t\n\n% ---------------------------------------------------\n% Locate nearest position of an electrode in the grid \n% ---------------------------------------------------\nxi = linspace(-0.5,0.5,GRID_SCALE); % x-axis description (row vector)\nyi = linspace(-0.5,0.5,GRID_SCALE); % y-axis description (row vector)\nfor i=1:MAXCHANS\n [useless_var horizidx(i)] = min(abs(y(i) - xi)); % find pointers to electrode\n [useless_var vertidx(i)] = min(abs(x(i) - yi)); % positions in Zi\nend\n \n% -----------------\n% Compute laplacian\n% -----------------\nfor i=1:size(map,2) \n \t[Xi,Yi,Zi] = griddata(y,x,map(:,i),yi',xi, 'v4'); % interpolate data\n\n \tlaplac2D = del2(Zi);\n\tpositions = horizidx + (vertidx-1)*GRID_SCALE;\n\tlaplac(:,i) = laplac2D(positions(:));\n\n\t% ------------------\n\t% Draw laplacian map\n\t% ------------------\n\tif exist('draw');\n mask = (sqrt(Xi.^2+Yi.^2) <= MAX_RADIUS);\n laplac2D(find(mask==0)) = NaN;\n\n\t\tsubplot(ceil(sqrt(size(map,2))), ceil(sqrt(size(map,2))), i);\n\t\tcontour(laplac2D); \n\t\ttitle( int2str(i) );\n\n% %%% Draw Head %%%%\nax = axis; \nwidth = ax(2)-ax(1);\naxis([ax(1)-width/3 ax(2)+width/3 ax(3)-width/3 ax(4)+width/3])\nsteps = 0:2*pi/100:2*pi;\nbasex = .18*MAX_RADIUS; \ntip = MAX_RADIUS*1.15; \nbase = MAX_RADIUS-.004;\nEarX = [.497 .510 .518 .5299 .5419 .54 .547 .532 .510 .489];\nEarY = [.0555 .0775 .0783 .0746 .0555 -.0055 -.0932 -.1313 -.1384 -.1199];\n\nHCOLOR = 'k';\nHLINEWIDTH = 1.8;\n\n% Plot Head, Ears, Nose\nhold on\nplot(1+width/2+cos(steps).*MAX_RADIUS*width,...\n 1+width/2+sin(steps).*MAX_RADIUS*width,...\n 'color',HCOLOR,'Linestyle','-','LineWidth',HLINEWIDTH); % head\n\nplot(1+width/2+[.18*MAX_RADIUS*width;0;-.18*MAX_RADIUS*width],...\n 1+width/2+[base;tip;base]*width,...\n 'Color',HCOLOR,'LineWidth',HLINEWIDTH); % nose\n \nplot(1+width/2+EarX*width,...\n 1+width/2+EarY*width,...\n 'color',HCOLOR,'LineWidth',HLINEWIDTH) % l ear\nplot(1+width/2-EarX*width,...\n 1+width/2+EarY*width,...\n 'color',HCOLOR,'LineWidth',HLINEWIDTH) % r ear\n\nhold off\naxis off\n\n\tend\nend; \n\nreturn;\n", "meta": {"author": "sccn", "repo": "eeglab", "sha": "36d3982a63cde83fb279ab465b7a026ec2807c0a", "save_path": "github-repos/MATLAB/sccn-eeglab", "path": "github-repos/MATLAB/sccn-eeglab/eeglab-36d3982a63cde83fb279ab465b7a026ec2807c0a/functions/miscfunc/lapplot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.5375871676384246}} {"text": "% GP_LEARN_PSEUDO - Learns the hyperparameters of a Gaussian process\n% using pseudo inputs.\n%\n% Usage:\n%\n% [THETA_F, THETA_NOISE, LOGLIKELIHOOD] = ...\n% GP_LEARN_PSEUDO(Y, COVFUNC_PSEUDO, THETA0_F, COVFUNC_NOISE, THETA0_NOISE)\n%\n% Y : Nx1 vector of observations\n% COVFUNC_PSEUDO : A special covariance function, see GP_COV_PSEUDO\n% THETA0_F : Initial parameter values for COVFUNC_PSEUDO\n% COVFUNC_NOISE : A diagonal noise covariance function\n% THETA0_NOISE : Initial parameter values for COVFUNC_NOISE\n%\n% THETA_F : Optimized parameter values for COVFUNC_PSEUDO\n% THETA_NOISE : Optimized parameter values for COVFUNC_NOISE\n% LOGLIKELIHOOD : The loglikelihood lower bound at the optimum\n%\n% Optional parameters can be given as\n%\n% [...] = GP_LEARN_PSEUDO(..., 'PARAMETER', VALUE)\n%\n% where the possible parameters are\n%\n% 'MAXITER' : Maximum number of iterations (default: 100)\n% 'CHECKGRAD' : Numerical check of the gradients (default: false)\n%\n% See also GP_PREDICT_PSEUDO, GP_LEARN, GP_COV_PSEUDO,\n% GP_LOGLIKELIHOOD_PSEUDO.\n\n% Last modified 2010-01-27\n% Copyright (c) Jaakko Luttinen (jaakko.luttinen@tkk.fi)\n\nfunction [theta_f, theta_noise, loglikelihood] = gp_learn_pseudo(y, ...\n covfunc_pseudo, ...\n theta_f, ...\n covfunc_noise, ...\n theta_noise, ...\n varargin)\n\noptions = struct('maxiter', 100, ...\n 'checkgrad', false);\n[options, errmsg] = argparse(options, varargin{:});\nerror(errmsg);\n\nn_theta_f = numel(theta_f);\ntheta = [theta_f(:); theta_noise(:)];\n\nif options.checkgrad\n mycheckgrad(@cost, log(theta), 1e-6);\nend\n\n\n[logtheta, logpdfs] = minimize(log(theta), @cost, options.maxiter);\nloglikelihood = -min(logpdfs);\ntheta = exp(logtheta);\n\n function [c, dc] = cost(logtheta)\n theta = exp(logtheta);\n theta_f = theta(1:n_theta_f);\n theta_noise = theta((n_theta_f+1):end);\n [c, dc_f, dc_noise] = gp_loglikelihood_pseudo(y, covfunc_pseudo, theta_f, ...\n covfunc_noise, theta_noise);\n c = -c;\n dc = -[dc_f; dc_noise] .* theta;\n end\n\nend\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_learn_pseudo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.5375871610099351}} {"text": "function [dtdx,dtrp,vart]=trop_model_prec(time,pos,azel,x)\n\nzhd=tropmodel(pi/2,pos,0); %zenith hydrostatic delay\n\n[mh,mw]=tropmapf(time,pos,azel); %hydrostatic and wet projection coefficient\n\nif azel(2)>0\n %equation: m_w=m_0+m_0*cot(el)*(Gn*cos(az)+Ge*sin(az))\n cotz=1.0/tan(azel(2));\n grad_n=mw*cotz*cos(azel(1)); %north wet projection coefficient\n grad_e=mw*cotz*sin(azel(1)); %east wet projection coefficient\n mw=mw+grad_n*x(2)+grad_e*x(3); %total wet projection coefficient\n dtdx(2)=grad_n*(x(1)-zhd); %north wet delay\n dtdx(3)=grad_e*(x(1)-zhd); %east wet delay\nend\n\ndtdx(1)=mw; \ndtrp=mh*zhd+mw*(x(1)-zhd);\nvart=0.01^2;\n\nreturn;", "meta": {"author": "kaichen686", "repo": "GINav", "sha": "bc6b3ab6c40db996a4fd8e8ca5b748fe21a23666", "save_path": "github-repos/MATLAB/kaichen686-GINav", "path": "github-repos/MATLAB/kaichen686-GINav/GINav-bc6b3ab6c40db996a4fd8e8ca5b748fe21a23666/src/gnss/ppp/trop_model_prec.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361557147438, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.5373237346199977}} {"text": "%imu model parameter should be defined in cont. time\nfunction [STM Qd]=mdl_ned_dcm(pos_n, vel_n, Cbn, acc, Aimu, Qimu, Cimu, Rimu, dt)\n\n%continious model\n[Anav N]=sys_ned_dcm_v000(pos_n, vel_n, Cbn, acc, 0, []);\nnst_imu=size(Aimu,1);\nnst=9+nst_imu;\nAc=[Anav N*Cimu;zeros(nst_imu,9) Aimu];\nQc=[N*Rimu*N' zeros(9,nst_imu);zeros(nst_imu,9) Qimu];\n\n\n%Discretize the model\nmx_a = dt*[-Ac,Qc;zeros(nst),Ac'];\nmx_b = expm(mx_a);\nSTM = mx_b(nst+1:2*nst,nst+1:2*nst)';\nQd = STM*mx_b(1:nst,nst+1:2*nst);", "meta": {"author": "JzHuai0108", "repo": "ekfmonoslam", "sha": "443f6be744732453cdb90679abcaf5c962a6295e", "save_path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam", "path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam/ekfmonoslam-443f6be744732453cdb90679abcaf5c962a6295e/instk/INS/mdl_ned_dcm_v000.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9124361509525463, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.5373237318155913}} {"text": " function mac = xray_atten_interp(kev, mac, kev_in, varargin)\n%function mac = xray_atten_interp(kev, mac, kev_in, [options])\n%|\n%| Interpolate mass attenuation coefficients (mac) onto desired energies.\n%| \n%| in\n%|\tkev\t[M,1]\n%|\tmac\t[M,1]\n%|\tkev_in\t[N,1]\t\tdesired energies [in keV]\n%|\n%| option\n%|\t'interp' {}\t\tdefault {'pchip', 'extrap'}\n%| out\n%|\tmac\t[N,1]\t\tmass attenuation coefficients [cm^2/g],\n%|\n%| Copyright 2004-05-1, Jeff Fessler, University of Michigan\n\n% default is to show example\nif nargin < 1, ir_usage, end\nif nargin == 1 && streq(kev, 'test'), xray_atten_interp_test, return, end\n\n% = {'linear', 'extrap'};\n% = {'spline', 'extrap'};\narg.interp = {'pchip', 'extrap'};\narg = vararg_pair(arg, varargin);\n\n% trick: allow for the k-edge jumps!\nmac = log(mac); % interpolate on a log scale\nmac = interp1_jump(kev, mac, kev_in, arg.interp{:});\nmac = exp(mac);\n\n% xray_atten_interp_test()\n% example usage, cf Fig. 3.4 of Macovski 1983\nfunction xray_atten_interp_test\nmtype = 'water'; ax = 10.^[1 3 -2 1.];\nmtype = 'lead'; ax = 10.^[1 3 -1 2.5];\n[mac kev] = xray_read_atten(mtype);\nkev1 = logspace(1,3,1+2^9);\nmac1 = xray_atten_interp(kev, mac, kev1);\nif im\n\tclf, loglog(kev, mac, '.', kev1, mac1, '-')\n\txlabel 'KeV', ylabel 'mass attenuation coefficient [cm^2/g]'\n\taxis(ax)\n\ttexts(0.7, 0.7, mtype)\n\tif streq(mtype, 'lead')\n\t\ttext(14, 40, 'L edge', 'horizontalalignment', 'center')\n\t\ttext(88, 1., 'K edge', 'horizontalalignment', 'center')\n\tend\nend\n% ir_savefig(['fig_atten_' mtype])\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/ct/xray_atten_interp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.7090191214879992, "lm_q1q2_score": 0.5372906993896963}} {"text": "function [w, infos] = sd(problem, in_options)\n% Full steepest descent gradient algorithm.\n%\n% Inputs:\n% problem function (cost/grad/hess)\n% in_options options\n% Output:\n% w solution of w\n% infos information\n%\n% This file is part of GDLibrary and SGDLibrary.\n%\n% Created by H.Kasai on Feb. 15, 2016\n% Modified by H.Kasai on Mar. 23, 2018\n% Modified by H.Kasai on Oct. 20, 2020\n\n\n % set dimensions and samples\n d = problem.dim;\n n = problem.samples; \n \n % set local options \n local_options = []; \n local_options.algorithm = 'SD'; \n local_options.sub_mode = 'STANDARD';\n\n % merge options\n options = mergeOptions(get_default_options(d), local_options); \n options = mergeOptions(options, in_options); \n\n % initialise\n iter = 0;\n grad_calc_count = 0;\n w = options.w_init;\n w_old = w;\n prev_step = options.step_init;\n \n if ~isfield(options, 'S')\n if strcmp(options.step_alg, 'exact')\n options.S = eye(d);\n end \n else \n %\n end\n \n % initialize by BB step-size \n if strcmp(options.step_init_alg, 'bb_init')\n options.step_init = bb_init(problem, w);\n end \n \n % store first infos\n clear infos; \n [infos, f_val, optgap, grad, gnorm] = store_infos(problem, w, options, [], iter, grad_calc_count, 0);\n grad_old = grad;\n \n % display info\n if options.verbose\n if ~problem.prox_flag\n fprintf('SD: Iter = %03d, cost = %.24e, gnorm = %.4e, optgap = %.4e\\n', iter, f_val, gnorm, optgap);\n else\n fprintf('PG: Iter = %03d, cost = %.24e, gnorm = %.4e, optgap = %.4e\\n', iter, f_val, gnorm, optgap);\n end\n end \n \n % set start time\n start_time = tic(); \n\n % main loop\n while (optgap > options.tol_optgap) && (gnorm > options.tol_gnorm) && (iter < options.max_epoch) \n \n options.iter = iter;\n [step, ~] = options.linesearchfun(options.step_alg, problem, w, w_old, grad, grad_old, prev_step, options); \n\n prev_step = step;\n w_old = w;\n if strcmp(options.sub_mode, 'SCALING')\n % diagonal scaling \n if isempty(options.S)\n h = problem.full_hess(w);\n options.S = diag(1./diag(h));\n end\n \n % update w\n w = w - step * options.S * grad; \n else\n % update w\n w = w - step * grad; \n end\n \n % proximal operator\n if problem.prox_flag \n w = problem.prox(w, step);\n end\n \n % store gradient\n grad_old = grad;\n\n % measure elapsed time\n elapsed_time = toc(start_time); \n \n % count gradient evaluations\n grad_calc_count = grad_calc_count + n; \n \n % update iter \n iter = iter + 1; \n \n % store infos\n [infos, f_val, optgap, grad, gnorm] = store_infos(problem, w, options, infos, iter, grad_calc_count, elapsed_time); \n\n % display infos\n if options.verbose\n if ~problem.prox_flag\n fprintf('SD: Iter = %03d, cost = %.24e, gnorm = %.4e, optgap = %.4e\\n', iter, f_val, gnorm, optgap);\n else\n fprintf('PG: Iter = %03d, cost = %.24e, gnorm = %.4e, optgap = %.4e\\n', iter, f_val, gnorm, optgap);\n end\n end \n end\n \n if gnorm < options.tol_gnorm\n fprintf('Gradient norm tolerance reached: tol_gnorm = %g\\n', options.tol_gnorm);\n elseif optgap < options.tol_optgap\n fprintf('Optimality gap tolerance reached: tol_optgap = %g\\n', options.tol_optgap); \n elseif iter == options.max_epoch\n fprintf('Max iter reached: max_epoch = %g\\n', options.max_epoch);\n end \n \nend\n", "meta": {"author": "hiroyuki-kasai", "repo": "SGDLibrary", "sha": "d19a12559c79c3726683243885b15f982f4bec3d", "save_path": "github-repos/MATLAB/hiroyuki-kasai-SGDLibrary", "path": "github-repos/MATLAB/hiroyuki-kasai-SGDLibrary/SGDLibrary-d19a12559c79c3726683243885b15f982f4bec3d/gd_solver/sd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933447152497, "lm_q2_score": 0.6548947155710233, "lm_q1q2_score": 0.5369438187858684}} {"text": "function fh = GNSSspectrumgen\n%==========================================================================\n%GNSSspectrumgen Functions to generate GNSS analytical spectra.\n% fh = GNSSspectrumgen returns the handlers of the local functions:\n%\n% spectrumgen_call\n% [SI SQ] = spectrumgen_call(signal,F) returns the analytical complex \n% spectra of a GNSS signal with normalized complex power.\n%\n% Inputs\n% signal --> GPS L1: L1CA, L1P, L1M, L1C, L1Cd, L1Cp, L1Cp1,L1Cp2\n% L1, L1_new.\n% GPS L2: L2C, L2P, L2M, L2, L2_new.\n% GPS L5: L5I, L5Q, L5, L5_new \n% Galileo E1: E1PRS/EA, E1OS.\n% Galileo E6: E6PRS/E6OS.\n% Galileo E5: E5, E5A, E5B.\n% BeiDou-2 Current: \n% \tB1: B11, B12, B1\n% B2: B2I, B2Q, B2\n% B3: B3\n% BeiDou-2 Future: \n% B1: B1Cd, B1Cp, B1C, B1_new\n% B2: B2_new\n% B3: B3_new, B3A, B3composite\n% F --> Baseband frequency points.\n%\n% Ouputs\n% SI/SQ --> Normalized complex spectrum.\n%\n% spectrum_BPSK\n% S = spectrum_BPSK(fc,F) returns spectrum of a BPSK modulation with a\n% chipping rate fc.\n%\n% spectrum_BOCs\n% S = spectrum_BOCs(n,m,F) returns spectrum of a sine-phased even BOC \n% modulation with a chipping rate fc=m*1.023e6 and sub-carrier rate \n% fs = n*1.023e6.\n%\n% spectrum_BOCc\n% S = spectrum_BOCc(n,m,F) returns spectrum of a cosine-phased even BOC\n% modulation with a chipping rate fc=m*1.023e6 and sub-carrier rate\n% fs = n*1.023e6.\n%\n% spectrum_AltBOC returns spectrum of a sine-phased\n% modified even AltBOC modulation with a chipping rate fc=m*1.023e6 and \n% sub-carrier rate fs = n*1.023e6.\n%\n% Observations\n% # I think that L2 can also transmit a C/A component, but that they\n% actually never do it.\n% # I am not sure if the future BeiDou signals will replace or \n% complement the former signals. Now I assume they will replace them.\n% # I cound't find the official transmitted powers of the BeiDou \n% signals anywhere. I have assumed they are -163dBm per component.\n%\n% References\n% # L1CA/L2: GPS Interface Control Document IS-GPS-200\n% # L1C: GPS Interface Control Document IS-GPS-800\n% # L5: GPS Interface Control Document IS-GPS-705\n% # Galileo: Galileo Open Service Signal In Space Interface Control\n% Document (OS SIS ICD)\n% # BeiDou: BeiDou Navigation Satellite System Signal In Space \n% Interface Control Document 2.0\n%--------------------------------------------------------------------------\n% Version log (main changes)\n% 02/03/2017 --> Log started\n%--------------------------------------------------------------------------\n% Author: Daniel Pascual (daniel.pascual [at] protonmail.com) \n% Copyright 2017 Daniel Pascual\n% License: GNU GPLv3\n%==========================================================================\n\n% Copyright 2017 Daniel Pascual\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 fh.spectrumgen_call = @spectrumgen_call; \n fh.spectrum_BPSK = @spectrum_BPSK;\n fh.spectrum_BOCs = @spectrum_BOCs;\n fh.spectrum_BOCc = @spectrum_BOCc;\n fh.spectrum_AltBOC = @spectrum_AltBOC;\nend\n \n \nfunction [SI, SQ] = spectrumgen_call(signal,F)\n%==========================================================================\n% \n%--------------------------------------------------------------------------\n% Author: Daniel Pascual (daniel.pascual [at] protonmail.com) \n% Copyright 2017 Daniel Pascual\n% License: GNU GPLv3\n%==========================================================================\n\n switch(signal)\n %-------------------- All GNSS individual ------------------------- \n % BPSK\n case {'L1CA', 'L2C'}\n SI = spectrum_BPSK(1.023e6,F);\n SQ = zeros(size(SI));\n \n case {'E6CS'}\n SI = spectrum_BPSK(5*1.023e6,F); \n SQ = zeros(size(SI));\n \n case {'L1P', 'L2P', 'L5I', 'L5Q'}\n SI = spectrum_BPSK(10.23e6,F);\n SQ = zeros(size(SI));\n \n % BOCs\n case{'L1Cd','L1Cp1'} \n SI = spectrum_BOCs(1,1,F);\n SQ = zeros(size(SI));\n \n case{'L1Cp2'} \n SI = spectrum_BOCs(6,1,F);\n SQ = zeros(size(SI));\n \n case {'L1M','L2M'}\n SI = spectrum_BOCs(10,5,F);\n SQ = zeros(size(SI)); \n \n case{'L1Cp'} \n P_Cp1 = GNSS_POWERS.GPS_L1_Cp1/GNSS_POWERS.GPS_L1_Cp;\n P_Cp2 = GNSS_POWERS.GPS_L1_Cp2/GNSS_POWERS.GPS_L1_Cp;\n \n S_Cp1 = P_Cp1*spectrumgen_call('L1Cp1',F); \n S_Cp2 = P_Cp2*spectrumgen_call('L1Cp2',F); \n \n SI = S_Cp1 + S_Cp2;\n SQ = zeros(size(SI)); \n \n case{'L1C'}\n P_Cd = GNSS_POWERS.GPS_L1_Cd/GNSS_POWERS.GPS_L1_C;\n P_Cp = GNSS_POWERS.GPS_L1_Cp/GNSS_POWERS.GPS_L1_C;\n \n S_Cd = P_Cd*spectrumgen_call('L1Cd',F); \n S_Cp = P_Cp*spectrumgen_call('L1Cp',F); \n \n SI = S_Cd;\n SQ = S_Cp;\n \n case 'E1OS'\n SI = (10/11)*spectrum_BOCs(1,1,F)+(1/11)*spectrum_BOCs(6,1,F); \n SQ = zeros(size(SI)); \n \n % BOCc \n case {'E6A','E6PRS'}\n SI = spectrum_BOCc(10,5,F);\n SQ = zeros(size(SI));\n \n case {'E1A','E1PRS'}\n SI = spectrum_BOCc(15,2.5,F);\n SQ = zeros(size(SI));\n \n %-------------------- GPS L1 ------------------------------------- \n % Prior to Block III\n case 'L1'\n P_M = GNSS_POWERS.GPS_L1_M/GNSS_POWERS.GPS_L1;\n P_P = GNSS_POWERS.GPS_L1_P/GNSS_POWERS.GPS_L1;\n P_CA = GNSS_POWERS.GPS_L1_CA/GNSS_POWERS.GPS_L1;\n\n S_CA = P_CA*spectrumgen_call('L1CA',F); \n S_P = P_P*spectrumgen_call('L1P',F); \n S_M = P_M*spectrumgen_call('L1M',F); \n\n SI = S_P+S_M;\n SQ = S_CA;\n \n % Block III (includes L1C)\n case 'L1_new' \n \n P_M = GNSS_POWERS.GPS_L1_M/GNSS_POWERS.GPS_L1_new;\n P_P = GNSS_POWERS.GPS_L1_P/GNSS_POWERS.GPS_L1_new;\n P_CA = GNSS_POWERS.GPS_L1_CA/GNSS_POWERS.GPS_L1_new;\n P_C = GNSS_POWERS.GPS_L1_C/GNSS_POWERS.GPS_L1_new;\n\n S_CA = P_CA*spectrumgen_call('L1CA',F); \n S_P = P_P*spectrumgen_call('L1P',F); \n S_M = P_M*spectrumgen_call('L1M',F); \n [S_Cd, S_Cp] = spectrumgen_call('L1C',F); \n S_Cd = S_Cd*P_C;\n S_Cp = S_Cp*P_C;\n\n SI = S_P+S_M+S_Cd;\n SQ = S_CA+S_Cp;\n \n %-------------------- GPS L2 ------------------------------------- \n case 'L2_new' \n \n P_P = GNSS_POWERS.GPS_L2_P_new/GNSS_POWERS.GPS_L2_new;\n P_C = GNSS_POWERS.GPS_L2_C/GNSS_POWERS.GPS_L2_new; \n P_M = GNSS_POWERS.GPS_L2_M/GNSS_POWERS.GPS_L2_new; \n \n S_P = P_P*spectrumgen_call('L2P',F); \n S_C = P_C*spectrumgen_call('L2C',F); \n S_M = P_M*spectrumgen_call('L2M',F); \n \n SI = S_P+S_M;\n SQ = S_C;\n \n case 'L2_new_2'\n \n P_P = GNSS_POWERS.GPS_L2_P_new/GNSS_POWERS.GPS_L2_new_2;\n P_C = GNSS_POWERS.GPS_L2_C_new/GNSS_POWERS.GPS_L2_new_2; \n P_M = GNSS_POWERS.GPS_L2_M/GNSS_POWERS.GPS_L2_new_2; \n \n S_P = P_P*spectrumgen_call('L2P',F); \n S_C = P_C*spectrumgen_call('L2C',F); \n S_M = P_M*spectrumgen_call('L2M',F); \n \n SI = S_P+S_M;\n SQ = S_C;\n \n %-------------------- GPS L5 ------------------------------------- \n case {'L5', 'L5_new'}\n SI = 0.5*spectrumgen_call('L5I',F);\n SQ = SI; \n\n %-------------------- Galileo E1 ---------------------------------- \n case {'E1'}\n P_E1PRS = 0.5;\n P_E1OS = 0.5;\n \n S_E1PRS = P_E1PRS*spectrumgen_call('E1PRS',F);\n S_E1OS = P_E1OS*spectrumgen_call('E1OS',F);\n \n SI = S_E1OS;\n SQ = S_E1PRS;\n \n %-------------------- Galileo E6 ---------------------------------- \n case 'E6'\n P_E6A = 0.5;\n P_E6B = 0.5; \n \n S_E6PRS = P_E6A*spectrumgen_call('E6PRS',F); \n S_E6CS = P_E6B*spectrumgen_call('E6CS',F); \n \n SI = S_E6CS;\n SQ = S_E6PRS;\n\n %-------------------- Galileo E5 ---------------------------------- \n case 'E5'\n SI = 0.5*spectrum_AltBOC(15,10,F);\n SQ = SI;\n \n case {'E5A','E5B'}\n aux = spectrum_AltBOC(15,10,F); \n len = floor(length(aux)/2);\n aux2 = [aux(1:len+1) zeros(1,len)]; \n len2 = floor(length(aux2)/2);\n [~, aux3] = max(aux2);\n SI = 0.5*2*circshift(aux2',len2-aux3)'; % actually is not exactly multply by 2..\n SQ = SI;\n \n %-------------------- BeiDou-2 current ---------------------------- \n % B1\n case {'B1','B11','B12'}\n SI = 0.5*spectrum_BPSK(2*1.023e6,F);\n SQ = 0.5*spectrum_BPSK(2*1.023e6,F);\n \n % B2\n case {'B2Q'}\n SI = spectrum_BPSK(10*1.023e6,F); \n SQ = zeros(size(SI));\n case {'B2I'}\n SI = spectrum_BPSK(2*1.023e6,F);\n SQ = zeros(size(SI));\n case{'B2'}\n P_B2Q = 0.5;\n P_B2I = 0.5;\n\n SQ = P_B2Q*spectrumgen_call('B2Q',F); \n SI = P_B2I*spectrumgen_call('B2I',F); \n \n % B3\n case{'B3'}\n SI = 0.5*spectrum_BPSK(10*1.023e6,F);\n SQ = SI; \n \n %-------------------- BeiDou-2 future ----------------------------- \n % B1\n case {'B1Cd'}\n SI = spectrum_BOCs(1,1,F);\n SQ = zeros(size(SI));\n \n case {'B1Cp'}\n SI = spectrum_BOCs(6,1,F);\n SQ = zeros(size(SI));\n \n case {'B1C'} \n P_B1Cd = (10/11);\n P_B1Cp = (1/11); \n \n S_B1Cd = P_B1Cd*spectrumgen_call('B1Cd',F); \n S_B1Cp = P_B1Cp*spectrumgen_call('B1Cp',F); \n \n SI = S_B1Cd + S_B1Cp; \n SQ = zeros(size(SI));\n \n case {'B1_new'} \n SI = spectrum_BOCs(14,2,F);\n SQ = zeros(size(SI));\n \n case {'B1composite'}\n P_B1C = GNSS_POWERS.BEIDOU_B1C/GNSS_POWERS.BEIDOU_B1_composite; \n P_B1_new = GNSS_POWERS.BEIDOU_B1_new/GNSS_POWERS.BEIDOU_B1_composite; \n \n S_B1C = P_B1C*spectrumgen_call('B1C',F); \n S_B1_new = P_B1_new*spectrumgen_call('B1_new',F); \n \n SI = S_B1C+S_B1_new;\n SQ = zeros(size(SI));\n \n % B2\n case{'B2_new'}\n SI = 0.5*spectrum_AltBOC(15,10,F);\n SQ = 0.5*spectrum_AltBOC(15,10,F);\n\n % B3\n case{'B3_new'}\n SI = 0.5*spectrum_BPSK(10*1.023e6,F);\n SQ = 0.5*SI;\n case{'B3A'}\n S = spectrum_BOCs(15,2.5,F);\n SQ = zeros(size(SI));\n \n case {'B3composite'} \n P_B3_new = GNSS_POWERS.BEIDOU_B3_new/GNSS_POWERS.BEIDOU_B3_composite; \n P_B3A = GNSS_POWERS.BEIDOU_B3A/GNSS_POWERS.BEIDOU_B3_composite; \n \n S_B3_new = P_B3_new*spectrumgen_call('B3_new',F); \n S_B3A = P_B3A*spectrumgen_call('B3A',F); \n \n SI = S_B3_new; \n SQ = S_B3A; \n end\n end\n\nfunction S = spectrum_BPSK(fc,F)\n%==========================================================================\n% BPSK of chipping rate fc.\n%--------------------------------------------------------------------------\n% Author: Daniel Pascual (daniel.pascual [at] protonmail.com) \n% Copyright 2017 Daniel Pascual\n% License: GNU GPLv3\n%==========================================================================\n\n S = sinc((1/fc)*F); \n aux = sum(abs(S).^2)/length(S); \n S = S/sqrt(aux);\n S = abs(S).^2;\nend\n\nfunction S = spectrum_BOCs(n,m,F) \n%==========================================================================\n% sine-phased BOC even of a chipping rate fc=m*1.023e6 and sub-carrier rate\n% of fs = n*1.023e6.\n%--------------------------------------------------------------------------\n% Author: Daniel Pascual (daniel.pascual [at] protonmail.com) \n% Copyright 2017 Daniel Pascual\n% License: GNU GPLv3\n%==========================================================================\n\n fs = n*1.023e6;\n fc = m*1.023e6;\n\n S = sinc((1/fc)*F).*tan(pi*F/(2*fs)); \n aux = sum(abs(S).^2)/length(S);\n S = S/sqrt(aux);\n S = abs(S).^2;\nend\n\nfunction S = spectrum_BOCc(n,m,F) \n%==========================================================================\n% cosine-phased BOC even of a chipping rate fc=m*1.023e6 and sub-carrier\n% rate of fs = n*1.023e6.\n%--------------------------------------------------------------------------\n% Author: Daniel Pascual (daniel.pascual [at] protonmail.com) \n% Copyright 2017 Daniel Pascual\n% License: GNU GPLv3\n%==========================================================================\n\n fs = n*1.023e6;\n fc = m*1.023e6;\n\n S = 2*sinc((1/fc)*F).*((sin(pi*F/(4*fs)).^2)./cos(pi*F/(2*fs))); \n aux = sum(abs(S).^2)/length(S);\n S = S/sqrt(aux);\n S = abs(S).^2;\nend\n\nfunction S = spectrum_AltBOC(n,m,F) \n%==========================================================================\n% sine-phased AltBOC even of a chipping rate fc=m*1.023e6 and sub-carrier\n% rate of fs = n*1.023e6.\n%--------------------------------------------------------------------------\n% Author: Daniel Pascual (daniel.pascual [at] protonmail.com) \n% Copyright 2017 Daniel Pascual\n% License: GNU GPLv3\n%==========================================================================\n\n fs = n*1.023e6;\n fc = m*1.023e6;\n\n S = (4*fc./((pi*F).^2)).* ((cos(pi*F/(fc))).^2).* (((cos(pi*F/(2*fs))).^2) - cos(pi*F/(2*fs)) - 2*cos(pi*F/(2*fs)).*cos(pi*F/(4*fs)) + 2 ) ./ ((cos(pi*F/(2*fs))).^2);\n S_ = S;\n S_(find(isnan(S))) = 0;\n aux = sum(abs(S_))/length(S); \n S = S/aux;\n S = abs(S);\nend", "meta": {"author": "danipascual", "repo": "GNSS-matlab", "sha": "0365dbc78b3e142266ef899440005dfcc1ee8155", "save_path": "github-repos/MATLAB/danipascual-GNSS-matlab", "path": "github-repos/MATLAB/danipascual-GNSS-matlab/GNSS-matlab-0365dbc78b3e142266ef899440005dfcc1ee8155/source/GNSSspectrumgen.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120234, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5368486261525992}} {"text": "function [p] = dot(qt1,qt2, do_qr)\n%Dot product of two QTT-Tuckers\n% [PR]=DOT(TT1,TT2) -- dot product of two TT-tensors\n%\n% [PR]=DOT(TT1,TT2, DO_QR) if DO_QR==true is specified, perform the \n% left-to-right QRs of TT1,TT2\n% before the scalar product. It increases the accuracy in some cases.\n%\n% In general, returns a 4D tensor of sizes \n% r0(tt1), r0(tt2), rd(tt1), rd(tt2)\n% If r0(tt1) = r0(tt2) = 1 it returns a matrix of size rd(tt1) x rd(tt2)\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\nif (nargin<3)||(isempty(do_qr))\n do_qr = false;\nend;\n\nd=qt1.dphys;\nfor i=1:d\n % dot product of factors gives rt1 times rt2 matrix, to be convolved\n % between cores\n % Make it more precise by QRs? <-- already inside @tt_tensor/dot\n% [qt1.tuck{i}, rv1]=qr(qt1.tuck{i}, 'lr');\n% [qt2.tuck{i}, rv2]=qr(qt2.tuck{i}, 'lr');\n% rv1 = eye(qt1.tuck{i}.r(end));\n% rv2 = eye(qt2.tuck{i}.r(end));\n Pfac = squeeze(dot(qt1.tuck{i}, qt2.tuck{i}, do_qr)); % size rt1,rt2\n% rt1 = size(rv1, 2); rt2 = size(rv2, 2);\n% rt1new = size(rv1,1); rt2new = size(rv2,1);\n % Now, merge Pfac to the core of qt1\n curcr = qt2.core{i};\n rc1 = size(curcr, 1); rt2 = size(curcr, 2); rc2 = size(curcr, 3);\n curcr = permute(curcr, [1, 3, 2]);\n curcr = reshape(curcr, rc1*rc2, rt2);\n% curcr = curcr*(rv1.');\n curcr = curcr*(Pfac.'); % Now, core2 has the tucker ranks of qt1\n curcr = reshape(curcr, rc1, rc2, qt1.core.n(i));\n qt2.core{i} = permute(curcr, [1, 3, 2]);\n \n% curcr = qt2.core{i};\n% rc1 = size(curcr, 1); rc2 = size(curcr, 3);\n% curcr = permute(curcr, [1, 3, 2]);\n% curcr = reshape(curcr, rc1*rc2, rt2); \n% curcr = curcr*(rv2.');\n% curcr = reshape(curcr, rc1, rc2, rt2new);\n% qt2.core{i} = permute(curcr, [1, 3, 2]); \nend;\n% Finaly, dot product of cores. It is consistent, since we merged Pfacs\np = dot(qt1.core, qt2.core, do_qr);\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/@qtt_tucker/dot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246118695629, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.5368486254350575}} {"text": "function Population = LCSA_NSGAIIIEnvironmentalSelection(Population,N,Z,Zmin)\n% ----------------------------------------------------------------------- \n% Copyright (C) 2020 Heiner Zille\n%\n% This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 \n% International License. (CC BY-NC-SA 4.0). To view a copy of this license, \n% visit http://creativecommons.org/licenses/by-nc-sa/4.0/ or see the \n% pdf-file \"License-CC-BY-NC-SA-4.0.pdf\" that came with this code. \n%\n% You are free to: \n% * Share ? copy and redistribute the material in any medium or format\n% * Adapt ? remix, transform, and build upon the material \n% Under the following terms:\n% * Attribution ? You must give appropriate credit, provide a link to the \n% license, and indicate if changes were made. You may do so in any reasonable \n% manner, but not in any way that suggests the licensor endorses you or your use.\n% * NonCommercial ? You may not use the material for commercial purposes.\n% * ShareAlike ? If you remix, transform, or build upon the material, you must \n% distribute your contributions under the same license as the original.\n% * No additional restrictions ? You may not apply legal terms or technological \n% measures that legally restrict others from doing anything the license permits.\n% \n% Author of this Code: \n% Heiner Zille or \n%\n% This code is based on the following publications:\n%\n% 1) Heiner Zille \n% \"Large-scale Multi-objective Optimisation: New Approaches and a Classification of the State-of-the-Art\" \n% PhD Thesis, Otto von Guericke University Magdeburg, 2019 \n% http://dx.doi.org/10.25673/32063 \n% \n% 2) Heiner Zille and Sanaz Mostaghim\n% \"Linear Search Mechanism for Multi- and Many-Objective Optimisation\"\n% 10th International Conference on Evolutionary Multi-Criterion Optimization (EMO 2019), \n% Lecture Notes in Computer Science, vol 11411. \n% Deb K. et al. (eds), Springer, Cham, East Lansing, Michigan, USA, March 2019 \n% https://doi.org/10.1007/978-3-030-12598-1_32.\n%\n% This file is intended to work with the PlatEMO framework version 2.5. \n% Date of publication of this code: 06.04.2020 \n% Last Update of this code: 06.04.2020\n% A newer version of this algorithm may be available. Please contact the author \n% or see http://www.ci.ovgu.de/Research/Codes.html. \n%\n% The files may have been modified in Feb 2021 by the authors of the Platemo framework to work with the Platemo 3.0 release. \n% ----------------------------------------------------------------------- \n% This file is derived from its original version containied in the PlatEMO \n% framework.\n% ----------------------------------------------------------------------- \n\n if isempty(Zmin)\n Zmin = ones(1,size(Z,2));\n end\n\n %% Non-dominated sorting\n [FrontNo,MaxFNo] = NDSort(Population.objs,Population.cons,N);\n Next = FrontNo < MaxFNo;\n \n %% Select the solutions in the last front\n Last = find(FrontNo==MaxFNo);\n Choose = LastSelection(Population(Next).objs,Population(Last).objs,N-sum(Next),Z,Zmin);\n Next(Last(Choose)) = true;\n % Population for next generation\n Population = Population(Next);\nend\n\nfunction Choose = LastSelection(PopObj1,PopObj2,K,Z,Zmin)\n% Select part of the solutions in the last front\n\n PopObj = [PopObj1;PopObj2] - repmat(Zmin,size(PopObj1,1)+size(PopObj2,1),1);\n [N,M] = size(PopObj);\n N1 = size(PopObj1,1);\n N2 = size(PopObj2,1);\n NZ = size(Z,1);\n\n %% Normalization\n % Detect the extreme points\n Extreme = zeros(1,M);\n w = zeros(M)+1e-6+eye(M);\n for i = 1 : M\n [~,Extreme(i)] = min(max(PopObj./repmat(w(i,:),N,1),[],2));\n end\n % Calculate the intercepts of the hyperplane constructed by the extreme\n % points and the axes\n Hyperplane = PopObj(Extreme,:)\\ones(M,1);\n a = 1./Hyperplane;\n if any(isnan(a))\n a = max(PopObj,[],1)';\n end\n % Normalization\n PopObj = PopObj./repmat(a',N,1);\n \n %% Associate each solution with one reference point\n % Calculate the distance of each solution to each reference vector\n Cosine = 1 - pdist2(PopObj,Z,'cosine');\n Distance = repmat(sqrt(sum(PopObj.^2,2)),1,NZ).*sqrt(1-Cosine.^2);\n % Associate each solution with its nearest reference point\n [d,pi] = min(Distance',[],1);\n\n %% Calculate the number of associated solutions except for the last front of each reference point\n rho = hist(pi(1:N1),1:NZ);\n \n %% Environmental selection\n Choose = false(1,N2);\n Zchoose = true(1,NZ);\n % Select K solutions one by one\n while sum(Choose) < K\n % Select the least crowded reference point\n Temp = find(Zchoose);\n Jmin = find(rho(Temp)==min(rho(Temp)));\n j = Temp(Jmin(randi(length(Jmin))));\n I = find(Choose==0 & pi(N1+1:end)==j);\n % Then select one solution associated with this reference point\n if ~isempty(I)\n if rho(j) == 0\n [~,s] = min(d(N1+I));\n else\n s = randi(length(I));\n end\n Choose(I(s)) = true;\n rho(j) = rho(j) + 1;\n else\n Zchoose(j) = false;\n end\n end\nend", "meta": {"author": "BIMK", "repo": "PlatEMO", "sha": "c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5", "save_path": "github-repos/MATLAB/BIMK-PlatEMO", "path": "github-repos/MATLAB/BIMK-PlatEMO/PlatEMO-c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5/PlatEMO/Algorithms/Multi-objective optimization/LCSA/LCSA_NSGAIIIEnvironmentalSelection.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.5368486147682751}} {"text": "function beta=calcStarBetaskBest(A,K)\n%%CALCSTARBETASKBEST Calculate target-measurement association probabilities,\n% as in the JPDAFStar given an association matrix using\n% only the k-best hypotheses for the computation of the\n% target-measurement association probabilities rather\n% than goign through all joint association events.\n%\n%INPUTS: A A numTar X numMeas matrix of all-positive likelihood\n% ratios for assigning the target specified by the row to the\n% measurement specified by the column.\n% K The number of hypotheses to generate.\n%\n%OUTPUTS: beta A numTar X (numMeas+1) matrix of probabilities of assigning\n% the target given by the row to the measurement given by the\n% column. The final column is a set of missed detection\n% probabilities.\n%\n%The general idea behind this function is the same as that of the function\n%calcStarBetasBF. However, rather than generating all possible\n%joint association events, only the k-best events are generated.\n%\n%To reformulate the problem such that a 2D assignment algorithm can be\n%used, the logarithm of the likelihood ratios must be taken, then the cost\n%values are exponentiated to get traditional probabilities.\n%\n%October 2013 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\n%In order to be able to use the k-Best 2D assignment algorithm, the\n%association matrix must be augmented with extra columns that represent\n%missed detection events. When the likelihood ratios in A have been\n%appropriately computed, the likelihood ratio of a missed detection event\n%is equal to one.\n\nnumTar=size(A,1);\nnumMeas=size(A,2);\n\n%Adjust the cost matrix so that 2D assignment can be use.\nA=log(A);\n\n%Alocate space for the results.\nbeta=zeros(numTar,numMeas+1);\n\n%Augment the A matrix to handle missed detection hypotheses. These are\n%supposed to have a likelihood ratio of 1, so the logarithm should be\n%zero.\nAClut=1-eye(numTar);\nAClut(AClut==1)=-inf;\n[col4rowBest,row4ColBest,gainBest]=kBest2DAssignment([A,AClut],K,true);\n\n%Undo the logarithm from before.\ngainBest=exp(gainBest);\n\n%Adjust K to reflect the fact that fewer than K hypotheses might have been\n%present.\nK=size(col4rowBest,2);\n\n%For each hypothesis, determine the set of measurements that are\n%target-originated and save them order in tarMeas. Also find the set of\n%targets that are observed and save them in obsTar.\ntarMeas=zeros(numTar,K);\nobsTar=zeros(numMeas,K);\nfor curHyp=1:K\n tarMeas(:,curHyp)=col4rowBest(:,curHyp);\n\n %Remove elements that are missed detections.\n misSel=col4rowBest(:,curHyp)>numMeas;\n tarMeas(misSel,curHyp)=0;\n\n %Sort the result.\n tarMeas(:,curHyp)=sort(tarMeas(:,curHyp));\n obsTar(:,curHyp)=sort(row4ColBest(1:numMeas,curHyp));\nend\n\n%For each set of observed targets and measurements that are\n%target-originated, go through and only keep the most likely hypothesis.\n%Since everything is already ordered in decreasing gain, the first\n%occurrence of each set of observed targets and target-originated\n%measurements is the most likely.\nvalidHyps=true(K,1);\nfor curHyp=1:K\n if(validHyps(curHyp)==false)\n continue;\n end\n validHyps(curHyp)=false;\n \n for HypS=(curHyp+1):K\n if(isequal(tarMeas(:,curHyp),tarMeas(:,HypS))&&isequal(obsTar(:,curHyp),obsTar(:,HypS)))\n validHyps(HypS)=false;\n end\n end\n \n %Add the ML hypothesis with the given set of observed targets and\n %target-originated measurements to the beta terms.\n for curTar=1:numTar\n curMeas=col4rowBest(curTar,curHyp);\n if(curMeas>numMeas)\n %If it is a missed detection.\n beta(curTar,end)=beta(curTar,end)+gainBest(curHyp);\n else\n beta(curTar,curMeas)=beta(curTar,curMeas)+gainBest(curHyp);\n end\n end\nend\n\n%Normalize the betas so that sum of the probabilities of each target being\n%assigned to a measurement or a missed detection sums to one.\nbeta=bsxfun(@rdivide,beta,sum(beta,2));\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/Assignment_Algorithms/Association_Probabilities_and_Specific_Updates/calcStarBetaskBest.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324983301568, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5367633439271983}} {"text": "function value = dzasum ( n, x, incx )\n\n%*****************************************************************************80\n%\n%% DZASUM 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% 09 May 2006\n%\n% Author:\n%\n% MATLAB version by John Burkardt\n%\n% Reference:\n%\n% Jack Dongarra, Cleve Moler, Jim Bunch, Pete Stewart,\n% LINPACK User's Guide,\n% SIAM, 1979.\n%\n% Charles Lawson, Richard Hanson, David Kincaid, Fred Krogh,\n% Basic Linear Algebra Subprograms for FORTRAN usage,\n% 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/blas1_z/dzasum.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.734119526900183, "lm_q2_score": 0.731058584489497, "lm_q1q2_score": 0.536684382181747}} {"text": "function F = erf(F, varargin)\n%ERF Error function of a CHEBFUN.\n% ERF(X) is the error function of the real-valued CHEBFUN X.\n%\n% The error function is defined as:\n% erf(X)(s) = 2/sqrt(pi) * integral from 0 to X(s) of exp(-t^2) dt.\n%\n% See also ERFC, 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:erf:notreal', 'Input must be real.');\nend\n\n% Call the compose method:\nF = compose(F, @erf, 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/erf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7981867969424067, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.5366462802102608}} {"text": "function surf = imJointSurfaceArea(img, L1, L2, varargin)\n% Surface area of the interface between two labels.\n%\n% S = imJointSurfaceArea(LBL, L1, L2)\n% Estimates the joint surface area between the two labels L1 and L2 in\n% the label image LBL.\n%\n% S = imJointSurfaceArea(LBL, L1, L2, NDIRS)\n% Specifies the number of directions used for estimating surface area.\n% NDIRS can be either 3 or 13 (the default).\n%\n% S = imJointSurfaceArea(..., RESOL)\n% Specifies image resolution. RESOL is a 1-by-3 row vector containing\n% resolution in the X, Y and Z direction (in that order).\n%\n%\n% Example\n% % generate a demo image\n% img = discreteBall(1:10, 1:100, 1:100, [50.12 50.23 50.34 40]);\n% % convert to image with two different labels\n% img2 = uint8(img + 1);\n% % compute joint surface area\n% imJointSurfaceArea(img2, 1, 2)\n% ans = \n% 2.0102e+004\n%\n% See also\n% imSurfaceArea\n\n% ------\n% Author: David Legland\n% e-mail: david.legland@inra.fr\n% Created: 2010-07-26, using Matlab 7.9.0.529 (R2009b)\n% Copyright 2010 INRA - Cepia Software Platform.\n\n% check image dimension and type\nif ndims(img) ~= 3 || islogical(img)\n error('first argument should be a 3D image');\nend\n\n\n%% Process input arguments\n\n% default number of directions\nndir = 13;\n\n% default image resolution\ndelta = [1 1 1];\n\n% Process user input arguments\nwhile ~isempty(varargin)\n var = varargin{1};\n if ~isnumeric(var)\n error('option should be numeric');\n end\n \n % option is either connectivity or resolution\n if isscalar(var)\n ndir = var;\n else\n delta = var;\n end\n varargin(1) = [];\nend\n\n\n%% Initialisations\n\n% distances between a pixel and its neighbours.\nd1 = delta(1);\nd2 = delta(2);\nd3 = delta(3);\n\n% volume of a voxel (used for computing line densities)\nvol = d1 * d2 * d3;\n\n\n%% Main processing for 3 directions\n\n% number of transitions along the 3 main directions\nn1a = sum(sum(sum(img(:,1:end-1,:)==L1 & img(:,2:end,:)==L2)));\nn1b = sum(sum(sum(img(:,1:end-1,:)==L2 & img(:,2:end,:)==L1)));\nn2a = sum(sum(sum(img(1:end-1,:,:)==L1 & img(2:end,:,:)==L2)));\nn2b = sum(sum(sum(img(1:end-1,:,:)==L2 & img(2:end,:,:)==L1)));\nn3a = sum(sum(sum(img(:,:,1:end-1)==L1 & img(:,:,2:end)==L2)));\nn3b = sum(sum(sum(img(:,:,1:end-1)==L2 & img(:,:,2:end)==L1)));\n\nif ndir == 3\n % compute surface area by averaging over the 3 main directions\n surf = 4/3 * ((n1a+n1b)/d1 + (n2a+n2b)/d2 + (n3a+n3b)/d3) / 2 * vol;\n return;\nend\n\n\n%% Additional processing for 13 directions\n\n% Number of connected components along diagonals contained in the three\n% main planes\nn4a = sum(sum(sum(img(2:end,1:end-1,:)==L1 & img(1:end-1,2:end,:)==L2)));\nn4b = sum(sum(sum(img(2:end,1:end-1,:)==L2 & img(1:end-1,2:end,:)==L1)));\nn5a = sum(sum(sum(img(1:end-1,1:end-1,:)==L1 & img(2:end,2:end,:)==L2)));\nn5b = sum(sum(sum(img(1:end-1,1:end-1,:)==L2 & img(2:end,2:end,:)==L1)));\nn6a = sum(sum(sum(img(:,2:end,1:end-1)==L1 & img(:,1:end-1,2:end)==L2)));\nn6b = sum(sum(sum(img(:,2:end,1:end-1)==L2 & img(:,1:end-1,2:end)==L1)));\nn7a = sum(sum(sum(img(:,1:end-1,1:end-1)==L1 & img(:,2:end,2:end)==L2)));\nn7b = sum(sum(sum(img(:,1:end-1,1:end-1)==L2 & img(:,2:end,2:end)==L1)));\nn8a = sum(sum(sum(img(2:end,:,1:end-1)==L1 & img(1:end-1,:,2:end)==L2)));\nn8b = sum(sum(sum(img(2:end,:,1:end-1)==L2 & img(1:end-1,:,2:end)==L1)));\nn9a = sum(sum(sum(img(1:end-1,:,1:end-1)==L1 & img(2:end,:,2:end)==L2)));\nn9b = sum(sum(sum(img(1:end-1,:,1:end-1)==L2 & img(2:end,:,2:end)==L1)));\n\n%TODO: add the case of 9 directions ?\n\n% Number of connected components along lines corresponding to diagonals of\n% the unit cube\nn10a = sum(sum(sum(img(1:end-1,1:end-1,1:end-1)==L1 & img(2:end,2:end,2:end)==L2)));\nn10b = sum(sum(sum(img(1:end-1,1:end-1,1:end-1)==L2 & img(2:end,2:end,2:end)==L1)));\nn11a = sum(sum(sum(img(2:end,1:end-1,1:end-1)==L1 & img(1:end-1,2:end,2:end)==L2)));\nn11b = sum(sum(sum(img(2:end,1:end-1,1:end-1)==L2 & img(1:end-1,2:end,2:end)==L1)));\nn12a = sum(sum(sum(img(1:end-1,2:end,1:end-1)==L1 & img(2:end,1:end-1,2:end)==L2)));\nn12b = sum(sum(sum(img(1:end-1,2:end,1:end-1)==L2 & img(2:end,1:end-1,2:end)==L1)));\nn13a = sum(sum(sum(img(2:end,2:end,1:end-1)==L1 & img(1:end-1,1:end-1,2:end)==L2)));\nn13b = sum(sum(sum(img(2:end,2:end,1:end-1)==L2 & img(1:end-1,1:end-1,2:end)==L1)));\n\n% space between 2 voxels in each direction\nd12 = hypot(d1, d2);\nd13 = hypot(d1, d3);\nd23 = hypot(d2, d3);\nd123 = sqrt(d1^2 + d2^2 + d3^2);\n\n% Compute weights corresponding to surface fraction of spherical caps\n% For isotropic case, weights correspond to:\n% c1 = 0.04577789120476 * 2; % Ox\n% c2 = 0.04577789120476 * 2; % Oy\n% c3 = 0.04577789120476 * 2; % Oz\n% c4 = 0.03698062787608 * 2; % Oxy\n% c6 = 0.03698062787608 * 2; % Oxz\n% c8 = 0.03698062787608 * 2; % Oyz\n% c10 = 0.03519563978232 * 2; % Oxyz\nc = computeDirectionWeights3d13(delta);\n\n% compute the weighted sum of each direction\n% intersection count * direction weight / line density\nsurf = 4 * vol * (...\n (n1a+n1b)*c(1)/d1 + (n2a+n2b)*c(2)/d2 + (n3a+n3b)*c(3)/d3 + ...\n (n4a+n4b+n5a+n5b)*c(4)/d12 + (n6a+n6b+n7a+n7b)*c(6)/d13 + ...\n (n8a+n8b+n9a+n9b)*c(8)/d23 + ...\n (n10a + n10b + n11a + n11b + n12a + n12b + n13a + n13b) * c(10) / d123) / 2;\n\n", "meta": {"author": "mattools", "repo": "matImage", "sha": "94d892c7beac0db32daadf2646ce37f58e894caf", "save_path": "github-repos/MATLAB/mattools-matImage", "path": "github-repos/MATLAB/mattools-matImage/matImage-94d892c7beac0db32daadf2646ce37f58e894caf/matImage/imMinkowski/imJointSurfaceArea.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.5366462777806178}} {"text": "function ker0_values_test ( )\n\n%*****************************************************************************80\n%\n%% KER0_VALUES_TEST demonstrates the use of KER0_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, 'KER0_VALUES_TEST:\\n' );\n fprintf ( 1, ' KER0_VALUES stores values of \\n' );\n fprintf ( 1, ' the Kelvin function KER of order 0.\\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 ] = ker0_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/ker0_values_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.672331699179286, "lm_q2_score": 0.7981867801399695, "lm_q1q2_score": 0.5366462741539488}} {"text": "function bdiffma(newcat)\n % This routine etsimates the b-value of a curve automatically\n % The b-valkue curve is differenciated and the point\n % of maximum curvature marked. The b-value will be calculated\n % using this point and the point half way toward the high\n % magnitude end of the b-value curve.\n\n % Stefan Wiemer 1/95\n %\n think\n %zmap_message_center.set_info(' ','Calculating b-value...')\n global cluscat mess bfig backcat xt3 bvalsum3\n global ttcat teb t0b cua b1 b2 n1 n2\n report_this_filefun(mfilename('fullpath'));\n\n [existFlag,figNumber]=figure_exists('frequency-magnitude distribution',1);\n if existFlag\n % figure_w_normalized_uicontrolunits(bfig);\n bfig = figNumber;\n else\n bfig=figure_w_normalized_uicontrolunits(... %build figure for plot\n 'Units','normalized','NumberTitle','off',...\n 'Name','frequency-magnitude distribution',...\n 'MenuBar','none',...\n 'visible','off',...\n 'pos',[ 0.300 0.7 0.5 0.5]);\n\n\n \n uicontrol('Units','normal',...\n 'Position',[.0 .85 .08 .06],'String','Info ',...\n 'Callback','infoz(1)');\n uicontrol('Units','normal',...\n 'Position',[.0 .55 .10 .06],'String','Manual ',...\n 'Callback','bfitnew(newcat)');\n matdraw\n\n uicontrol('Units','normal',...\n 'Position',[.0 .65 .08 .06],'String','Save ',...\n 'Callback',{@calSave9,xt3, bvalsum3})\n\n\n end\n\n maxmag = max(newcat.Magnitude);\n mima = min(newcat.Magnitude);\n if mima > 0 ; mima = 0 ; end\n\n % number of mag units\n nmagu = (maxmag*10)+1;\n\n bval = zeros(1,nmagu);\n bvalsum = zeros(1,nmagu);\n bvalsum3 = zeros(1,nmagu);\n\n [bval,xt2] = hist(newcat.Magnitude,(mima:0.1:maxmag));\n bvalsum = cumsum(bval); % N for M <=\n bvalsum3 = cumsum(bval(length(bval):-1:1)); % N for M >= (counted backwards)\n xt3 = (maxmag:-0.1:mima);\n\n\n backg_be = log10(bvalsum);\n backg_ab = log10(bvalsum3);\n orient tall\n\n if hold_state\n axes(cua)\n hold on\n else\n figure_w_normalized_uicontrolunits(bfig);delete(gca);delete(gca);delete(gca);delete(gca)\n rect = [0.2, 0.3, 0.70, 0.6]; % plot Freq-Mag curves\n axes('position',rect);\n end\n\n pl =semilogy(xt3,bvalsum3,'b');\n set(pl,'LineWidth',2.0)\n hold on\n %semilogy(xt3,bvalsum3,'om')\n difb = [0 diff(bvalsum3) ];\n %pl =semilogy(xt3,difb,'g');\n %set(pl,'LineWidth',2.0)\n %semilogy(xt3,difb,'g')\n grid\n\n % Marks the point of maximum curvature\n %\n i = find(difb == max(difb));\n i = max(i);\n %te = semilogy(xt3(i),difb(i),'xk');\n %set(te,'LineWidth',2,'MarkerSize',ms10)\n %te = semilogy(xt3(i),bvalsum3(i),'xk');\n %set(te,'LineWidth',2,'MarkerSize',ms10)\n\n % Estimate the b-value\n %\n i2 = 1 ;\n %te = semilogy(xt3(i2),difb(i2),'xk');\n %set(te,'LineWidth',2,'MarkerSize',ms10)\n %te = semilogy(xt3(i2),bvalsum3(i2),'xk');\n %set(te,'LineWidth',2,'MarkerSize',ms10)\n\n xlabel('Magnitude','FontWeight','bold','FontSize',ZmapGlobal.Data.fontsz.m)\n ylabel('Cumulative Number','FontWeight','bold','FontSize',ZmapGlobal.Data.fontsz.m)\n set(gca,'Color',color_bg)\n set(gca,'visible','on','FontSize',ZmapGlobal.Data.fontsz.m,'FontWeight','bold',...\n 'FontWeight','bold','LineWidth',1.5,...\n 'Box','on')\n\n cua = gca;\n\n\n par2 = 0.1 * max(bvalsum3);\n par3 = 0.12 * max(bvalsum3);\n M1b = [];\n M1b = [xt3(i) bvalsum3(i)];\n tt3=num2str(fix(100*M1b(1))/100);\n text( M1b(1),M1b(2),['|: M1=',tt3],'Fontweight','bold' )\n\n M2b = [];\n M2b = [xt3(i2) bvalsum3(i2)];\n tt4=num2str(fix(100*M2b(1))/100);\n %text( M2b(1),M2b(2),['|: M2=',tt4],'Fontweight','bold' )\n\n ll = xt3 >= M1b(1) & xt3 <= M2b(1);\n x = xt3(ll);\n\n [ av,bv,si] = bmemag(newcat);\n\n pause(0.1)\n\n y = backg_ab(ll);\n %[p,s] = polyfit(x,y,1) % fit a line to background\n [aw bw, ew] = wls(x',y');\n p = [bw aw];\n f = polyval(p,x);\n (teb-t0b)/(10.^ polyval(p,5))\n (teb-t0b)/(10.^ polyval(p,6))\n (teb-t0b)/(10.^ polyval(p,7))\n (teb-t0b)/(10.^ polyval(p,8))\n f = 10.^f;\n hold on\n ttm= semilogy(x,f,'r'); % plot linear fit to backg\n set(ttm,'LineWidth',1)\n set(gca,'XLim',[min(newcat.Magnitude)-0.5 max(newcat.Magnitude)+1.0])\n r = corrcoef(x,y);\n r = r(1,2);\n std_backg = ew; % standard deviation of fit\n\n p=-p(1,1);\n p=fix(100*p)/100;\n std_backg=fix(100*std_backg)/100;\n tt2=num2str(std_backg);\n tt1=num2str(p);\n tt4=num2str(bv,2);\n tt5=num2str(si,2);\n\n\n rect=[0 0 1 1];\n h2=axes('position',rect);\n set(h2,'visible','off');\n\n if ~ho\n txt1=text(.16, .18,['b-value (w LS, M > ', num2str(M1b(1)) '): ',tt1, ' +/- ', tt2]);\n set(txt1,'FontWeight','bold','FontSize',ZmapGlobal.Data.fontsz.m)\n txt1=text(.16, .12,['b-value (max lik, M > ', num2str(min(newcat.Magnitude)) '): ',tt4, ' +/- ', tt5]);\n set(txt1,'FontWeight','bold','FontSize',ZmapGlobal.Data.fontsz.m)\n\n else\n txt1=text(.16, .06,['b-value (weighted least square): ',tt1, ' +/- ', tt2]);\n set(txt1,'FontWeight','bold','FontSize',ZmapGlobal.Data.fontsz.m,'Color','r')\n end\n set(gcf,'visible','on');\n zmap_message_center.set_info(' ','Done')\n done\n\n if hold_state\n % calculate the probability that the two distributins are differnt\n b2 = str2double(tt1); n2 = newcat.Count;\n n = n1+n2;\n da = -2*n*log(n) + 2*n1*log(n1+n2*b1/b2) + 2*n2*log(n1*b2/b1+n2) -2;\n pr = exp(-da/2-2);\n disp(['Probability: ', num2str(pr)]);\n txt1=text(.65, .85,['Utsu Test: ', num2str(pr)]);\n set(txt1,'FontWeight','bold','FontSize',ZmapGlobal.Data.fontsz.m)\n else\n b1 = str2double(tt1); n1 = newcat.Count;\n end\n\n\n\n\n", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/zmap_deprecated/orphaned/src/bdiffma.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867681382279, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.5366462713252966}} {"text": "function [x, infos] = robust_online_mu_nmf(V, rank, in_options)\n% Robust online non-negative matrix factorization (ONMF) with outliers (RONMF) 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% R. Zhao and Y. F. Tan,\n% \"Online nonnegative matrix factorization with outliers,\"\n% ICASSP, 2016.\n% \n%\n% This file is part of NMFLibrary.\n%\n% Created by H.Sakai and H.Kasai on Feb. 12, 2017\n%\n% Change log: \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.lambda = 1;\n local_options.x_init_robust = true;\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 = 'Robust-Online-MU';\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 \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 Ct = zeros(m, rank);\n\n % main inner loop\n for t = 1 : options.batch_size : n - 1\n\n % Retrieve vt, ht and rt\n vt = V(:, t:t+options.batch_size-1);\n ht = H(:, t:t+options.batch_size-1);\n rt = R(:, t:t+options.batch_size-1);\n\n % update ht/rt\n ht = ht .* (Wt.' * vt) ./ (Wt.' * (Wt * ht + rt));\n ht = ht + (ht for details.\n%\n% A brief summary of ordering and orientation\n%\n% * edge: asecond ordering, i.e. edge(:,1) for details. Note that the ordering of vertices of each edge\n% will not change the indexing. For example, |locEdge = [2,3; 1,3; 1,2]|\n% use the same opposite indexing but different ordering. Chosing |[1 3]| or\n% |[3 1]| for the second edge will depend on the consideration of\n% orientation and ordering.\n%\n% *Global indexing of edges*\n%\n% One can easily collect all edges elementwise. The issue is the\n% duplication. For example, each interior edge will be counted twice. The\n% |unique| funciton is applied such that each edge has a unique global\n% index.\n%\ntotalEdge = uint32([elem(:,[2,3]); elem(:,[3,1]); elem(:,[1,2])]);\nsortedTotalEdge = sort(totalEdge,2);\n[edge,tempvar,je] = unique(sortedTotalEdge,'rows');\nNE = size(edge,1); \n%%\n% *Edge pointer*\n%\n% |elem2edge(1:NT,1:3)| records the pointer from the local index to the\n% global index of edges. For example, |elem2edge(t,1)| = 10 means the first\n% edge of triangle |t| (which is formed by [2 3] vertices of |t|) is the\n% |10-th| one in the |edge| array.\n%\n% Such information is stored in the third output of |unique| function.\n%%\nelem2edge = uint32(reshape(je,NT,3));\n%%\n% Note that the pointer |elem2edge| depends on the local indexing of edges\n% used in the generation of |totalEdge|. Here the opposite indexing of\n% three local edges is used.\n\n%% Ordering of Vertices\n%\n% We discuss the ordering of vertices of simplexes. Again there are local\n% ordering and global ordering. They may not be consistent and a sign array\n% is used to record the inconsistency if any.\n%\n% The local ordering refers to the ordering of local veritces of a simplex.\n% The local ordering could be used in the formulation of the local basis\n% and thus the ordering does matter.\n%\n% The global ordering refers to the ordering of the global index of\n% vertices of a simplex.\n%\n% *elem*. The local ordering is always [1,2,3]. Any permutation of three\n% veritces of a triangle still represents the same triangle. Such\n% freedom provide a room to record more information like:\n% \n% * global ordering of vertices\n% * orientation of triangles\n% * refinement rule\n%\n% Two types of ordering of |elem| is of particular importance\n%\n% * Positive ordering\n% * Ascend ordering\n%\n% In the positive ordering, the three vertices are ordered such that the\n% signed area, det(v12,v13), is positive. If |elem| is not positive\n% ordered, |elem = fixorder(node,elem)| will compute the signed area by\n% |simplexvolume(node,elem)| and switch the vertices for triangles with\n% negative areas.\n%\n% For 2-D triangulations, three vertices of a triangle in 2-D is sorted\n% counter-cloclwise and the first vertex is chosen as the newest vertex.\n% Such ordering enables the efficient implementation of local refinement\n% and coarsening in 2-D; see \n% and . *Such ordering scheme\n% is the default choice and used in most places*.\n%\n%\n% In ascend ordering, the vertices of |elem| is sorted such that\n% |elem(t,1)