{"text": "function field=meg_forward(dip_par,forwpar)\n% calculates the magnetic field of n dipoles\n% in a realistic volume conductor\n% usage: field=meg_forward(dip_par,forwpar)\n%\n% input:\n% dip_par nx6 matrix where each row contains location (first 3 numbers)\n% and moment (second 3 numbers) of a dipole\n% forwpar structure containing all information relevant for this\n% calculation; forwpar is calculated with meg_ini\n% You have here an option to include linear transformations in\n% the forward model by specifying forpwar.lintrafo=A\n% where A is an NxM matrix. Then field -> A field\n% You can use that, e.g., if you can write the forward model\n% with M magnetometer-channels plus a matrix multiplication\n% transforming this to a (eventually higher order) gradiometer.\n%\n% output:\n% field mxn matrix where the i.th column is the field in m channels\n% of the i.th dipole\n%\n% note: No assumptions about units are made (i.e. no scaling factors)\n%\n% Copyright (C) 2003, Guido Nolte\n%\n% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org\n% for the documentation and details.\n%\n% FieldTrip is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% FieldTrip is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with FieldTrip. If not, see .\n%\n% $Id$\n\ndevice_sens=forwpar.device_sens;\n\nfield_sens_sphere=getfield_sphere(dip_par,forwpar.device_sens,forwpar.center);\nfield=field_sens_sphere;clear field_sens_sphere;\nif isfield(forwpar,'device_ref')\n field=field-getfield_sphere(dip_par,forwpar.device_ref,forwpar.center);\nend\nif isfield(forwpar,'device_weights')\n field=field+forwpar.weights*getfield_sphere(dip_par,forwpar.device_weights,forwpar.center);\nend\n\nif forwpar.order>0\n coeff=forwpar.coeff_sens;\n if isfield(forwpar,'device_ref')\n coeff=coeff-forwpar.coeff_ref;\n end\n if isfield(forwpar,'device_weights')\n coeff=coeff+forwpar.coeff_weights*forwpar.weights';\n end\n field=field+getfield_corr(dip_par,coeff,forwpar.center,forwpar.order);\nend\n\nif isfield(forwpar,'lintrafo');\n field=forwpar.lintrafo*field;\nend\n\nreturn % main function\n\n\nfunction field=getfield_sphere(source,device,center)\n[ndip,ndum]=size(source);\n[nchan,ndum]=size(device);\nx1=source(:,1:3)-repmat(center',ndip,1);\nn1=source(:,4:6);\nx2=device(:,1:3)-repmat(center',nchan,1);\nn2=device(:,4:6);\n%spherical\nbt=leadsphere_all(x1',x2',n2');\nn1rep=reshape(repmat(n1',1,nchan),3,ndip,nchan);\nb=dotproduct(n1rep,bt);\nfield=b';\nreturn\n\nfunction field=getfield_corr(source,coeffs,center,order)\n[ndip,ndum]=size(source);\nx1=source(:,1:3)-repmat(center',ndip,1);\nn1=source(:,4:6);\n%correction\nif order>0\n scale=10;\n [bas,gradbas]=legs(x1,n1,order,scale);\n nbasis=(order+1)^2-1;\n coeffs=coeffs(1:nbasis,:);\n field=-(gradbas*coeffs)';\nend\nreturn\n\nfunction out=crossproduct(x,y)\n% usage: out=testprog(x,y)\n% testprog calculates the cross-product of vector x and y\n[n,m,k]=size(x);\nout=zeros(3,m,k);\nout(1,:,:)=x(2,:,:).*y(3,:,:)-x(3,:,:).*y(2,:,:);\nout(2,:,:)=x(3,:,:).*y(1,:,:)-x(1,:,:).*y(3,:,:);\nout(3,:,:)=x(1,:,:).*y(2,:,:)-x(2,:,:).*y(1,:,:);\nreturn\n\nfunction out=dotproduct(x,y)\n% usage: out=dotproduct(x,y)\n% testprog calculates the dotproduct of vector x and y\n[n,m,k]=size(x);\noutb=x(1,:,:).*y(1,:,:)+x(2,:,:).*y(2,:,:)+x(3,:,:).*y(3,:,:);\nout=reshape(outb,m,k);\nreturn\n\nfunction result=norms(x)\n[n,m,k]=size(x);\nresultb=sqrt(x(1,:,:).^2+x(2,:,:).^2+x(3,:,:).^2);\nresult=reshape(resultb,m,k);\nreturn\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/forward/private/meg_forward.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.34986642796912015}} {"text": "function [W,dist_H_V] = shepard(V,C,P,E,CE,p)\n % SHEPARD Compute shepard weights for a list of vertices, given a list of\n % samples and optionally a denominator power value.\n %\n % W = shepard(V,C)\n %\n % Inputs:\n % V list of vertex positions\n % C list of control vertices\n % P list of indices into C for point controls, { 1:size(C,1) }\n % E list of bones, pairs of indices into C, connecting control vertices, \n % { [] }\n % CE list of \"cage edges\", pairs of indices into ***P***, connecting\n % control ***points***. A \"cage edge\" just tells point boundary conditions \n % to vary linearly along straight lines between the end points, and to be\n % zero for all other handles. { [] }\n % p (optional) power for denominator, scalar or list same size as C {2}\n %\n % Outputs:\n % W weights, # vertices by # handles matrix of weights\n %\n % Example:\n % % \"Shape-aware\" shepard weights\n % D = permute(sum((repmat(V,[1,1,size(C,1)]) - ...\n % permute(repmat(C,[1,1,n]),[3,2,1])).^2,2),[1,3,2]);\n % [minD,b] = min(D);\n % snap_C = V(b,:);\n % [BV,ev,ed] = biharmonic_embedding(V,F,6);\n % [W] = shepard(BV,BV(b,:));\n %\n %\n\n % check if either are 3D but really all z's are 0\n V_flat = size(V,2) == 3 && (sqrt(sum(V(:,3).^2)) < 1e-10);\n C_flat = size(C,2) == 3 && (sqrt(sum(C(:,3).^2)) < 1e-10);\n % is both are essentially 2D then ignore z-coords\n if((size(C,2) == 2 || C_flat) && (size(V,2) == 2 || V_flat))\n % ignore z coordinate\n V = V(:,1:2);\n C = C(:,1:2);\n end\n\n assert(size(C,2) == size(V,2));\n dim = size(C,2);\n\n % default p value\n if(~exist('p','var'))\n p = 2;\n end\n\n if(~exist('P','var'))\n P = 1:size(C,1);\n end\n\n if(~exist('E','var'))\n E = [];\n end\n\n if(~exist('CE','var'))\n CE = [];\n end\n\n assert(prod(size(P)) == max(size(P)));\n assert(isempty(E) || size(E,2) == 2);\n assert(isempty(CE) || size(CE,2) == 2);\n assert(isempty(E) || max(E(:))<=size(C,1));\n assert(isempty(CE) || max(CE(:))<=numel(P));\n assert(isempty(P) || max(P(:))<=size(C,1));\n assert(isempty(E) || min(E(:)) >= 1);\n assert(isempty(CE) || min(CE(:)) >= 1);\n assert(isempty(P) || min(P(:)) >= 1);\n\n\n % number of point controls \n np = numel(P);\n nb = size(E,1);\n % number of domain vertices\n n = size(V,1);\n\n % if p is a scalar convert it now to a list the same size as C\n if(prod(size(p)) == 1)\n p = repmat(p,np+nb,1);\n elseif ~isempty(CE)\n if 0 ~= std(p(CE(:)))\n error('Variable powers not supported with cage edges');\n end\n end\n\n dist_P_V = zeros(np,n);\n if(np > 0)\n % vectors from V to every P, where PmV(i,j,:) is the vector from domain\n % vertex j to handle i\n PmV = ...\n permute( ...\n permute(repmat(C(P,:),[1,1,n]),[3,2,1]) - ...\n repmat(V,[1,1,np]),[3,1,2]);\n % distance from V to every P, where dist_P_V(i,j) is the distance from domain\n % vertex j to point handle i\n dist_P_V = sqrt(sum(PmV.^2,3));\n % distance from each corner in P to the next corner so that edge_length(i) \n end\n\n dist_B_V = zeros(nb,n);\n if(nb > 0)\n % loop over bones\n for( ii = 1:nb )\n % project to line\n [t,sqr_d] = project_to_lines(V,C(E(ii,1),:),C(E(ii,2),:));\n d = sqrt(sqr_d);\n % if projected point falls outside of line segment take distance to\n % closest end point\n d(t<0) = sqrt(sum((V(t<0,:)-repmat(C(E(ii,1),:),size(V(t<0,:),1),1)).^2,2));\n d(t>1) = sqrt(sum((V(t>1,:)-repmat(C(E(ii,2),:),size(V(t>1,:),1),1)).^2,2));\n dist_B_V(ii,:) = d';\n end\n end\n\n dist_H_V = [dist_P_V ; dist_B_V];\n % power of each control point seen by each vertex in domain\n pp = repmat(p,1,n);\n W = 1.0./((dist_H_V).^pp);\n\n if(size(CE,1) > 0)\n % zero out previous entries in points with incident cage edges\n W(CE(:),:) = 0;\n % compute projection of each point to each line segment\n [T,sqrD] = project_to_lines(V,C(P(CE(:,1)),:),C(P(CE(:,2)),:));\n % compute weights for each cage edge as if it were a bone\n pce = (p(CE(:,1))+p(CE(:,2)))/2;\n [~,dist_CE_V] = shepard(V,C,[],P(CE),[],pce);\n % compute \"bone weights\" for each cage edge as they were before\n % normalization\n ppce = repmat(pce,1,n);\n WCE = 1.0./((dist_CE_V).^ppce)';\n % clamp distances\n T(T<0) = 0;\n T(T>1) = 1;\n % multiply \"bone weight\" by projection parameter and sum up\n II = repmat(1:n,1,2*size(CE,1))';\n JJ = reshape(repmat(CE(:)',n,1),[],1);\n VV = [WCE(:).*(1-T(:)); WCE(:).*T(:)];\n W = W+sparse(II,JJ,VV,n,np+nb)';\n % cage edges on-samples\n on_sample = dist_CE_V < eps;\n [I,J] = find(on_sample);\n W(:,any(on_sample)) = 0;\n % grab T transpose\n TT = T';\n W(sub2ind(size(W),CE(I,1),J)) = 1-TT(on_sample);\n W(sub2ind(size(W),CE(I,2),J)) = TT(on_sample);\n end\n\n % Handle degenrate case that a control point is on a mesh vertex\n % snap vertices close to corners\n on_sample = dist_H_V < eps;\n W(:,any(on_sample,1)) = 0;\n W(on_sample) = 1;\n\n % normalize W\n W = W./repmat(sum(W,1),np+nb,1);\n\n % we've made W transpose\n W = W';\n\nend\n", "meta": {"author": "alecjacobson", "repo": "gptoolbox", "sha": "a0cb37d8edbcfb1e3587f793df8f24c76a2d7305", "save_path": "github-repos/MATLAB/alecjacobson-gptoolbox", "path": "github-repos/MATLAB/alecjacobson-gptoolbox/gptoolbox-a0cb37d8edbcfb1e3587f793df8f24c76a2d7305/mesh/shepard.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6723316860482763, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.3492906463260801}} {"text": "classdef prtClassMilVbDpGmm < prtClass\n % prtClassMilVbDpGmm VBDPGMM MIL Classifier\n %\n % A variational bayes classifier for multiple instance data. There\n % are a number of parameters available for pruning/training.\n % Performnace should (in theory) be somewhat invariant to these. See\n % the text of Manandhar et al., for descriptions.\n %\n % You may need to reduce the dimensionality of the data being used via\n % PCA, PLS, or some other pre-processing prior to using\n % prtClassMilVbDpGmm. We also recommend making sure the data is\n % approximately zero-mean, unit-variance in each of the columns.\n %\n % dsTrain = prtDataGenMultipleInstance;\n % dsTest = prtDataGenMultipleInstance;\n % class = prtClassMilVbDpGmm;\n % class = class.train(dsTrain);\n % yOutTrain = class.run(dsTrain);\n % yOutTest = class.run(dsTest);\n %\n % [pfTrain,pdTrain] = prtScoreRoc(yOutTrain);\n % [pfTest,pdTest] = prtScoreRoc(yOutTest);\n % subplot(1,1,1);\n % plot(pfTrain,pdTrain,pfTest,pdTest);\n %\n\n\n\n\n\n\n\n properties (SetAccess=private)\n name = 'MilVbDpGmm' \n nameAbbreviation = 'MilVbDpGmm' \n isNativeMary = false; % False\n end\n \n \n properties\n maxVbIter = 300;\n \n K0 = 5;\n K1 = 5; \n gamma_0_1_m0 = 1;\n gamma_0_2_m0 = .001;\n gamma_0_1_m1 = 1;\n gamma_0_2_m1 = .001;\n alpha = [10 10];\n \n rvH1\n rvH0\n end\n \n properties (Hidden)\n \n initialFit = [];\n %Dependent on \"d\"\n v_0_m\n v_1_m\n beta_1_m\n beta_0_m\n \n rho_0_1\n rho_0_0\n Phi_0_1\n Phi_0_0\n end\n \n\tmethods\n\t\tfunction self = prtClassMilVbDpGmm(varargin)\n\n\t\t\tself = prtUtilAssignStringValuePairs(self,varargin{:});\n \n self.classTrain = 'prtDataSetClassMultipleInstance';\n self.classRun = 'prtDataSetClassMultipleInstance';\n self.classRunRetained = false;\n end\n\t\t\n end\n \n methods (Access=protected, Hidden = true)\n\t\tfunction self = trainAction(self,dsMil)\n \n milStruct = dsMil.data;\n x = cat(1,milStruct.data);\n \n bagLabels = dsMil.targets;\n expandedBagLabels = dsMil.expandedTargets;\n \n bagIndices = dsMil.getBagInds;\n uniqueBagIndices = unique(bagIndices);\n \n d = size(x,2);\n \n self.v_0_m = d+2;\n self.v_1_m = d+2;\n self.beta_1_m = d;\n self.beta_0_m = d;\n self.rho_0_0 = zeros(1,d);\n self.rho_0_1 = zeros(1,d);\n \n self.Phi_0_0 = eye(d)*d;\n self.Phi_0_1 = eye(d)*d;\n \n% params = struct('K0',5,'K1',5,'gamma_0_1_m0',1,'gamma_0_2_m0',.001,'gamma_0_1_m1',1,'gamma_0_2_m1',.001,...\n% 'v_0_m',d+2,'v_1_m',d+2,'beta_1_m',d,'beta_0_m',d, ...\n% 'rho_0_1',zeros(1,d),'rho_0_0',zeros(1,d),'Phi_0_1',eye(d)*d,'Phi_0_0',eye(d)*d,'alpha',[4 1]*10000);\n \n \n [rvH0,rvH1,xH0,xH1] = initialize(self,{milStruct.data},bagLabels);\n %self.initialFit = self.calculateDataLogLikelihood(self,xH0,xH1);\n ll0 = sum(rvH0.logPdf(xH0));\n ll1 = rvH0.pdf(xH1).*self.alpha(1)/sum(self.alpha) + rvH1.pdf(xH1).*self.alpha(2)/sum(self.alpha);\n self.initialFit = ll0 + sum(log(ll1));\n \n \n [p0,pp] = rvH0.pdf(x);\n phi_0_i = bsxfun(@rdivide,pp,sum(pp,2));\n \n [p1,pp] = rvH1.pdf(x);\n phi_1_i = bsxfun(@rdivide,pp,sum(pp,2));\n phi_1_i(expandedBagLabels == 0,:) = 0;\n p1(expandedBagLabels ==0) = 0;\n \n phi_1_M = p1./(p0 + p1);\n phi_0_M = 1-phi_1_M;\n \n \n locEps = 1e-6;\n \n for vbIter = 1:self.maxVbIter\n %Equations 67 and 68; note, these are different from 20-21 (!)\n % gamma_i_1_m0 = sum(bsxfun(@times,phi_0_M,phi_0_i)) + self.gamma_0_1_m0;\n % gamma_i_2_m0 = cat(2,0,cumsum(gamma_i_1_m0(1:end-1),2)) + self.gamma_0_2_m0;\n %\n % gamma_i_1_m1 = sum(bsxfun(@times,phi_1_M,phi_1_i)) + self.gamma_0_1_m1;\n % gamma_i_2_m1 = cat(2,0,cumsum(gamma_i_1_m1(1:end-1),2)) + self.gamma_0_2_m1;\n \n %Equations 20-21\n gamma_i_1_m0 = sum(bsxfun(@times,phi_0_M,phi_0_i)) + self.gamma_0_1_m0;\n gamma_i_2_m0 = fliplr(cumsum(fliplr(gamma_i_1_m0))) - gamma_i_1_m0 + self.gamma_0_2_m0;\n \n gamma_i_1_m1 = sum(bsxfun(@times,phi_1_M,phi_1_i)) + self.gamma_0_1_m1;\n gamma_i_2_m1 = fliplr(cumsum(fliplr(gamma_i_1_m1))) - gamma_i_1_m1 + self.gamma_0_2_m1;\n \n %Update priors... H0 Gaussian; Equations 77-79 (H0)\n respMat = bsxfun(@times,phi_0_M,phi_0_i);\n nBar0 = sum(respMat)+locEps; %avoid 1./0 problems\n for cluster = 1:self.K0\n mu_i_0(cluster,:) = 1/nBar0(cluster)*sum(bsxfun(@times,respMat(:,cluster),x));\n \n xx = bsxfun(@times,sqrt(respMat(:,cluster)),bsxfun(@minus,x,mu_i_0(cluster,:)));\n c = 1/nBar0(cluster)*xx'*xx;\n cov_i_0(cluster,:) = c(:);\n end\n \n %Update priors... H1 Gaussian; Equations 77-79\n respMat = bsxfun(@times,phi_1_M,phi_1_i);\n nBar1 = sum(respMat)+locEps;\n for cluster = 1:self.K1\n mu_i_1(cluster,:) = 1/nBar1(cluster)*sum(bsxfun(@times,respMat(:,cluster),x));\n \n xx = bsxfun(@times,sqrt(respMat(:,cluster)),bsxfun(@minus,x,mu_i_1(cluster,:)));\n c = 1/nBar1(cluster)*xx'*xx;\n cov_i_1(cluster,:) = c(:);\n end\n \n %Updating hyper-parameters; eqns 81-84\n nu_0 = self.v_0_m + nBar0;\n nu_1 = self.v_1_m + nBar1;\n \n beta_0 = self.beta_0_m + nBar0;\n beta_1 = self.beta_1_m + nBar1;\n \n \n for cluster = 1:self.K0\n rho_0(cluster,:) = self.beta_0_m*self.rho_0_0 + nBar0(cluster)*mu_i_0(cluster,:);\n rho_0(cluster,:) = rho_0(cluster,:)./beta_0(cluster);\n \n %See equation 84; Note: this is different from Equation 84 - 84 is\n %wrong\n %covPart = nBar0(cluster) * reshape(cov_i_0(cluster,:),d,d) * ((mu_i_0(cluster,:) - rho_0(cluster,:))'*(mu_i_0(cluster,:) - rho_0(cluster,:)));\n covPart = nBar0(cluster) * self.beta_0_m * ((mu_i_0(cluster,:) - self.rho_0_0)'*(mu_i_0(cluster,:) - self.rho_0_0));\n covPart = covPart ./ beta_0(cluster);\n \n phiCov = self.Phi_0_0 + nBar0(cluster)*reshape(cov_i_0(cluster,:),d,d) + covPart;\n Phi_0(cluster,:) = phiCov(:)';\n end\n \n for cluster = 1:self.K1\n rho_1(cluster,:) = self.beta_1_m*self.rho_0_1 + nBar1(cluster)*mu_i_1(cluster,:);\n rho_1(cluster,:) = rho_1(cluster,:)./beta_1(cluster);\n \n %See equation 84; Note: this is different from Equation 84 - 84 is\n %wrong\n %covPart = nBar1(cluster) * reshape(cov_i_1(cluster,:),d,d) * ((mu_i_1(cluster,:) - rho_1(cluster,:))'*(mu_i_1(cluster,:) - rho_1(cluster,:)));\n % covPart = nBar1(cluster) * reshape(cov_i_1(cluster,:),d,d) * ((mu_i_1(cluster,:) - self.rho_0_0)'*(mu_i_1(cluster,:) - self.rho_0_0));\n covPart = nBar1(cluster) * self.beta_1_m * ((mu_i_1(cluster,:) - self.rho_0_1)'*(mu_i_1(cluster,:) - self.rho_0_1));\n covPart = covPart ./ beta_1(cluster);\n \n phiCov = self.Phi_0_1 + nBar1(cluster)*reshape(cov_i_1(cluster,:),d,d) + covPart;\n Phi_1(cluster,:) = phiCov(:)';\n end\n \n % Equation 102\n matGamma = psi(gamma_i_1_m0) - psi(gamma_i_1_m0 + gamma_i_2_m0);\n matGamma2 = psi(gamma_i_2_m0) - psi(gamma_i_1_m0 + gamma_i_2_m0);\n log_pi_0 = matGamma + cat(2,0,cumsum(matGamma2(1:end-1)));\n \n matGamma = psi(gamma_i_1_m1) - psi(gamma_i_1_m1 + gamma_i_2_m1);\n matGamma2 = psi(gamma_i_2_m1) - psi(gamma_i_1_m1 + gamma_i_2_m1);\n log_pi_1 = matGamma + cat(2,0,cumsum(matGamma2(1:end-1)));\n \n \n % Equation 105\n nBarM0 = self.alpha(1) + sum(phi_0_M(expandedBagLabels == 1,:));\n nBarM1 = self.alpha(2) + sum(phi_1_M(expandedBagLabels == 1,:));\n log_eta = psi([nBarM0,nBarM1]) - psi(nBarM1+nBarM0);\n \n % \n for cluster = 1:self.K0\n temp_det0 = sum(psi((nu_0(cluster) + 1 - (1:d))/2));\n temp_det0 = temp_det0 + d*log(2);\n log_det_0(cluster) = temp_det0 + log(det(reshape(Phi_0(cluster,:),d,d)^-1));\n end\n for cluster = 1:self.K1\n temp_det1 = sum(psi((nu_1(cluster) + 1 - (1:d))/2));\n temp_det1 = temp_det1 + d*log(2);\n log_det_1(cluster) = temp_det1 + log(det(reshape(Phi_1(cluster,:),d,d)^-1));\n end\n \n \n %Equatioin 113\n for cluster = 1:self.K0\n c = reshape(Phi_0(cluster,:),d,d);\n % v = prtUtilCalcDiagXcInvXT(bsxfun(@minus,x,mu_i_0(cluster,:)),c);\n v = prtUtilCalcDiagXcInvXT(bsxfun(@minus,x,rho_0(cluster,:)),c);\n inner_0_n(:,cluster) = d/beta_0(cluster) + nu_0(cluster).*v;\n end\n \n for cluster = 1:self.K1\n c = reshape(Phi_1(cluster,:),d,d);\n % v = prtUtilCalcDiagXcInvXT(bsxfun(@minus,x,mu_i_1(cluster,:)),c);\n v = prtUtilCalcDiagXcInvXT(bsxfun(@minus,x,rho_1(cluster,:)),c);\n inner_1_n(:,cluster) = d/beta_1(cluster) + nu_1(cluster).*v;\n end\n \n for cluster = 1:self.K0\n eLogPdf0(:,cluster) = -d*log(2*pi) + log_det_0(cluster) - inner_0_n(:,cluster);\n end\n eLogPdf0 = eLogPdf0*1/2;\n \n for cluster = 1:self.K1\n eLogPdf1(:,cluster) = -d*log(2*pi) + log_det_1(cluster) - inner_1_n(:,cluster);\n end\n eLogPdf1 = eLogPdf1*1/2;\n \n phiHat0 = bsxfun(@plus,eLogPdf0,log_pi_0);\n phiHat1 = bsxfun(@plus,eLogPdf1,log_pi_1);\n phiHat1(expandedBagLabels == 0,:) = -inf;\n \n phi_1_i = bsxfun(@rdivide,exp(phiHat1),sum(exp(phiHat1),2));\n phi_0_i = bsxfun(@rdivide,exp(phiHat0),sum(exp(phiHat0),2));\n \n phi_1_i(exp(phiHat1) == 0) = 0;\n phi_0_i(exp(phiHat0) == 0) = 0;\n \n %\n n1 = (log(sum(exp(phiHat1),2))+log_eta(2));\n n0 = (log(sum(exp(phiHat0),2))+log_eta(1));\n phi_1_M = exp(n1)./(exp(n1)+exp(n0));\n phi_1_M(expandedBagLabels == 0) = 0;\n \n phi_0_M = 1-phi_1_M;\n \n for i = 1:size(rho_0,1)\n c = Phi_0(i,:)./nu_0(i);\n c = reshape(c,d,d);\n if vbIter == 1\n mm0(i) = prtRvMvn('mu',rho_0(i,:),'sigma',c);\n else\n mm0(i).mu = rho_0(i,:);\n mm0(i).sigma = c;\n end\n end\n for i = 1:size(rho_1,1)\n c = Phi_1(i,:)./nu_1(i);\n c = reshape(c,d,d);\n if vbIter == 1\n mm1(i) = prtRvMvn('mu',rho_1(i,:),'sigma',c);\n else\n mm1(i).mu = rho_1(i,:);\n mm1(i).sigma = c;\n end\n end\n \n pi0 = exp(log_pi_0); pi0 = pi0./sum(pi0);\n rv0 = prtRvGmm('nComponents',size(mu_i_0,1),'mixingProportions',pi0,'components',mm0);\n \n pi1 = exp(log_pi_1); pi1 = pi1./sum(pi1);\n rv1 = prtRvGmm('nComponents',size(mu_i_1,1),'mixingProportions',pi1,'components',mm1);\n \n \n self.rvH1 = rv1;\n self.rvH0 = rv0;\n \n drawnow;\n if ~mod(vbIter,100);\n disp(vbIter)\n subplot(2,4,1);\n stem(exp(log_pi_0));\n subplot(2,4,2);\n stem(exp(log_eta))\n subplot(2,4,3);\n stem(exp(log_pi_1));\n fprintf('exp(log_pi_0): %.2f\\n',exp(log_pi_0))\n fprintf('exp(log_pi_1): %.2f\\n',exp(log_pi_1))\n \n \n subplot(2,4,4);\n self.isTrained = true;\n yOut = self.run(dsMil);\n prtScoreRoc(yOut);\n \n subplot(2,4,5:8);\n if d > 1\n plot(x(expandedBagLabels == 0,1),x(expandedBagLabels == 0,2),'b.');\n hold on;\n plot(x(expandedBagLabels == 1,1),x(expandedBagLabels == 1,2),'r.');\n \n for i = 1:size(rho_0,1)\n c = Phi_0(i,:)./nu_0(i);\n c = reshape(c,d,d);\n if d > 1\n % plotMvnEllipse(rho_0(i,1:2),c(1:2,1:2),1);\n end\n mm0(i) = prtRvMvn('mu',rho_0(i,:),'sigma',c);\n end\n for i = 1:size(rho_1,1)\n c = Phi_1(i,:)./nu_1(i);\n c = reshape(c,d,d);\n if d > 1\n % plotMvnEllipse(rho_1(i,1:2),c(1:2,1:2),1);\n end\n mm1(i) = prtRvMvn('mu',rho_1(i,:),'sigma',c);\n end\n hold on; h = plot(rho_0(:,1),rho_0(:,2),'ko'); set(h,'MarkerFaceColor','k');\n hold on; h = plot(rho_1(:,1),rho_1(:,2),'go'); set(h,'MarkerFaceColor','g');\n \n hold off;\n end\n drawnow;\n end\n \n end\n end\n \n function yOut = runAction(self,dsMil)\n \n for n = 1:dsMil.nObservations\n milStruct = dsMil.data(n);\n data = milStruct.data; \n \n h1 = self.rvH1.logPdf(data);\n h0 = self.rvH0.logPdf(data);\n l0 = h0'-prtUtilSumExp([h0';h1']);\n \n h0LogProbabilityBag = sum(l0);\n %exp(h0LogProbabilityBag)\n \n y(n,1) = 1-exp(h0LogProbabilityBag);\n end\n \n yOut = prtDataSetClass(y,dsMil.targets);\n end\n \n function [h0Mix,h1Mix,xH0,xH1] = initialize(self,xBag,bagLabels)\n \n %H0 Kmeans\n xH0 = cat(1,xBag{bagLabels == 0});\n idx0 = kmeans(xH0,self.K0,'Replicates',1,'EmptyAction','singleton','MaxIter',100);\n uIds = unique(idx0);\n \n for idx = 1:length(uIds)\n rvH0struct(idx).mean = mean(xH0(idx0 == idx,:),1);\n \n try\n rvH0struct(idx).cov = cov(xH0(idx0 == idx,:));\n chol(rvH0struct(idx).cov);\n assert(size(xH0,2) == size(rvH0struct(idx).cov,2)); \n catch ME\n rvH0struct(idx).cov = diag(var(xH0(idx0 == idx,:))) + eye(size(xH0,2));\n end\n \n rvH0(idx) = prtRvMvn('mu',rvH0struct(idx).mean,'sigma',rvH0struct(idx).cov);\n pi(idx) = sum(idx0 == idx)./length(idx0);\n \n end\n pi = pi./sum(pi);\n h0Mix = prtRvGmm('nComponents',length(rvH0),'mixingProportions',pi,'components',rvH0);\n \n %Least likely H1\n h1Bags = xBag(bagLabels == 1);\n for h1Ind = 1:length(h1Bags)\n ll = h0Mix.logPdf(h1Bags{h1Ind});\n [~,ind] = min(ll);\n xH1(h1Ind,:) = h1Bags{h1Ind}(ind,:);\n end\n \n %H1 Kmeans\n idx1 = kmeans(xH1,self.K1,'Replicates',1,'EmptyAction','singleton','MaxIter',100);\n uIds = unique(idx1);\n \n pi = [];\n for idx = 1:length(uIds)\n rvH1struct(idx).mean = mean(xH1(idx1 == idx,:),1);\n \n try\n rvH1struct(idx).cov = cov(xH1(idx0 == idx,:));\n chol(rvH1struct(idx).cov);\n catch ME\n rvH1struct(idx).cov = diag(var(xH1)) + eye(size(xH1,2));\n end\n \n rvH1(idx) = prtRvMvn('mu',rvH1struct(idx).mean,'sigma',rvH1struct(idx).cov);\n pi(idx) = sum(idx1 == idx)./length(idx1);\n \n end\n pi = pi./sum(pi);\n h1Mix = prtRvGmm('nComponents',length(rvH1),'mixingProportions',pi,'components',rvH1);\n end\n end\nend\n", "meta": {"author": "covartech", "repo": "PRT", "sha": "4305e612af048e7dbf3d9392efc7436db125b1fc", "save_path": "github-repos/MATLAB/covartech-PRT", "path": "github-repos/MATLAB/covartech-PRT/PRT-4305e612af048e7dbf3d9392efc7436db125b1fc/multipleInstance/prtClassMilVbDpGmm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.682573734412324, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.34928431383371716}} {"text": "function [cl,cd] = bpolar(BladeState,AC)\n% To make your own bpolar:\n% BladeState is the state of the blade element with matrix components:\n% BladeState =\n% M: Mach number\n% alpha: angle of attack (radians)\n% r: radius location (nondimensional)\n% psi: azimuth location (radians)\n% alphadot: rate of change of angle of attack (rad/s)\n% Re: Reynolds number\n% all components on BladeState inputs are m x n, where n is the number of\n% blade elements, and m is the uniformly distributed number of azimuth\n% elements.\n%\n% NB: this function should run VERY fast, so avoid loops and extensive\n% interpolation.\n% see also lininterp1f\n%\n% AC is a structure with AC data (see documentation)\n%\n% cl and cd are the m x n arrays containing each blade element's lift and\n% drag coefficients.\n% note that output coefficients will be non-dimensionalized by a constant\n% blade chord, typically the average blade chord.\n%\n% The blade polar function is responsible for capturing all important rotor\n% phenomena, including reverse flow, retreating blade stall, and advancing\n% tip critical mach number.\n%\n% to capture reverse flow effects, the drag polar should be able to handle\n% alphas +/- 360 deg\n%\n% critical mach drag rise and stall should also be modeled.\n\n% This file is an example of using wind tunnel data (NACA 0012), very fast\n% interpolation, and a critical mach drag rise approximation.\n\n\n% Drag Coefficient data\n%from http://www.cyberiad.net\n% -------------------------------- REYNOLDS NUMBER -----------------------\n\n% RE = [5000000] ;\n\nDragData = [ 0.0064\n 0.0064\n 0.0066\n 0.0068\n 0.0072\n 0.0076\n 0.0081\n 0.0086\n 0.0092\n 0.0098\n 0.0106\n 0.0118\n 0.0130\n 0.0143\n 0.0159\n 0.0177\n 0.0198\n 0.0229\n 0.1480\n 0.2740\n 0.2970\n 0.3200\n 0.3440\n 0.3690\n 0.3940\n 0.4200\n 0.4460\n 0.4730\n 0.5700\n 0.7450\n 0.9200\n 1.0750\n 1.2150\n 1.3450\n 1.4700\n 1.5750\n 1.6650\n 1.7350\n 1.7800\n 1.8000\n 1.8000\n 1.7800\n 1.7500\n 1.7000\n 1.6350\n 1.5550\n 1.4650\n 1.3500\n 1.2250\n 1.0850\n 0.9250\n 0.7550\n 0.5750\n 0.4200\n 0.3200\n 0.2300\n 0.1400\n 0.0550\n 0.0250\n 0.0550\n 0.1400\n 0.2300\n 0.3200\n 0.4200\n 0.5750\n 0.7550\n 0.9250\n 1.0850\n 1.2250\n 1.3500\n 1.4650\n 1.5550\n 1.6350\n 1.7000\n 1.7500\n 1.7800\n 1.8000\n 1.8000\n 1.7800\n 1.7350\n 1.6650\n 1.5750\n 1.4700\n 1.3450\n 1.2150\n 1.0750\n 0.9200\n 0.7450\n 0.5700\n 0.4730\n 0.4460\n 0.4200\n 0.3940\n 0.3690\n 0.3440\n 0.3200\n 0.2970\n 0.2740\n 0.1480\n 0.0229\n 0.0198\n 0.0177\n 0.0159\n 0.0143\n 0.0130\n 0.0118\n 0.0106\n 0.0098\n 0.0092\n 0.0086\n 0.0081\n 0.0076\n 0.0072\n 0.0068\n 0.0066\n 0.0064\n 0.0064];\nLiftData =[ 0\n 0.1100\n 0.2200\n 0.3300\n 0.4400\n 0.5500\n 0.6600\n 0.7700\n 0.8800\n 0.9900\n 1.1000\n 1.1842\n 1.2673\n 1.3242\n 1.3423\n 1.3093\n 1.2195\n 1.0365\n 0.9054\n 0.8412\n 0.8233\n 0.8327\n 0.8563\n 0.8903\n 0.9295\n 0.9718\n 1.0193\n 1.0680\n 0.9150\n 1.0200\n 1.0750\n 1.0850\n 1.0400\n 0.9650\n 0.8750\n 0.7650\n 0.6500\n 0.5150\n 0.3700\n 0.2200\n 0.0700\n -0.0700\n -0.2200\n -0.3700\n -0.5100\n -0.6250\n -0.7350\n -0.8400\n -0.9100\n -0.9450\n -0.9450\n -0.9100\n -0.8500\n -0.7400\n -0.6600\n -0.6750\n -0.8500\n -0.6900\n 0\n 0.6900\n 0.8500\n 0.6750\n 0.6600\n 0.7400\n 0.8500\n 0.9100\n 0.9450\n 0.9450\n 0.9100\n 0.8400\n 0.7350\n 0.6250\n 0.5100\n 0.3700\n 0.2200\n 0.0700\n -0.0700\n -0.2200\n -0.3700\n -0.5150\n -0.6500\n -0.7650\n -0.8750\n -0.9650\n -1.0400\n -1.0850\n -1.0750\n -1.0200\n -0.9150\n -1.0680\n -1.0193\n -0.9718\n -0.9295\n -0.8903\n -0.8563\n -0.8327\n -0.8233\n -0.8412\n -0.9054\n -1.0365\n -1.2195\n -1.3093\n -1.3423\n -1.3242\n -1.2673\n -1.1842\n -1.1000\n -0.9900\n -0.8800\n -0.7700\n -0.6600\n -0.5500\n -0.4400\n -0.3300\n -0.2200\n -0.1100\n 0];\nAlpha =[0\n 1\n 2\n 3\n 4\n 5\n 6\n 7\n 8\n 9\n 10\n 11\n 12\n 13\n 14\n 15\n 16\n 17\n 18\n 19\n 20\n 21\n 22\n 23\n 24\n 25\n 26\n 27\n 30\n 35\n 40\n 45\n 50\n 55\n 60\n 65\n 70\n 75\n 80\n 85\n 90\n 95\n 100\n 105\n 110\n 115\n 120\n 125\n 130\n 135\n 140\n 145\n 150\n 155\n 160\n 165\n 170\n 175\n 180\n 185\n 190\n 195\n 200\n 205\n 210\n 215\n 220\n 225\n 230\n 235\n 240\n 245\n 250\n 255\n 260\n 265\n 270\n 275\n 280\n 285\n 290\n 295\n 300\n 305\n 310\n 315\n 320\n 325\n 330\n 333\n 334\n 335\n 336\n 337\n 338\n 339\n 340\n 341\n 342\n 343\n 344\n 345\n 346\n 347\n 348\n 349\n 350\n 351\n 352\n 353\n 354\n 355\n 356\n 357\n 358\n 359\n 360]*pi/180;\nmodinpcount = 0;\nwhile any(BladeState.alpha(:)<0)\n ind = BladeState.alpha<0;\n BladeState.alpha(ind) = BladeState.alpha(ind)+2*pi;\n modinpcount=modinpcount+1;\nend\nif modinpcount>2\n disp('crazy stuff going on in bpolar - very very negative alphas')\nend\nmodinpcount = 0;\nwhile any(BladeState.alpha(:)>2*pi)\n ind = BladeState.alpha>2*pi;\n BladeState.alpha(ind) = BladeState.alpha(ind)-2*pi;\n modinpcount=modinpcount+1;\nend\nif modinpcount>1\n disp('crazy stuff going on in bpolar - very very positive alphas')\nend\ncd = mylerp1(Alpha,DragData,BladeState.alpha);%,'linear');\ncl = mylerp1(Alpha,LiftData,BladeState.alpha);%,'linear');\nif any(isnan([cd(:);cl(:)]));\n disp(' check this out')\nend\n% Data from http://adg.stanford.edu/aa241/drag/dragrise.html\n% at Cl of .3\n% M-Mcrit:\nMdiff0 =[ -1\n -0.15\n -0.125\n -0.1\n -0.075\n -0.05\n -0.025\n 0\n 0.025\n 0.05\n 0.075\n 0.1\n 0.125\n 0.15\n 0.175\n 0.2\n 0.225\n 10000.225];\n\nCdinvisc =[0\n 0\n 0\n 0.000025\n 0.00005\n 0.00015\n 0.0005\n 0.002\n 0.0052\n 0.0103\n 0.0173\n 0.026\n 0.037\n 0.048\n 0.068\n 0.1\n 0.148\n 20000];\n\nMcrit = max(.55,-.02002*abs(BladeState.alpha)+.765);\n% from ESDU AERO W.00.03.01\n% Critical Mach number for high speed aerofoil sections.\n\ncd = cd + mylerp1(Mdiff0,Cdinvisc,abs(BladeState.M)-Mcrit);\n\n%tip loss\nind = BladeState.r>.97;\ncl(ind)=cl(ind).*(1-(BladeState.r(ind)-.97)/.03);\n\n%% root cutout\ncl(BladeState.r<.15) = 0;\ncd(BladeState.r<.15) = .1;\n\nif any([isnan(cl(:)) isnan(cd(:))])\n disp('NaN in bpolar function')\n cd(isnan(cd)) = 1;\n cl(isnan(cl)) = 1;\nend\n\nend\n\nfunction yi = mylerp1(x,y,xi)\n% Y = interp1(x,y,X,'linear');\n\ntoreshape = size(xi);\nxi = xi(:);\nyi = lininterp1f(x,y,xi,NaN); %mex .dll function\nyi = reshape(yi,toreshape);\n\nend", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/41725-core-conceptual-optimization-of-rotorcraft-environment/CORE_v0p7 - for upload may 2013/toolbox/bpolar_0012.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.3491559019158495}} {"text": "% Scrip: mcgrid.m\n% Calculates Magnitude shift map for two specific time periods\n% Uses view_mcgrid to plot the results\n%\n% J. Woessner\n% last update: 22.01.04\n\nreport_this_filefun(mfilename('fullpath'));\n\n\nglobal no1 bo1 inb1 inb2 valeg valeg2 CO valm1\n\nvaleg = 1;\nvalm1 = min(a.Magnitude);\nprf = NaN;\nif sel == 'in'\n % Set the grid parameter\n %Initial values\n dx = 1;\n dy = 1;\n ni = 150;\n Nmin = 150;\n ra = 50;\n fMaxRadius = 5;\n fSplitTime = 2000.4;\n\n % cut catalog at mainshock time:\n% l = a.Date > maepi(1,3);\n% a = a.subset(l);\n\n % cat at selecte magnitude threshold\n l = a.Magnitude < valm1;\n a(l,:) = [];\n newt2 = a;\n\n ho2=true;\n timeplot\n ho2=false;\n\n\n %The definitions in the following line were present in the initial bvalgrid.m file.\n %stan2 = NaN; stan = NaN; prf = NaN; av = NaN;\n\n % make the interface\n % creates a dialog box to input grid parameters\n %\n figure_w_normalized_uicontrolunits(...\n 'Name','Grid Input Parameter',...\n 'NumberTitle','off', ...\n 'MenuBar','none', ...\n 'NextPlot','new', ...\n 'units','points',...\n 'Visible','off', ...\n 'Position',[ wex+200 wey-200 650 250]);\n axis off\n% labelList2=[' Automatic Mcomp (max curvature) | Fixed Mc (Mc = Mmin) | Automatic Mcomp (90% probability) | Automatic Mcomp (95% probability) | Best (?) combination (Mc95 - Mc90 - max curvature) | Constant Mc'];\n% labelPos = [0.2 0.8 0.6 0.08];\n% hndl2=uicontrol(...\n% 'Style','popup',...\n% 'Position',labelPos,...\n% 'Units','normalized',...\n% 'String',labelList2,...\n% 'Callback','inb2 =get(hndl2,''Value''); ');\n%\n% set(hndl2,'value',5);\n\n\n % creates a dialog box to input grid parameters\n %\n\n oldfig_button = uicontrol('BackGroundColor',[.60 .92 .84], ...\n 'Style','checkbox','string','Plot in Current Figure',...\n 'Position',[.78 .7 .20 .08],...\n 'Units','normalized');\n\n set(oldfig_button,'value',1);\n\n\n freq_field=uicontrol('Style','edit',...\n 'Position',[.30 .60 .12 .08],...\n 'Units','normalized','String',num2str(ni),...\n 'Callback','ni=str2double(get(freq_field,''String'')); set(freq_field,''String'',num2str(ni));set(tgl2,''value'',0); set(tgl1,''value'',1)');\n\n\n freq_field0=uicontrol('Style','edit',...\n 'Position',[.30 .50 .12 .08],...\n 'Units','normalized','String',num2str(ra),...\n 'Callback','ra=str2double(get(freq_field0,''String'')); set(freq_field0,''String'',num2str(ra)) ; set(tgl2,''value'',1); set(tgl1,''value'',0)');\n\n freq_field2=uicontrol('Style','edit',...\n 'Position',[.30 .40 .12 .08],...\n 'Units','normalized','String',num2str(dx),...\n 'Callback','dx=str2double(get(freq_field2,''String'')); set(freq_field2,''String'',num2str(dx));');\n\n freq_field3=uicontrol('Style','edit',...\n 'Position',[.30 .30 .12 .080],...\n 'Units','normalized','String',num2str(dy),...\n 'Callback','dy=str2double(get(freq_field3,''String'')); set(freq_field3,''String'',num2str(dy));');\n\n freq_field4=uicontrol('Style','edit',...\n 'Position',[.6 .30 .12 .080],...\n 'Units','normalized','String',num2str(fSplitTime),...\n 'Callback','fSplitTime=str2double(get(freq_field4,''String'')); set(freq_field4,''String'',num2str(fSplitTime));');\n\n freq_field7=uicontrol('Style','edit',...\n 'Position',[.30 .20 .12 .080],...\n 'Units','normalized','String',num2str(Nmin),...\n 'Callback','Nmin=str2double(get(freq_field7,''String'')); set(freq_field7,''String'',num2str(Nmin));');\n\n freq_field8=uicontrol('Style','edit',...\n 'Position',[.6 .60 .12 .080],...\n 'Units','normalized','String',num2str(fMaxRadius),...\n 'Callback','fMaxRadius=str2double(get(freq_field8,''String'')); set(freq_field8,''String'',num2str(fMaxRadius));');\n\n tgl1 = uicontrol('Style','radiobutton',...\n 'string','Number of Events:',...\n 'Position',[.05 .60 .2 .0800], 'Callback','set(tgl2,''value'',0)',...\n 'Units','normalized');\n\n set(tgl1,'value',0);\n\n tgl2 = uicontrol('Style','radiobutton',...\n 'string','OR: Constant Radius',...\n 'Position',[.05 .50 .2 .080], 'Callback','set(tgl1,''value'',0)',...\n 'Units','normalized');\n set(tgl2,'value',1);\n\n create_grid = uicontrol('Style','radiobutton',...\n 'string','Calculate a new grid', 'Callback','set(load_grid,''value'',0), set(prev_grid,''value'',0)','Position',[.78 .55 .2 .080],...\n 'Units','normalized');\n\n set(create_grid,'value',1);\n\n prev_grid = uicontrol('Style','radiobutton',...\n 'string','Reuse the previous grid', 'Callback','set(load_grid,''value'',0),set(create_grid,''value'',0)','Position',[.78 .45 .2 .080],...\n 'Units','normalized');\n\n\n load_grid = uicontrol('Style','radiobutton',...\n 'string','Load a previously saved grid', 'Callback','set(prev_grid,''value'',0),set(create_grid,''value'',0)','Position',[.78 .35 .2 .080],...\n 'Units','normalized');\n\n save_grid = uicontrol('Style','checkbox',...\n 'string','Save selected grid to file',...\n 'Position',[.78 .22 .2 .080],...\n 'Units','normalized');\n\n\n\n close_button=uicontrol('Style','Pushbutton',...\n 'Position',[.60 .05 .15 .12 ],...\n 'Units','normalized','Callback','close;done','String','Cancel');\n\n go_button1=uicontrol('Style','Pushbutton',...\n 'Position',[.20 .05 .15 .12 ],...\n 'Units','normalized',...\n 'Callback','tgl1 =get(tgl1,''Value'');tgl2 =get(tgl2,''Value'');prev_grid = get(prev_grid,''Value'');create_grid = get(create_grid,''Value''); load_grid = get(load_grid,''Value''); save_grid = get(save_grid,''Value''); oldfig_button = get(oldfig_button,''Value''); close,sel =''ca'', mc_grid',...\n 'String','Go');\n\n text(...\n 'Color',[0 0 0 ],...\n 'EraseMode','normal',...\n 'Position',[0.10 0.98 0 ],...\n 'Rotation',0 ,...\n 'FontSize',ZmapGlobal.Data.fontsz.l ,...\n 'FontWeight','bold',...\n 'String','Please choose an Mc estimation option ');\n txt3 = text(...\n 'Color',[0 0 0 ],...\n 'EraseMode','normal',...\n 'Position',[0.30 0.75 0 ],...\n 'Rotation',0 ,...\n 'FontSize',ZmapGlobal.Data.fontsz.l ,...\n 'FontWeight','bold',...\n 'String',' Grid Parameter');\n txt5 = text(...\n 'Color',[0 0 0 ],...\n 'EraseMode','normal',...\n 'Position',[-0.1 0.4 0 ],...\n 'Rotation',0 ,...\n 'FontSize',ZmapGlobal.Data.fontsz.m ,...\n 'FontWeight','bold',...\n 'String','Spacing in x (dx) in deg:');\n\n txt6 = text(...\n 'Color',[0 0 0 ],...\n 'EraseMode','normal',...\n 'Position',[-0.1 0.3 0 ],...\n 'Rotation',0 ,...\n 'FontSize',ZmapGlobal.Data.fontsz.m ,...\n 'FontWeight','bold',...\n 'String','Spacing in y (dy) in deg:');\n\n txt7 = text(...\n 'Color',[0 0 0 ],...\n 'EraseMode','normal',...\n 'Position',[-0.1 0.18 0 ],...\n 'Rotation',0 ,...\n 'FontSize',ZmapGlobal.Data.fontsz.m ,...\n 'FontWeight','bold',...\n 'String','Min. No. of events > Mc:');\n\n txt9 = text(...\n 'Color',[0 0 0 ],...\n 'EraseMode','normal',...\n 'Position',[0.42 0.28 0 ],...\n 'Rotation',0 ,...\n 'FontSize',ZmapGlobal.Data.fontsz.s ,...\n 'FontWeight','bold',...\n 'String','Time window:');\n\n txt11 = text(...\n 'Color',[0 0 0 ],...\n 'EraseMode','normal',...\n 'Position',[0.42 0.62 0 ],...\n 'Rotation',0 ,...\n 'FontSize',ZmapGlobal.Data.fontsz.s ,...\n 'FontWeight','bold',...\n 'String','Max. Radius /[km]:');\n\n set(gcf,'visible','on');\n watchoff\n\nend % if nargin ==0\n\n% get the grid-size interactively and\n% calculate the b-value in the grid by sorting\n% thge seimicity and selectiong the ni neighbors\n% to each grid point\n\nif sel == 'ca'\n\n\n\n %In the following line, the program .m is called, which creates a rectangular grid from which then selects,\n %on the basis of the vector ll, the points within the selected poligon.\n\n % get new grid if needed\n if load_grid == 1\n [file1,path1] = uigetfile(['*.mat'],'previously saved grid');\n if length(path1) > 1\n think\n load([path1 file1])\n end\n plot(newgri(:,1),newgri(:,2),'k+')\n elseif load_grid ==0 && prev_grid == 0\n selgp\n if length(gx) < 2 || length(gy) < 2\n errordlg('Selection too small! (Dx and Dy are in degreees! ');\n return\n end\n elseif prev_grid == 1\n plot(newgri(:,1),newgri(:,2),'k+')\n end\n % end\n\n gll = ll;\n\n if save_grid == 1\n\n sFile = ['*.mat'];\n sPath = pwd;\n [file1,path1] = uiputfile([sFile], 'Grid File Name?');\n sSaveFile = [path1 file1];\n save(sSaveFile, 'newgri', 'dx', 'dy', 'gx', 'gy', 'xvect', 'yvect', 'tmpgri', 'll', 'fSplitTime', 'Nmin', 'ra', 'a');\n end\n\n % selgp\n itotal = length(newgri(:,1));\n% if length(gx) < 4 | length(gy) < 4\n% errordlg('Selection too small! (Dx and Dy are in degreees! ');\n% return\n% end\n\n zmap_message_center.set_info(' ','Running... ');think\n % make grid, calculate start- endtime etc. ...\n %\n t0b = min(a.Date) ;\n n = a.Count;\n teb = a(n,3) ;\n tdiff = round((teb - t0b)*365/par1);\n loc = zeros(3, length(gx)*length(gy));\n\n % loop over all points\n %\n i1 = 0.;\n mRes =[];\n mResult = [];\n allcount = 0.;\n wai = waitbar(0,' Please Wait ... ');\n set(wai,'NumberTitle','off','Name','Rate change grid - percent done');\n drawnow\n\n % loop over all points\n for i= 1:length(newgri(:,1))\n i/length(newgri(:,1));\n % Grid node point\n x = newgri(i,1);y = newgri(i,2);\n allcount = allcount + 1.;\n\n\n % calculate distance from center point and sort with distance\n l = sqrt(((a.Longitude-x)*cos(pi/180*y)*111).^2 + ((a.Latitude-y)*111).^2) ;\n [s,is] = sort(l);\n mCat = a(is(:,1),:) ; % re-orders matrix to agree row-wise\n % Use Radius to determine grid node catalogs\n l3 = l <= ra;\n mCat = a.subset(l3); % new data per grid point (mCat) is sorted in distance\n\n\n % % Select earthquakes in non-overlapping rectangles\n % vSel = (a.Longitude >= (newgri(i,1)-dx/2)) & (a.Longitude < (newgri(i,1)+dx/2)) &...\n % (a.Latitude >= (newgri(i,2)-dy/2)) & (a.Latitude < (newgri(i,2)+dy/2));\n % % Select earthquakes in overlapping rectangles\n % vSel = (a.Longitude >= (newgri(i,1)-dx)) & (a.Longitude < (newgri(i,1)+dx)) &...\n % (a.Latitude >= (newgri(i,2)-dy)) & (a.Latitude < (newgri(i,2)+dy));\n % mCat = a.subset(vSel);\n\n % Initialize\n fMinTime = min(mCat(:,3));\n fMaxTime = max(mCat(:,3));\n\n % Select data from 2 time periods\n vSelT = mCat(:,3) < fSplitTime;\n mCat1 = mCat(vSelT,:);\n mCat2 = mCat(~vSelT,:);\n % Length of catalog (resolution)\n nNumevents1 = length(mCat1(:,1));\n nNumevents2 = length(mCat2(:,1));\n\n % Minimum bin: essential for computing difference in FMD\n fMinBin = roundn(min(mCat(:,6)),-1);\n fMaxBin = roundn(max(mCat(:,6)),-1);\n\n if (length(mCat1(:,1)) >=Nmin & length(mCat2(:,1)) >= Nmin)\n % Compute change in FMD normalized by time period\n % Time periods\n fPeriod1 = max(mCat1(:,3))-min(mCat1(:,3));\n fPeriod2 = max(mCat2(:,3))-min(mCat2(:,3));\n [vFMD1, vBin1] = hist(mCat1(:,6),fMinBin:0.1:fMaxBin);\n [vFMD2, vBin2] = hist(mCat2(:,6),fMinBin:0.1:fMaxBin);\n fChFMD = max(cumsum(abs(vFMD2./fPeriod2-vFMD1./fPeriod1)));\n % Calculate shift\n [fMshift, fProbability, fAICc, mProblikelihood, bH] = calc_loglikelihood_dM2(mCat1, mCat2);\n % Check for validity of model using KS-Test result to produce validated result of magnitude shift\n if (bH == 1 | fMshift == 0)\n fMshift_valid = NaN;\n else\n fMshift_valid = fMshift;\n end\n % Calculate Mc\n [mResult1, fMls1, fMc1, fMu1, fSigma1, mDatPredBest1,...\n vPredBest1, fBvalue1, fAvalue1, bH1] = calc_McEMR_kstest(mCat1, 0.1);\n [mResult2, fMls2, fMc2, fMu2, fSigma2, mDatPredBest2,...\n vPredBest2, fBvalue2, fAvalue2, bH2] = calc_McEMR_kstest(mCat2, 0.1);\n % Mc change\n fdMc = fMc2-fMc1;\n if (bH1 ==0 && bH2 == 0)\n fdMc_val = fdMc;\n else\n fdMc_val = NaN;\n end\n % Calculate Utsu-Test\n [dA, fProbEqual, fProbDifferent] = calc_Utsu(fBvalue1, fBvalue2, nNumevents1, nNumevents2);\n % Create result matrix\n mResult = [mResult; i fMshift fProbability fAICc bH nNumevents1 nNumevents2 fMshift_valid fChFMD fMc1 fMc2 fdMc fdMc_val dA fProbEqual fProbDifferent bH1 fBvalue1 fAvalue1 bH2 fBvalue2 fAvalue2];\n else\n % Create result matrix\n mResult = [mResult; i NaN NaN NaN NaN nNumevents1 nNumevents2 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN];\n end\n waitbar(allcount/itotal)\n end % for newgr\n\n % Save the data to rcval_grid.mat\n save mcgrid.mat mResult gx gy dx dy par1 tdiff t0b teb a main faults mainfault coastline yvect xvect tmpgri ll bo1 newgri gll ra maepi fSplitTime\n disp('Saving data to mcgrid.mat in current directory')\n\n close(wai)\n watchoff\n\n normlap2=ones(length(tmpgri(:,1)),1)*nan;\n % Magnitude shift\n normlap2(ll)= mResult(:,2);\n mMagShift = reshape(normlap2,length(yvect),length(xvect));\n\n\n % KS-Test-Value\n normlap2(ll)= mResult(:,5);\n mHkstest = reshape(normlap2,length(yvect),length(xvect));\n\n %%% Resolution parameters\n % Number of events per grid node in first time period\n normlap2(ll)= mResult(:,6);\n mNumevents1 = reshape(normlap2,length(yvect),length(xvect));\n\n % Number of events per grid node in first time period\n normlap2(ll)= mResult(:,7);\n mNumevents2 = reshape(normlap2,length(yvect),length(xvect));\n\n % Validated magnitude shift\n normlap2(ll)= mResult(:,8);\n mMagShift_valid = reshape(normlap2,length(yvect),length(xvect));\n\n % Absolute FMD difference\n normlap2(ll)= mResult(:,9);\n mChFMD = reshape(normlap2,length(yvect),length(xvect));\n\n % Mc Periode 1\n normlap2(ll)= mResult(:,10);\n mMc1 = reshape(normlap2,length(yvect),length(xvect));\n\n % Mc Periode 2\n normlap2(ll)= mResult(:,11);\n mMc2 = reshape(normlap2,length(yvect),length(xvect));\n\n % Mc change\n normlap2(ll)= mResult(:,12);\n mdMc = reshape(normlap2,length(yvect),length(xvect));\n\n % Mc change validated by KS-Test\n normlap2(ll)= mResult(:,13);\n mdMc_val = reshape(normlap2,length(yvect),length(xvect));\n\n % Difference of AIC for Utsu-Test\n normlap2(ll)= mResult(:,14);\n mdAIC_Utsu = reshape(normlap2,length(yvect),length(xvect));\n\n % Probability of stationarity (favoring stationarity)\n normlap2(ll)= mResult(:,15);\n mStationary1_Utsu = reshape(normlap2,length(yvect),length(xvect));\n\n % Probability of stationarity (favoring non-stationarity)\n normlap2(ll)= mResult(:,16);\n mStationary2_Utsu = reshape(normlap2,length(yvect),length(xvect));\n\n % Data to plot first map\n re3 = mMagShift;\n lab1 = 'Magnitude shift';\n\n\n % View the map\n view_mcgrid\n\nend % if sel = na\n\n% Load exist b-grid\nif sel == 'lo'\n [file1,path1] = uigetfile(['*.mat'],'b-value gridfile');\n if length(path1) > 1\n think\n load([path1 file1])\n\n normlap2=ones(length(tmpgri(:,1)),1)*nan;\n\n % Magnitude shift\n normlap2(ll)= mResult(:,2);\n mMagShift = reshape(normlap2,length(yvect),length(xvect));\n\n % KS-Test-Value\n normlap2(ll)= mResult(:,5);\n mHkstest = reshape(normlap2,length(yvect),length(xvect));\n\n %%% Resolution parameters\n % Number of events per grid node in first time period\n normlap2(ll)= mResult(:,6);\n mNumevents1 = reshape(normlap2,length(yvect),length(xvect));\n\n % Number of events per grid node in first time period\n normlap2(ll)= mResult(:,7);\n mNumevents2 = reshape(normlap2,length(yvect),length(xvect));\n\n try\n % Validated magnitude shift\n normlap2(ll)= mResult(:,8);\n mMagShift_valid = reshape(normlap2,length(yvect),length(xvect));\n\n % Absolute FMD difference\n normlap2(ll)= mResult(:,9);\n mChFMD = reshape(normlap2,length(yvect),length(xvect));\n % Mc Periode 1\n normlap2(ll)= mResult(:,10);\n mMc1 = reshape(normlap2,length(yvect),length(xvect));\n\n % Mc Periode 2\n normlap2(ll)= mResult(:,11);\n mMc2 = reshape(normlap2,length(yvect),length(xvect));\n\n % Mc change\n normlap2(ll)= mResult(:,12);\n mdMc = reshape(normlap2,length(yvect),length(xvect));\n\n % Mc change\n normlap2(ll)= mResult(:,13);\n mdMc_val = reshape(normlap2,length(yvect),length(xvect));\n\n % Difference of AIC for Utsu-Test\n normlap2(ll)= mResult(:,14);\n mdAIC_Utsu = reshape(normlap2,length(yvect),length(xvect));\n\n % Probability of stationarity (favoring stationarity)\n normlap2(ll)= mResult(:,15);\n mStationary1_Utsu = reshape(normlap2,length(yvect),length(xvect));\n\n % Probability of stationarity (favoring non-stationarity)\n normlap2(ll)= mResult(:,16);\n mStationary2_Utsu = reshape(normlap2,length(yvect),length(xvect));\n\n catch\n disp('Validated magnitude shift map not available');\n end\n % Initial map set to relative rate change\n re3 = mMagShift;\n lab1 = 'Magnitude shift';\n\n old = re3;\n % Plot\n view_mcgrid;\n else\n return\n end\nend\n", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/zmap_deprecated/orphaned/src/jochen/Scriptlab/mc_grid.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228625116081, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.34904286260507245}} {"text": "function [lf] = eeg_halfspace_dipole(dippos, elc, vol)\n\n% EEG_HALFSPACE_DIPOLE calculate the leadfield on electrode positions elc\n% for a dipole at position dippos. The halfspace solution requires a plane dividing a\n% conductive zone (cond > 0), from a non-coductive zone (cond = 0).\n%\n% Use as\n% [lf] = eeg_halfspace_dipole(dippos, elc, vol)\n%\n% See also EEG_INFINITE_DIPOLE, EEG_INFINITE_MONOPOLE, EEG_HALFSPACE_MONOPOLE\n\n% Copyright (C) 2011, Cristiano Micheli and Robert Oostenveld\n%\n% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org\n% for the documentation and details.\n%\n% FieldTrip is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% FieldTrip is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with FieldTrip. If not, see .\n%\n% $Id$\n\nif isfield(vol, 'pos')\n % this is for forward/backward compatibility\n vol.pnt = vol.pos;\n vol = rmfield(vol, 'pos');\nend\n\nsiz = size(dippos);\nif any(siz==1)\n % positions are specified as a single vector\n Ndipoles = prod(siz)/3;\n dippos = dippos(:)'; % ensure that it is a row vector\nelseif siz(2)==3\n % positions are specified as a Nx3 matrix -> reformat to a single vector\n Ndipoles = siz(1);\n dippos = dippos';\n dippos = dippos(:)'; % ensure that it is a row vector\nelse\n ft_error('incorrect specification of dipole locations');\nend\n\nNelc = size(elc,1);\nlf = zeros(Nelc,3*Ndipoles);\n\nfor i=1:Ndipoles\n % this is the position of dipole \"i\"\n dip1 = dippos((1:3) + 3*(i-1));\n \n % find the position of a mirror dipole symmetric to the plane\n dip2 = get_mirror_pos(dip1, vol);\n \n % compute the potential of the original and the mirror dipole\n lf1 = eeg_infinite_dipole(dip1, elc, vol);\n lf2 = eeg_infinite_dipole(dip2, elc, vol);\n \n % the z-direction of the mirror dipole should be swapped\n lf2(:,3) = -lf2(:,3);\n \n % take the sum of the two dipoles\n lf = lf1 + lf2;\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% SUBFUNCTION\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction P2 = get_mirror_pos(P1,vol)\n% calculates the position of a point symmetric to pnt with respect to a plane\n\n% define the plane\npnt = vol.pnt;\nori = vol.ori; % already normalized\n\nif abs(dot(P1-pnt,ori)). \n\nclear all\n\n% =========================================================================\n% SIMULATION\n% =========================================================================\n\n% create the computational grid\nPML_size = 20; % size of the PML in grid points\nNx = 128 - 2*PML_size; % number of grid points in the x (row) direction\nNy = 256 - 2*PML_size; % number of grid points in the y (column) direction\ndx = 0.1e-3; % grid point spacing in the x direction [m]\ndy = 0.1e-3; % grid point spacing in the y direction [m]\nkgrid = makeGrid(Nx, dx, Ny, dy);\n\n% define the properties of the propagation medium\nmedium.sound_speed = 1500;\t% [m/s]\n\n% create initial pressure distribution using makeDisc\ndisc_magnitude = 5; % [au]\ndisc_x_pos = 60; % [grid points]\ndisc_y_pos = 140; \t% [grid points]\ndisc_radius = 5; % [grid points]\ndisc_2 = disc_magnitude*makeDisc(Nx, Ny, disc_x_pos, disc_y_pos, disc_radius);\n\ndisc_x_pos = 30; % [grid points]\ndisc_y_pos = 110; \t% [grid points]\ndisc_radius = 8; % [grid points]\ndisc_1 = disc_magnitude*makeDisc(Nx, Ny, disc_x_pos, disc_y_pos, disc_radius);\n\n% smooth the initial pressure distribution and restore the magnitude\np0 = smooth(kgrid, disc_1 + disc_2, true);\n\n% assign to the source structure\nsource.p0 = p0;\n\n% define a four-sided, square sensor\nsensor.mask = zeros(kgrid.Nx, kgrid.Ny);\nsensor.mask(1, :) = 1;\nsensor.mask(end, :) = 1;\nsensor.mask(:, 1) = 1;\nsensor.mask(:, end) = 1;\n\n% create the time array\n[kgrid.t_array, dt] = makeTime(kgrid, medium.sound_speed);\n\n% set the input arguements\ninput_args = {'PMLInside', false, 'PMLSize', PML_size, 'PlotPML', false, 'Smooth', false};\n\n% run the simulation for omnidirectional detector elements\nsensor_data = kspaceFirstOrder2D(kgrid, medium, source, sensor, input_args{:});\n\n% define the directionality of the sensor elements\nsensor.directivity_angle = zeros(kgrid.Nx, kgrid.Ny);\nsensor.directivity_angle(1, :) = 0; \t % max sensitivity in x direction\nsensor.directivity_angle(end, :) = 0; \t % max sensitivity in x direction\nsensor.directivity_angle(:, 1) = pi/2; % max sensitivity in y direction\nsensor.directivity_angle(:, end) = pi/2; % max sensitivity in y direction\n\n% define the directivity size\nsensor.directivity_size = 20*kgrid.dx;\n\n% run the simulation with directional elements\nsensor_data_directional = kspaceFirstOrder2D(kgrid, medium, source, sensor, input_args{:});\n\n% reset the initial pressure\nsource.p0 = 0;\n\n% assign the time reversal data for the omnidirectional case\nsensor.time_reversal_boundary_data = sensor_data;\n\n% run the time reversal reconstruction\np0_recon = kspaceFirstOrder2D(kgrid, medium, source, sensor, input_args{:});\n\n% assign the time reversal data for the directional case\nsensor.time_reversal_boundary_data = sensor_data_directional;\n\n% run the time reversal reconstruction with directional elements\np0_recon_directional = kspaceFirstOrder2D(kgrid, medium, source, sensor, input_args{:});\n\n% =========================================================================\n% VISUALISATION\n% =========================================================================\n\n% plot the initial pressure and sensor distribution\nfigure;\nimagesc(kgrid.y_vec*1e3, kgrid.x_vec*1e3, p0 + sensor.mask*disc_magnitude, [-disc_magnitude disc_magnitude]);\ncolormap(getColorMap);\nylabel('x-position [mm]');\nxlabel('y-position [mm]');\naxis image;\ncolorbar;\n\n% plot the reconstructed initial pressure \nfigure;\nimagesc(kgrid.y_vec*1e3, kgrid.x_vec*1e3, p0_recon, [-disc_magnitude disc_magnitude]);\ncolormap(getColorMap);\nylabel('x-position [mm]');\nxlabel('y-position [mm]');\naxis image;\ncolorbar;\n\n% plot the reconstructed initial pressure with directivity\nfigure;\nimagesc(kgrid.y_vec*1e3, kgrid.x_vec*1e3, p0_recon_directional, [-disc_magnitude disc_magnitude]);\ncolormap(getColorMap);\nylabel('x-position [mm]');\nxlabel('y-position [mm]');\naxis image;\ncolorbar;\n\n% plot a profile for comparison\nfigure;\nplot(kgrid.y_vec*1e3, p0(disc_x_pos, :), 'k-',...\n kgrid.y_vec*1e3, p0_recon(disc_x_pos, :), 'r--',...\n kgrid.y_vec*1e3, p0_recon_directional(disc_x_pos, :), 'b:');\nxlabel('y-position [mm]');\nylabel('Pressure');\nlegend('True', 'Omnidirectional','Directional');\naxis tight;\nset(gca, 'YLim', [0 5.1]);\n", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/K-wave/k-Wave/examples/example_pr_2D_TR_directional_sensors.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5736784220301064, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.34860324839554585}} {"text": "function gpcf = gpcf_squared(varargin)\n%GPCF_SQUARED Create a squared (dot product) covariance function\n%\n% Description\n% GPCF = GPCF_SQUARED('PARAM1',VALUE1,'PARAM2,VALUE2,...) creates\n% a squared (dot product) covariance function structure in which\n% the named parameters have the specified values. Any unspecified\n% parameters are set to default values. The squared covariance function\n% corresponds to x.^2 mean function and the respective covariance matrix\n% is given as C = x.^2*diag(gpcf.coeffSigma2)*(x'.^2);\n%\n% GPCF = GPCF_SQUARED(GPCF,'PARAM1',VALUE1,'PARAM2,VALUE2,...) \n% modify a covariance function structure with the named\n% parameters altered with the specified values.\n% \n% Parameters for squared (dot product) covariance function\n% interactions - twoway interactions (default off)\n% coeffSigma2 - prior variance for regressor coefficients [10]\n% This can be either scalar corresponding\n% to a common prior variance or vector\n% defining own prior variance for each\n% coefficient.\n% coeffSigma2_prior - prior structure for coeffSigma2 [prior_logunif]\n% selectedVariables - vector defining which inputs are used [all]\n%\n% Note! If the prior is 'prior_fixed' then the parameter in\n% question is considered fixed and it is not handled in\n% optimization, grid integration, MCMC etc.\n%\n% See also\n% GP_SET, GPCF_*, PRIOR_*, MEAN_*\n%\n% Copyright (c) 2007-2016 Jarno Vanhatalo\n% Copyright (c) 2008-2010 Jaakko Riihimäki\n% Copyright (c) 2010 Aki Vehtari\n% Copyright (c) 2014 Arno Solin\n\n% This software is distributed under the GNU General Public\n% License (version 3 or later); please refer to the file\n% License.txt, included with the software, for details.\n\n ip=inputParser;\n ip.FunctionName = 'GPCF_SQUARED';\n ip.addOptional('gpcf', [], @isstruct);\n ip.addParamValue('interactions', 'off', @(x) ismember(x,{'on' 'off'}))\n ip.addParamValue('coeffSigma2',10, @(x) isvector(x) && all(x>0));\n ip.addParamValue('coeffSigma2_prior',prior_logunif, @(x) isstruct(x) || isempty(x));\n ip.addParamValue('selectedVariables',[], @(x) isvector(x) && all(x>0));\n ip.parse(varargin{:});\n gpcf=ip.Results.gpcf;\n\n if isempty(gpcf)\n init=true;\n gpcf.type = 'gpcf_squared';\n else\n if ~isfield(gpcf,'type') && ~isequal(gpcf.type,'gpcf_squared')\n error('First argument does not seem to be a valid covariance function structure')\n end\n init=false;\n end\n \n if init || ~ismember('interactions',ip.UsingDefaults)\n gpcf.interactions=ip.Results.interactions;\n end\n \n % Initialize parameter\n if init || ~ismember('coeffSigma2',ip.UsingDefaults)\n gpcf.coeffSigma2=ip.Results.coeffSigma2;\n end\n\n % Initialize prior structure\n if init\n gpcf.p=[];\n end\n if init || ~ismember('coeffSigma2_prior',ip.UsingDefaults)\n gpcf.p.coeffSigma2=ip.Results.coeffSigma2_prior;\n end\n if ~ismember('selectedVariables',ip.UsingDefaults)\n selectedVariables=ip.Results.selectedVariables;\n if ~isempty(selectedVariables)\n gpcf.selectedVariables = selectedVariables;\n end\n end\n \n if init\n % Set the function handles to the subfunctions\n gpcf.fh.pak = @gpcf_squared_pak;\n gpcf.fh.unpak = @gpcf_squared_unpak;\n gpcf.fh.lp = @gpcf_squared_lp;\n gpcf.fh.lpg = @gpcf_squared_lpg;\n gpcf.fh.cfg = @gpcf_squared_cfg;\n gpcf.fh.cfdg = @gpcf_squared_cfdg;\n gpcf.fh.cfdg2 = @gpcf_squared_cfdg2;\n gpcf.fh.ginput = @gpcf_squared_ginput;\n gpcf.fh.ginput2 = @gpcf_squared_ginput2;\n gpcf.fh.ginput3 = @gpcf_squared_ginput3;\n gpcf.fh.ginput4 = @gpcf_squared_ginput4;\n gpcf.fh.cov = @gpcf_squared_cov;\n gpcf.fh.trcov = @gpcf_squared_trcov;\n gpcf.fh.trvar = @gpcf_squared_trvar;\n gpcf.fh.recappend = @gpcf_squared_recappend;\n gpcf.fh.cf2ss = @gpcf_squared_cf2ss;\n end \n\nend\n\nfunction [w, s, h] = gpcf_squared_pak(gpcf, w)\n%GPCF_squared_PAK Combine GP covariance function parameters into one vector\n%\n% Description\n% W = GPCF_squared_PAK(GPCF) takes a covariance function\n% structure GPCF and combines the covariance function\n% parameters and their hyperparameters into a single row\n% vector W. This is a mandatory subfunction used for \n% example in energy and gradient computations.\n%\n% w = [ log(gpcf.coeffSigma2)\n% (hyperparameters of gpcf.coeffSigma2)]'\n%\n% See also\n% GPCF_squared_UNPAK\n \n w = []; s = {}; h =[];\n if ~isempty(gpcf.p.coeffSigma2)\n w = log(gpcf.coeffSigma2);\n if numel(gpcf.coeffSigma2)>1\n s = [s; sprintf('log(squared.coeffSigma2 x %d)',numel(gpcf.coeffSigma2))];\n else\n s = [s; 'log(squared.coeffSigma2)'];\n end\n h = [h ones(1, numel(gpcf.coeffSigma2))];\n % Hyperparameters of coeffSigma2\n [wh, sh, hh] = gpcf.p.coeffSigma2.fh.pak(gpcf.p.coeffSigma2);\n sh=strcat(repmat('prior-', size(sh,1),1),sh);\n w = [w wh];\n s = [s; sh];\n h = [h 1+hh];\n end\nend\n\nfunction [gpcf, w] = gpcf_squared_unpak(gpcf, w)\n%GPCF_squared_UNPAK Sets the covariance function parameters \n% into the structure\n%\n% Description\n% [GPCF, W] = GPCF_squared_UNPAK(GPCF, W) takes a covariance\n% function structure GPCF and a hyper-parameter vector W, and\n% returns a covariance function structure identical to the\n% input, except that the covariance hyper-parameters have been\n% set to the values in W. Deletes the values set to GPCF from\n% W and returns the modified W. This is a mandatory subfunction \n% used for example in energy and gradient computations.\n%\n% Assignment is inverse of \n% w = [ log(gpcf.coeffSigma2)\n% (hyperparameters of gpcf.coeffSigma2)]'\n%\n% See also\n% GPCF_squared_PAK\n \n gpp=gpcf.p;\n\n if ~isempty(gpp.coeffSigma2)\n i2=length(gpcf.coeffSigma2);\n i1=1;\n gpcf.coeffSigma2 = exp(w(i1:i2));\n w = w(i2+1:end);\n \n % Hyperparameters of coeffSigma2\n [p, w] = gpcf.p.coeffSigma2.fh.unpak(gpcf.p.coeffSigma2, w);\n gpcf.p.coeffSigma2 = p;\n end\nend\n\nfunction lp = gpcf_squared_lp(gpcf)\n%GPCF_squared_LP Evaluate the log prior of covariance function parameters\n%\n% Description\n% LP = GPCF_squared_LP(GPCF) takes a covariance function\n% structure GPCF and returns log(p(th)), where th collects the\n% parameters. This is a mandatory subfunction used for example \n% in energy computations.\n%\n% See also\n% GPCF_squared_PAK, GPCF_squared_UNPAK, GPCF_squared_LPG, GP_E\n\n% Evaluate the prior contribution to the error. The parameters that\n% are sampled are from space W = log(w) where w is all the \"real\" samples.\n% On the other hand errors are evaluated in the W-space so we need take\n% into account also the Jacobian of transformation W -> w = exp(W).\n% See Gelman et al. (2013), Bayesian Data Analysis, third edition, p. 21.\n lp = 0;\n gpp=gpcf.p;\n\n if ~isempty(gpp.coeffSigma2)\n lp = gpp.coeffSigma2.fh.lp(gpcf.coeffSigma2, gpp.coeffSigma2) + sum(log(gpcf.coeffSigma2));\n end\nend\n\nfunction lpg = gpcf_squared_lpg(gpcf)\n%GPCF_squared_LPG Evaluate gradient of the log prior with respect\n% to the parameters.\n%\n% Description\n% LPG = GPCF_squared_LPG(GPCF) takes a covariance function\n% structure GPCF and returns LPG = d log (p(th))/dth, where th\n% is the vector of parameters. This is a mandatory subfunction \n% used for example in gradient computations.\n%\n% See also\n% GPCF_squared_PAK, GPCF_SQUARED_UNPAK, GPCF_SQUARED_LP, GP_G\n\n lpg = [];\n gpp=gpcf.p;\n \n if ~isempty(gpcf.p.coeffSigma2) \n lll=length(gpcf.coeffSigma2);\n lpgs = gpp.coeffSigma2.fh.lpg(gpcf.coeffSigma2, gpp.coeffSigma2);\n lpg = [lpg lpgs(1:lll).*gpcf.coeffSigma2+1 lpgs(lll+1:end)];\n end\nend\n\nfunction DKff = gpcf_squared_cfg(gpcf, x, x2, mask, i1)\n%GPCF_SQUARED_CFG Evaluate gradient of covariance function\n% with respect to the parameters\n%\n% Description\n% DKff = GPCF_SQUARED_CFG(GPCF, X) takes a covariance function\n% structure GPCF, a matrix X of input vectors and returns\n% DKff, the gradients of covariance matrix Kff = k(X,X) with\n% respect to th (cell array with matrix elements). This is a \n% mandatory subfunction used in gradient computations.\n%\n% DKff = GPCF_SQUARED_CFG(GPCF, X, X2) takes a covariance\n% function structure GPCF, a matrix X of input vectors and\n% returns DKff, the gradients of covariance matrix Kff =\n% k(X,X2) with respect to th (cell array with matrix\n% elements). This subfunction is needed when using sparse \n% approximations (e.g. FIC).\n%\n% DKff = GPCF_SQUARED_CFG(GPCF, X, [], MASK) takes a covariance\n% function structure GPCF, a matrix X of input vectors and\n% returns DKff, the diagonal of gradients of covariance matrix\n% Kff = k(X,X2) with respect to th (cell array with matrix\n% elements). This subfunction is needed when using sparse \n% approximations (e.g. FIC).\n%\n% DKff = GPCF_SQUARED_CFG(GPCF,X,X2,MASK,i) takes a covariance \n% function structure GPCF, a matrix X of input vectors and \n% returns DKff, the gradient of covariance matrix Kff = \n% k(X,X2), or k(X,X) if X2 is empty, with respect to ith \n% hyperparameter. This subfunction is needed when using\n% memory save option in gp_set.\n%\n% See also\n% GPCF_SQUARED_PAK, GPCF_SQUARED_UNPAK, GPCF_SQUARED_LP, GP_G\n\n if nargin>2 && ~isempty(x2)\n if size(x,2) ~= size(x2,2)\n error('gpcf_squared -> _cfg: the number of columns of X1 and X2 has to be same')\n end\n end\n\n if isfield(gpcf, 'selectedVariables')\n x = x(:,gpcf.selectedVariables);\n end\n [n, m] =size(x);\n h = x.^2;\n if isequal(gpcf.interactions,'on')\n for xi1=1:m\n for xi2=xi1+1:m\n h = [h x(:,xi1).*x(:,xi2)];\n end\n end\n end\n \n DKff = {};\n \n if nargin==5\n % Use memory save option\n savememory=1;\n if i1==0\n % Return number of hyperparameters\n DKff=0;\n if ~isempty(gpcf.p.coeffSigma2)\n DKff=length(gpcf.coeffSigma2);\n end\n return\n end\n else\n savememory=0;\n end\n \n % Evaluate: DKff{1} = d Kff / d coeffSigma2\n % NOTE! Here we have already taken into account that the parameters are transformed\n % through log() and thus dK/dlog(p) = p * dK/dp\n\n \n % evaluate the gradient for training covariance\n if nargin == 2 || (isempty(x2) && isempty(mask))\n \n if ~isempty(gpcf.p.coeffSigma2)\n if length(gpcf.coeffSigma2) == 1\n DKff{1}=gpcf.coeffSigma2*h*(h');\n else\n if isa(gpcf.coeffSigma2,'single')\n epsi=eps('single');\n else\n epsi=eps;\n end\n if ~savememory\n i1=1:length(gpcf.coeffSigma2);\n end\n DKff=cell(1,length(i1));\n for ii1=i1\n DD = gpcf.coeffSigma2(ii1)*h(:,ii1)*(h(:,ii1)');\n DD(abs(DD)<=epsi) = 0;\n DKff{ii1}= (DD+DD')./2;\n end\n end\n end\n \n \n % Evaluate the gradient of non-symmetric covariance (e.g. K_fu)\n elseif nargin == 3 || isempty(mask)\n \n error('this part of the subfunction has not been tested')\n \n if isfield(gpcf, 'selectedVariables')\n x2 = x2(:,gpcf.selectedVariables);\n end\n h2 = x2.^2;\n if isequal(gpcf.interactions,'on')\n for xi1=1:m\n for xi2=xi1+1:m\n h2 = [h2 x2(:,xi1).*x2(:,xi2)];\n end\n end\n end\n \n if ~isempty(gpcf.p.coeffSigma2)\n if length(gpcf.coeffSigma2) == 1\n DKff{1}=gpcf.coeffSigma2*h*(h2');\n else\n if ~savememory\n i1=1:m;\n end\n for ii1=i1\n DKff{ii1}=gpcf.coeffSigma2(ii1)*h(:,ii1)*(h2(:,ii1)');\n end\n end\n end\n % Evaluate: DKff{1} = d mask(Kff,I) / d coeffSigma2\n % DKff{2...} = d mask(Kff,I) / d coeffSigma2\n elseif nargin == 4 || nargin == 5\n \n error('this part of the subfunction has not been tested')\n \n if ~isempty(gpcf.p.coeffSigma2)\n if length(gpcf.coeffSigma2) == 1\n DKff{1}=gpcf.coeffSigma2*sum(h.^2,2); % d mask(Kff,I) / d coeffSigma2\n else\n if ~savememory\n i1=1:m;\n end\n for ii1=i1\n DKff{ii1}=gpcf.coeffSigma2(ii1)*(h(:,ii1).^2); % d mask(Kff,I) / d coeffSigma2\n end\n end\n end\n end\n if savememory\n DKff=DKff{i1};\n end\nend\n\nfunction DKff = gpcf_squared_cfdg(gpcf, x, x2, dims)\n%GPCF_SQUARED_CFDG Evaluate gradient of covariance function, of\n% which has been taken partial derivative with\n% respect to x, with respect to parameters.\n%\n% Description\n% DKff = GPCF_SQUARED_CFDG(GPCF, X) takes a covariance function\n% structure GPCF, a matrix X of input vectors and returns\n% DKff, the gradients of derivatived covariance matrix\n% dK(df,f)/dhyp = d(d k(X,X)/dx)/dhyp, with respect to the\n% parameters\n%\n% Evaluate: DKff{1:m} = d Kff / d coeffSigma2\n% m is the dimension of inputs. This subfunction is needed when using\n% derivative observations.\n%\n% Note! When coding the derivatives of the covariance function, remember\n% to double check them. See gp_cov for lines of code to check the\n% matrices\n%\n% See also\n% GPCF_SQUARED_GINPUT\n\n[~,m]=size(x);\nif nargin<3\n x2=x;\nend\nif nargin < 4 || isempty(dims)\n dims = 1:m;\nend\nii1=0;\nDKff={};\nif isfield(gpcf,'selectedVariables')\n selVars = gpcf.selectedVariables;\nelse\n selVars = 1:m;\nend\nc = gpcf.coeffSigma2;\n\nh = x.^2;\nh2 = x2.^2;\n\nii1=0;\nDKff={};\nif ~isempty(gpcf.p.coeffSigma2)\n if length(gpcf.coeffSigma2)==1\n % One coeffSigma2\n for i1=dims\n if isfield(gpcf, 'selectedVariables') && sum(gpcf.selectedVariables==i1)==0\n DK{i1}=zeros(size(x,1),size(x2,1));\n else\n DK{i1}=c(1).*2*x(:,i1)*h2(:,i1)';\n if isequal(gpcf.interactions,'on')\n for xi2=selVars\n if xi2~=i1\n DK{i1} = DK{i1} + c(1)*x(:,xi2)*(x2(:,i1).*x2(:,xi2))';\n end\n end\n end\n end\n end\n ii1=ii1+1;\n DKff{ii1}=cat(1,DK{1:end});\n else\n % vector of coeffSigma2s\n for i1=1:length(selVars)\n for j=dims\n if selVars(i1)~=j %|| (isfield(gpcf, 'selectedVariables') && sum(gpcf.selectedVariables==i1)==0)\n DK{j}=zeros(size(x,1),size(x2,1));\n else\n DK{j}=c(i1).*2*x(:,j)*h2(:,j)';\n end\n end\n ii1=ii1+1;\n DKff{ii1}=cat(1,DK{1:end});\n end\n if isequal(gpcf.interactions,'on')\n for xi1=1:length(selVars)\n for xi2=xi1+1:length(selVars)\n i1=i1+1;\n for j=dims\n if j==xi1 \n DK{j} = c(i1)*x(:,xi2)*(x2(:,xi1).*x2(:,xi2))';\n elseif j==xi2\n DK{j} = c(i1)*x(:,xi1)*(x2(:,xi1).*x2(:,xi2))';\n else\n DK{j}=zeros(size(x,1),size(x2,1));\n end\n end\n ii1=ii1+1;\n DKff{ii1}=cat(1,DK{1:end});\n end\n end\n end\n end\nend\n\nend\n\nfunction DKff = gpcf_squared_cfdg2(gpcf, x, x2, dims1, dims2)\n%GPCF_SQUARED_CFDG2 Evaluate gradient of covariance function, of which has\n% been taken partial derivatives with respect to both\n% input variables x, with respect to parameters.\n%\n% Description\n% DKff = GPCF_SQUARED_CFDG2(GPCF, X) takes a covariance\n% function structure GPCF, a matrix X of input vectors and\n% returns DKff, the gradients of derivative covariance matrix\n% dK(df,df)/dhyp = d(d^2 k(X1,X2)/dX1dX2)/dhyp with respect to\n% the parameters\n%\n% Evaluate: DKff{1:m} = d K(df,df) / d coeffSigma\n% m is the dimension of inputs. This subfunction is needed when using\n% derivative observations.\n%\n% Note! When coding the derivatives of the covariance function, remember\n% to double check them. See gp_cov for lines of code to check the\n% matrices\n%\n% See also\n% GPCF_SQUARED_GINPUT, GPCF_SQUARED_GINPUT2\n\n\n[~, m] =size(x);\nif nargin <3 || isempty(x2)\n x2=x;\nend\nif nargin < 4 || isempty(dims1)\n %dims1 = 1:m;\n error('dims1 needs to be given')\nend\nif nargin < 5 || isempty(dims2)\n %dims2 = 1:m;\n error('dims2 needs to be given')\nend\nif isfield(gpcf,'selectedVariables')\n selVars = gpcf.selectedVariables;\nelse\n selVars = 1:m;\nend\n% NOTICE. AS OF NOW we assume that dims1 and dims2 are scalars\n\nii1=0;\nif length(gpcf.coeffSigma2)==1\n c=repmat(gpcf.coeffSigma2,1,(1+length(selVars))*length(selVars)/2);\nelse\n c=gpcf.coeffSigma2;\nend\nif length(gpcf.coeffSigma2)==1\n % One coeffSigma2\n if dims1~=dims2 %|| (isfield(gpcf, 'selectedVariables') && (sum(gpcf.selectedVariables==j)==0 || sum(gpcf.selectedVariables==k)==0))\n DK=zeros(size(x,1),size(x2,1));\n if isequal(gpcf.interactions,'on') && (sum(selVars==dims1)>0 || sum(selVars==dims2)>0)\n DK = c(1)*x(:,dims1)*x2(:,dims2)';\n end\n else\n if sum(selVars==dims1)==0\n DK=zeros(size(x,1),size(x2,1));\n else\n DK=c(1).*4.*x(:,dims1)*x2(:,dims2)';\n end\n if isequal(gpcf.interactions,'on') && sum(selVars==dims1)>0\n for xi2=selVars\n if xi2~=dims1\n DK = DK + c(1)*x(:,xi2)*x2(:,xi2)';\n end\n end\n end\n end\n ii1=ii1+1;\n DKff{ii1}=DK;\nelse\n % vector of coeffSigma2s\n for i1=1:length(selVars)\n if dims1~=dims2 || dims2~=selVars(i1)\n DK=zeros(size(x,1),size(x2,1));\n else\n DK=c(i1).*4.*x(:,dims1)*x2(:,dims2)';\n end\n ii1=ii1+1;\n DKff{ii1}=DK;\n end\n if isequal(gpcf.interactions,'on')\n for xi1=1:length(selVars)\n for xi2=xi1+1:length(selVars)\n i1=i1+1;\n %if k==xi1 && j==xi2\n if dims1==xi1 && dims2==xi2\n DK = c(i1)*x(:,xi2)*x2(:,xi1)';\n %elseif k==xi2 && j==xi1\n elseif dims1==xi2 && dims2==xi1\n DK = c(i1)*x(:,xi1)*x2(:,xi2)';\n %elseif k==j && k==xi1\n elseif dims1==dims2 && dims1==xi1 \n DK = c(i1)*x(:,xi2)*x2(:,xi2)';\n %elseif k==j && k==xi2\n elseif dims1==dims2 && dims1==xi2\n DK = c(i1)*x(:,xi1)*x2(:,xi1)';\n else\n DK=zeros(size(x,1),size(x2,1));\n end\n ii1=ii1+1;\n DKff{ii1}=DK;\n end\n end\n end\nend\n\nend\n\n\nfunction DKff = gpcf_squared_ginput(gpcf, x, x2, i1)\n%GPCF_SQUARED_GINPUT Evaluate gradient of covariance function with \n% respect to x.\n%\n% Description\n% DKff = GPCF_SQUARED_GINPUT(GPCF, X, X2) takes a covariance function\n% structure GPCF, a matrix X of input vectors and returns DKff, the\n% gradients of covariance matrix Kff = k(X,X2) with respect to X (cell\n% array with matrix elements). If called with only two inputs\n% GPCF_SQUARED_GINPUT(GPCF, X), X2=X. This subfunction is needed when\n% computing gradients with respect to inducing inputs in sparse\n% approximations. \n%\n% DKff = GPCF_SQUARED_GINPUT(GPCF, X, X2, i) takes a covariance\n% function structure GPCF, a matrix X of input vectors and\n% returns DKff, the gradients of covariance matrix Kff =\n% k(X,X2) with respect to ith covariate in X (matrix).\n% This subfunction is needed when using memory save option\n% in gp_set.\n%\n% Note! When coding the derivatives of the covariance function, remember\n% to double check them. See gp_cov for lines of code to check the\n% matrices\n%\n% See also\n% GPCF_SQUARED_PAK, GPCF_SQUARED_UNPAK, GPCF_SQUARED_LP, GP_G \n \nif isfield(gpcf, 'selectedVariables') \n error('The selectedVariables option has not yet been implemented for gpcf_squared with derivobs=''on'' ')\n % notice, some parts of the code already take into account the\n % selectedVariables but the code has not been checked\nend\n\n[n, m] =size(x);\n\nif nargin==4\n % Use memory save option\n savememory=1;\n if i1==0\n % Return number of covariates\n DKff=m;\n return\n end\nelse\n savememory=0;\nend\n\nif nargin == 2 || isempty(x2)\n \n xx = x.^2;\n if length(gpcf.coeffSigma2)==1\n s=gpcf.coeffSigma2.*ones(1,(1+m)*m/2);\n else\n s=gpcf.coeffSigma2;\n end\n ii1 = 0;\n if nargin<4\n i1=1:m;\n end\n for j = 1:n\n for i=i1\n DK = zeros(n);\n DK(j,:)=2*s(i)*x(j,i)*xx(:,i)';\n if isequal(gpcf.interactions,'on')\n for xi2=i1\n if xi2~=i\n DK(j,:) = DK(j,:) + s(i)*x(j,xi2).*(x(:,i).*x(:,xi2))';\n end\n end\n end\n DK = DK + DK';\n ii1 = ii1 + 1;\n DKff{ii1} = DK;\n end\n end\n \nelseif nargin == 3 || nargin == 4\n \n xx2 = x2.^2;\n if length(gpcf.coeffSigma2)==1\n s=gpcf.coeffSigma2.*ones(1,(1+m)*m/2);\n else\n s=gpcf.coeffSigma2;\n end\n ii1 = 0;\n if ~savememory\n i1=1:m;\n end\n for j = 1:n\n for i=i1\n DK = zeros(n, size(x2,1));\n DK(j,:)=2*s(i)*x(j,i)*xx2(:,i)';\n if isequal(gpcf.interactions,'on')\n for xi2=i1\n if xi2~=i\n DK(j,:) = DK(j,:) + s(i)*x(j,xi2).*(x2(:,i).*x2(:,xi2))';\n end\n end\n end\n ii1 = ii1 + 1;\n DKff{ii1} = DK;\n end\n end\nend\n\nend\n\nfunction DKff = gpcf_squared_ginput2(gpcf, x, x2, dims,takeOnlyDiag)\n%GPCF_SQUARED_GINPUT2 Evaluate gradient of covariance function with\n% respect to both input variables x and x2 in\n% same dimension.\n%\n% Description\n% DKff = GPCF_SQUARED_GINPUT2(GPCF, X, X2) takes a covariance\n% function structure GPCF, a matrix X of input vectors and\n% returns DKff, the gradients of twice derivatived covariance\n% matrix K(df,df) = dk(X1,X2)/dX1dX2 (cell array with matrix\n% elements). Input variable's dimensions are expected to be\n% same. This subfunction is needed when using derivative \n% observations.\n% \n% Note! When coding the derivatives of the covariance function, remember\n% to double check them. See gp_cov for lines of code to check the\n% matrices\n%\n% See also\n% GPCF_SQUARED_GINPUT, GPCF_SQUARED_GINPUT2, GPCF_SQUARED_CFDG2 \n\n[~,m]=size(x);\nii1=0;\nif nargin<4 || isempty(dims)\n dims=1:m;\nend\nif length(gpcf.coeffSigma2)==1\n c=repmat(gpcf.coeffSigma2,1,(1+m)*m/2);\nelse\n c=gpcf.coeffSigma2;\nend\nif isfield(gpcf, 'selectedVariables')\n sv = gpcf.selectedVariables;\nelse \n sv = 1:m;\nend\n\nif nargin==5 && isequal(takeOnlyDiag,'takeOnlyDiag')\n for i1=dims\n if ~any(sv==i1)%isfield(gpcf, 'selectedVariables') && sum(gpcf.selectedVariables==i1)==0\n DK=zeros(size(x,1),1);\n else\n DK=c(i1).*4.*(x(:,i1).*x2(:,i1));\n if isequal(gpcf.interactions,'on')\n i2=length(sv);\n for xi1=1:length(sv)\n for xi2=xi1+1:length(sv)\n if any(sv==xi1) && any(sv==xi2)\n i2=i2+1;\n if i1==xi1\n DK = DK + c(i2)*x(:,xi2).*x2(:,xi2);\n elseif i1==xi2\n DK = DK + c(i2)*x(:,xi1).*x2(:,xi1);\n end\n end\n end\n end\n end\n end\n ii1=ii1+1;\n DKff{ii1}=DK;\n end\nelse\n for i1=dims\n if ~any(sv==i1)%isfield(gpcf, 'selectedVariables') && sum(gpcf.selectedVariables==i1)==0\n DK=zeros(size(x,1),size(x2,1));\n else\n DK=c(i1).*4.*(x(:,i1)*x2(:,i1)');\n if isequal(gpcf.interactions,'on')\n i2=length(sv);\n for xi1=1:length(sv)\n for xi2=xi1+1:length(sv)\n if any(sv==xi1) && any(sv==xi2)\n i2=i2+1;\n if i1==xi1\n DK = DK + c(i2)*x(:,xi2)*x2(:,xi2)';\n elseif i1==xi2\n DK = DK + c(i2)*x(:,xi1)*x2(:,xi1)';\n end\n end\n end\n end\n end\n end\n ii1=ii1+1;\n DKff{ii1}=DK;\n end\nend\nend\n\nfunction DKff = gpcf_squared_ginput3(gpcf, x, x2, dims1, dims2)\n%GPCF_SQUARED_GINPUT3 Evaluate gradient of covariance function with\n% respect to both input variables x and x2 (in\n% different dimensions).\n%\n% Description\n% DKff = GPCF_SQUARED_GINPUT3(GPCF, X, X2) takes a covariance\n% function structure GPCF, a matrix X of input vectors and\n% returns DKff, the gradients of twice derivatived covariance\n% matrix K(df,df) = dk(X1,X2)/dX1dX2 (cell array with matrix\n% elements). The derivative is calculated in multidimensional\n% problem between input's observation dimensions which are not\n% same. This subfunction is needed when using derivative \n% observations.\n%\n% DKff is a cell array with the following elements:\n% DKff{1} = dk(X1,X2)/dX1_1dX2_2\n% DKff{2} = dk(X1,X2)/dX1_1dX2_3\n% ... \n% DKff{m-1} = dk(X1,X2)/dX1_1dX2_m\n% DKff{m} = dk(X1,X2)/dX1_2dX2_3\n% ...\n% DKff{m} = dk(X1,X2)/dX1_(m-1)dX2_m\n% where _m denotes the input dimension with respect to which the\n% gradient is calculated.\n%\n% Note! When coding the derivatives of the covariance function, remember\n% to double check them. See gp_cov for lines of code to check the\n% matrices\n% \n% See also\n% GPCF_SQUARED_GINPUT, GPCF_SQUARED_GINPUT2, GPCF_SQUARED_CFDG2 \n\n\n[~,m]=size(x);\nif nargin < 3\n error('Needs at least 3 input arguments')\nend\nif nargin<4 || isempty(dims1)\n dims1=1:m;\nend\nif nargin<5 || isempty(dims2)\n dims2=1:m;\nend\nif isfield(gpcf, 'selectedVariables')\n sv = gpcf.selectedVariables;\nelse \n sv = 1:m;\nend\n\nii1=0;\nif length(gpcf.coeffSigma2)==1\n c=repmat(gpcf.coeffSigma2,1,(1+m)*m/2);\nelse\n c=gpcf.coeffSigma2;\nend\nDK=zeros(size(x,1),size(x2,1));\ni2=m;\nfor i=dims1\n for j=dims2\n ii1=ii1+1;\n if isequal(gpcf.interactions,'on') && any(sv==i) && any(sv==j)\n i2 = min(i,j)*length(sv) - 0.5*min(i,j)*(min(i,j)-1) + max(i,j)-min(i,j);\n DKff{ii1} = c(i2)*x(:,j)*x2(:,i)';\n else\n DKff{ii1}=DK;\n end\n end\nend\n\n% i2=m;\n% for i=1:m-1\n% for j=i+1:m\n% i2=i2+1;\n% if any(dims1==i) && any(dims2==j)\n% ii1=ii1+1;\n% if isequal(gpcf.interactions,'on') && any(sv==i) && any(sv==j)\n% % if isequal(gpcf.interactions,'on') &&...\n% % ~(isfield(gpcf, 'selectedVariables') && (sum(gpcf.selectedVariables==i)==0 || sum(gpcf.selectedVariables==j)==0))\n% DKff{ii1} = c(i2)*x(:,j)*x2(:,i)';\n% else\n% DKff{ii1}=DK;\n% end\n% end\n% end\n% end\n\nend\n\nfunction DKff = gpcf_squared_ginput4(gpcf, x, x2, dims)\n%GPCF_SQUARED_GINPUT Evaluate gradient of covariance function with respect\n% to x. Simplified and faster version of squared_ginput,\n% returns full matrices. \n%\n% Description\n% DKff = GPCF_SQUARED_GINPUT4(GPCF, X, X2) takes a covariance function\n% structure GPCF, matrices X and X2 of input vectors and returns DKff,\n% the gradients of covariance matrix Kff = k(X,X2) with respect to X\n% (whole matrix); that is d k(X,X2)/dX. If called with only two inputs\n% GPCF_SQUARED_GINPUT4(GPCF, X), X2=X.\n%\n% This subfunction is needed when using derivative observations. \n%\n% Note! When coding the derivatives of the covariance function, remember\n% to double check them. See gp_cov for lines of code to check the\n% matrices\n%\n% See also\n% GPCF_SQUARED_PAK, GPCF_SQUARED_UNPAK, GPCF_SQUARED_LP, GP_G\n\n\n% if isfield(gpcf, 'selectedVariables') \n% error('The selectedVariables option has not yet been implemented for gpcf_squared with derivobs=''on'' ')\n% % notice, some parts of the code already take into account the\n% % selectedVariables but the code has not been checked\n% end\n% \n% if isfield(gpcf, 'selectedVariables')\n% m = length(gpcf.selectedVariables);\n% sv = gpcf.selectedVariables;\n% else \n% [~,m]=size(x);\n% sv = 1:m;\n% end\n% if nargin==2\n% x2=x;\n% end\n% if nargin<4\n% dims=1:size(x,2);\n% end\n% if length(gpcf.coeffSigma2)==1 \n% c=repmat(gpcf.coeffSigma2,1,(1+m)*m/2);\n% else\n% % If coeffSigma is vector, we trust it is of rigth length\n% c=gpcf.coeffSigma2;\n% end\n% h2=x2.^2;\n% ii1=0;\n% for i=dims\n% if ~any(sv==i) %isfield(gpcf, 'selectedVariables') && sum(gpcf.selectedVariables==i)==0\n% DK=zeros(size(x,1),size(x2,1));\n% else\n% DK=c(i).*2.*x(:,i)*h2(:,i)';\n% if isequal(gpcf.interactions,'on')\n% i2=m;\n% for xi1=sv\n% sv2 = sv(sv>xi1);\n% for xi2=sv2 %xi1+1:m\n% i2 = i2+1;\n% if i==xi1\n% DK = DK + c(i2)*x(:,xi2)*(x2(:,i).*x2(:,xi2))';\n% elseif i==xi2\n% DK = DK + c(i2)*x(:,xi1)*(x2(:,i).*x2(:,xi1))';\n% end\n% end\n% end\n% end\n% end\n% ii1=ii1+1;\n% DKff{ii1}=DK;\n% end\n\n[n,m]=size(x);\nif nargin<4\n dims=1:m;\nend\nif isfield(gpcf, 'selectedVariables')\n sv = gpcf.selectedVariables;\nelse \n sv = 1:m;\nend\nii1=0;\nif nargin==2\n x2=x;\nend\nh2=x2.^2;\nif length(gpcf.coeffSigma2)==1\n c=repmat(gpcf.coeffSigma2,1,(1+m)*m/2);\nelse\n c=gpcf.coeffSigma2;\nend\nfor i=dims\n if ~any(sv==i) % isfield(gpcf, 'selectedVariables') && sum(gpcf.selectedVariables==i)==0\n DK=zeros(size(x,1),size(x2,1));\n else\n DK=c(i).*2.*x(:,i)*h2(:,i)';\n if isequal(gpcf.interactions,'on')\n i2=length(sv);\n for xi1=1:length(sv)\n for xi2=xi1+1:length(sv)\n if any(sv==xi1) && any(sv==xi2)\n i2=i2+1;\n% i2 = min(i,j)*length(sv) - 0.5*min(i,j)*(min(i,j)-1) + max(i,j)-min(i,j)\n if i==xi1\n DK = DK + c(i2)*x(:,xi2)*(x2(:,i).*x2(:,xi2))';\n elseif i==xi2\n DK = DK + c(i2)*x(:,xi1)*(x2(:,i).*x2(:,xi1))';\n end\n end\n end\n end\n end\n end\n ii1=ii1+1;\n DKff{ii1}=DK;\nend\nend\n\nfunction C = gpcf_squared_cov(gpcf, x1, x2, varargin)\n%GP_SQUARED_COV Evaluate covariance matrix between two input vectors\n%\n% Description \n% C = GP_SQUARED_COV(GP, TX, X) takes in covariance function of\n% a Gaussian process GP and two matrixes TX and X that contain\n% input vectors to GP. Returns covariance matrix C. Every\n% element ij of C contains covariance between inputs i in TX\n% and j in X. This is a mandatory subfunction used for example in\n% prediction and energy computations.\n%\n% See also\n% GPCF_SQUARED_TRCOV, GPCF_SQUARED_TRVAR, GP_COV, GP_TRCOV\n \n if isempty(x2)\n x2=x1;\n end\n [n1,m1]=size(x1);\n [n2,m2]=size(x2);\n if m1~=m2\n error('the number of columns of X1 and X2 has to be same')\n end\n if isfield(gpcf, 'selectedVariables')\n x1 = x1(:,gpcf.selectedVariables);\n x2 = x2(:,gpcf.selectedVariables);\n end\n h1 = x1.^2;\n h2 = x2.^2;\n if isequal(gpcf.interactions,'on')\n m=size(x1,2);\n for xi1=1:m\n for xi2=xi1+1:m\n h1 = [h1 x1(:,xi1).*x1(:,xi2)];\n h2 = [h2 x2(:,xi1).*x2(:,xi2)];\n end\n end\n end\n C = h1*diag(gpcf.coeffSigma2)*(h2');\n C(abs(C)<=eps) = 0;\n \nend\n\nfunction C = gpcf_squared_trcov(gpcf, x)\n%GP_SQUARED_TRCOV Evaluate training covariance matrix of inputs\n%\n% Description\n% C = GP_SQUARED_TRCOV(GP, TX) takes in covariance function of\n% a Gaussian process GP and matrix TX that contains training\n% input vectors. Returns covariance matrix C. Every element ij\n% of C contains covariance between inputs i and j in TX. This \n% is a mandatory subfunction used for example in prediction and \n% energy computations.\n%\n% See also\n% GPCF_SQUARED_COV, GPCF_SQUARED_TRVAR, GP_COV, GP_TRCOV\n\n \n if isfield(gpcf, 'selectedVariables')\n x = x(:,gpcf.selectedVariables);\n end\n h = x.^2;\n if isequal(gpcf.interactions,'on')\n m=size(x,2);\n for xi1=1:m\n for xi2=xi1+1:m\n h = [h x(:,xi1).*x(:,xi2)];\n end\n end\n end\n C = h*diag(gpcf.coeffSigma2)*(h');\n C(abs(C)<=eps) = 0;\n C = (C+C')./2;\n \nend\n\n\nfunction C = gpcf_squared_trvar(gpcf, x)\n%GP_SQUARED_TRVAR Evaluate training variance vector\n%\n% Description\n% C = GP_SQUARED_TRVAR(GPCF, TX) takes in covariance function\n% of a Gaussian process GPCF and matrix TX that contains\n% training inputs. Returns variance vector C. Every element i\n% of C contains variance of input i in TX. This is a mandatory \n% subfunction used for example in prediction and energy computations.\n%\n%\n% See also\n% GPCF_SQUARED_COV, GP_COV, GP_TRCOV\n\n \n if isfield(gpcf, 'selectedVariables')\n x = x(:,gpcf.selectedVariables);\n end\n h = x.^2;\n if isequal(gpcf.interactions,'on')\n m=size(x,2);\n for xi1=1:m\n for xi2=xi1+1:m\n h = [h x(:,xi1).*x(:,xi2)];\n end\n end\n end\n if length(gpcf.coeffSigma2) == 1\n C=gpcf.coeffSigma2.*sum(h.^2,2);\n else\n C=sum(repmat(gpcf.coeffSigma2, size(x,1), 1).*h.^2,2);\n end\n C(abs(C) RECAPPEND\n\n if nargin == 2\n % Initialize the record\n reccf.type = 'gpcf_squared';\n \n % Initialize parameters\n reccf.coeffSigma2= [];\n\n % Set the function handles\n reccf.fh.pak = @gpcf_squared_pak;\n reccf.fh.unpak = @gpcf_squared_unpak;\n reccf.fh.lp = @gpcf_squared_lp;\n reccf.fh.lpg = @gpcf_squared_lpg;\n reccf.fh.cfg = @gpcf_squared_cfg;\n reccf.fh.cfdg = @gpcf_squared_cfdg;\n reccf.fh.cfdg2 = @gpcf_squared_cfdg2;\n reccf.fh.ginput = @gpcf_squared_ginput;\n reccf.fh.ginput2 = @gpcf_squared_ginput2;\n reccf.fh.ginput3 = @gpcf_squared_ginput3;\n reccf.fh.ginput4 = @gpcf_squared_ginput4;\n reccf.fh.cov = @gpcf_squared_cov;\n reccf.fh.trcov = @gpcf_squared_trcov;\n reccf.fh.trvar = @gpcf_squared_trvar;\n reccf.fh.recappend = @gpcf_squared_recappend;\n reccf.p=[];\n reccf.p.coeffSigma2=[];\n if ~isempty(ri.p.coeffSigma2)\n reccf.p.coeffSigma2 = ri.p.coeffSigma2;\n end\n\n else\n % Append to the record\n gpp = gpcf.p;\n \n reccf.interactions = gpcf.interactions;\n \n % record coeffSigma2\n reccf.coeffSigma2(ri,:)=gpcf.coeffSigma2;\n if isfield(gpp,'coeffSigma2') && ~isempty(gpp.coeffSigma2)\n reccf.p.coeffSigma2 = gpp.coeffSigma2.fh.recappend(reccf.p.coeffSigma2, ri, gpcf.p.coeffSigma2);\n end\n \n if isfield(gpcf, 'selectedVariables')\n reccf.selectedVariables = gpcf.selectedVariables;\n end\n end\nend\n\nfunction [F,L,Qc,H,Pinf,dF,dQc,dPinf,params] = gpcf_squared_cf2ss(gpcf,x)\n%GPCF_SQUARED_CF2SS Convert the covariance function to state space form\n%\n% Description\n% Convert the covariance function to state space form such that\n% the process can be described by the stochastic differential equation\n% of the form:\n% df(t)/dt = F f(t) + L w(t),\n% where w(t) is a white noise process. The observation model now \n% corresponds to y_k = H f(t_k) + r_k, where r_k ~ N(0,sigma2).\n%\n%\n\n % Check arguments\n if nargin < 2 || isempty(x), x = 0; end\n\n % Scaling\n x0 = min(x);\n \n % Define the model\n F = [0 1; 0 0]; \n L = [0; 1]; \n Qc = 0; \n H = [1 0];\n Pinf = [x0^2 x0; x0 1]*gpcf.coeffSigma2;\n dF = zeros(2,2,1);\n dQc = zeros(1,1,1);\n dPinf = [x0^2 x0; x0 1];\n params = {};\n\n % Set params\n params.stationary = false;\n \n % Check which parameters are optimized\n if isempty(gpcf.p.coeffSigma2), ind(1) = false; else ind(1) = true; end\n \n % Return only those derivatives that are needed\n dF = dF(:,:,ind);\n dQc = dQc(:,:,ind);\n dPinf = dPinf(:,:,ind);\n \nend", "meta": {"author": "gpstuff-dev", "repo": "gpstuff", "sha": "114937ec0a201306489a66cbba38283e722fb998", "save_path": "github-repos/MATLAB/gpstuff-dev-gpstuff", "path": "github-repos/MATLAB/gpstuff-dev-gpstuff/gpstuff-114937ec0a201306489a66cbba38283e722fb998/gp/gpcf_squared.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.3486032395372771}} {"text": "classdef ParadigmFBCSP < ParadigmDataflowSimplified\n % Paradigm for complex oscillatory processes using the filter-bank CSP algorithm.\n % Result = para_multiband_csp(Input-Data, Operation-Mode, Options...)\n %\n % Filter-bank CSP [1,2] is a simple extension of the basic CSP method (see ParadigmCSP), in which for\n % each of several time/frequency filters a set of CSP filters is learned, followed by log-variance\n % feature extraction, concatenation of all features (over all chosen spectral filters) and\n % subsequent machine learning. It is not a general replacement for CSP due to the problem of\n % overfitting, but is very useful whenever oscillatory processes in different frequency bands (and\n % with different spatial topographies) are jointly active, and their concerted behavior must be\n % taken into account for a given prediction task. Filter-bank CSP can also be used to capture\n % oscillations in multiple time windows, instead of frequency windows (for example for the detection\n % of complex event-related dynamics).\n %\n % Since the dimensionality of the feature space is larger than in CSP, and since complex\n % interactions may be present, a more complex classifier than the default LDA may be necessary to\n % learn an appropriate model. On the other hand, more flexibility amplifies the risk of overfitting\n % (especially with only little calibration data), so that the performance should always be compared\n % to standard CSP (and Spec-CSP). Another reason is that complex (relevant) interactions between\n % different frequency bands are seemingly rarely observed in practice. The most important\n % user-configurable parameters are the selection regions in time and frequency and the learner\n % component.\n %\n % Typical applications would be those in which either complex event-related oscillatory dynamics\n % happen (for example when reacting to a particular stimulus) and/or where non-trivial interactions\n % between frequency bands (e.g. alpha/theta) are relevant, such as, for example, in workload\n % measurements.\n %\n % Example: Consider a calibration data set in which a subject is maintaining and updating\n % different number of items in his/her working memory at different times, e.g. while performing\n % the n-Back task [2]. Events with types 'n1','n2','n3' indicate challenge stimuli in which the\n % respective number of items is being processed by the person. The goal is to be able to predict\n % the working-memory load of the person following the presentation of such a memory-related\n % challenge. An epoch of 3 seconds relative to each challenge is selected, and three different\n % regions are chosen, two of them over the entire interval, covering the theta and alpha ryhthm,\n % respectively, and one region that is restricted to a window around the time of heaviest\n % cognitive processing. The three regions are specified as a cell array of flt_select\n % parameters.\n %\n % data = io_loadset('data sets/mary/nback.eeg')\n % myapproach = {'FBCSP' 'SignalProcessing',{'EpochExtraction',[-0.5 2.5]}, ...\n % 'Prediction', {'FeatureExtraction',{'FreqWindows',[4 6; 7 15; 7 15],'TimeWindows',[-0.5 2.5; -0.5 2.5; 0.25 1.25]}, ...\n % 'MachineLearning',{'Learner','logreg'}}}\n % [loss,model,stats] = bci_train('Data',data, 'Approach','ParadigmFBCSP, 'TargetMarkers',{'n1','n2','n3'})\n %\n % References;\n % [1] Quadrianto Novi, Cuntai Guan, Tran Huy Dat, and Ping Xue, \"Sub-band Common Spatial Pattern (SBCSP) for Brain-Computer Interface\"\n % Proceedings of the 3rd International IEEE EMBS Conference on Neural Engineering Kohala Coast, Hawaii, USA, May 2-5, 2007\n % [2] Kai K. Ang, Zhang Y. Chin, Haihong Zhang, Cuntai Guan, \"Filter Bank Common Spatial Pattern (FBCSP) in Brain-Computer Interface\"\n % In 2008 IEEE International Joint Conference on Neural Networks (IEEE World Congress on Computational Intelligence) (June 2008), pp. 2390-2397.\n % [3] Owen, A. M., McMillan, K. M., Laird,A. R. & Bullmore, E. \"N-back working memory paradigm: A meta-analysis of normative functional neuroimaging studies.\"\n % Human Brain Mapping, 25, 46-59, 2005\n %\n % Name:\n % Filter-Bank CSP\n %\n % Christian Kothe, Swartz Center for Computational Neuroscience, UCSD\n % 2010-04-29\n \n methods\n \n function defaults = preprocessing_defaults(self)\n % define the default pre-processing parameters of this paradigm\n defaults = {'EpochExtraction',[0.5 3.5],'Resampling',200};\n end\n \n function model = feature_adapt(self,varargin)\n % adapt a feature representation using the CSP algorithm\n args = arg_define(varargin, ...\n arg_norep('signal'), ...\n arg({'patterns','PatternPairs'},3,uint32([1 1 64 10000]),'CSP patterns per band (times two).','cat','Feature Extraction'), ...\n arg({'shrinkage_cov','ShrinkageCovariance'},false,[],'Shrinkage covariance estimator. Whether to use shrinkage to estimate the covariance matrices.'), ...\n arg({'robust_cov','RobustCovariance'},false,[],'Robust covariance estimation. Whether to use robust cov estimation.'), ...\n arg({'freqwnds','FreqWindows'},[0.5 3; 4 7; 8 12; 13 30; 31 42],[0 0.5 200 1000],'Frequency bands of interest. Matrix containing one row for the start and end of each frequency band from which CSP patterns shall be computed. Values in Hz.','cat','Feature Extraction'), ...\n arg({'timewnds','TimeWindows'},[],[],'Time windows of interest. Matrix containing one row for the start and end of each time window from which CSP patterns shall be computed. Values in seconds. If both this and the freqwnds parameter are non-empty, they should have the same number of rows.','cat','Feature Extraction'), ...\n arg({'winfunc','WindowFunction'},'rect',{'barthann','bartlett','blackman','blackmanharris','bohman','cheb','flattop','gauss','hamming','hann','kaiser','nuttall','parzen','rect','taylor','triang','tukey'},'Type of window function. Typical choices are rect (rectangular), hann, gauss, blackman and kaiser.'),...\n arg({'winparam','WindowParameter','param'},[],[],'Parameter of the window function. This is mandatory for cheb, kaiser and tukey and optional for some others.','shape','scalar'));\n \n if args.signal.nbchan == 1\n error('Multi-band CSP does intrinsically not support single-channel data (it is a spatial filter).'); end\n if args.signal.nbchan < args.patterns\n error('Multi-band CSP prefers to work on at least as many channels as you request output patterns. Please reduce the number of pattern pairs.'); end\n if ~isempty(args.freqwnds) && ~isempty(args.timewnds) && size(args.freqwnds,1) ~= size(args.timewnds,1)\n error('If both time and frequency windows are specified, both arrays must have the same number of rows (together they define the windows in time and frequency).'); end\n if isempty(args.timewnds)\n args.timewnds = zeros(size(args.freqwnds,1),0); end\n if isempty(args.freqwnds)\n args.freqwnds = zeros(size(args.timewnds,1),0); end\n \n filters = [];\n patterns = [];\n % for each window\n for w = 1:max(size(args.freqwnds,1),size(args.timewnds,1))\n % pre-parse arguments for flt_window and flt_spectrum (for fast subsequent online use)\n time_args{w} = arg_report('vals',@flt_window,{'time',{args.timewnds(w,:),args.winfunc,args.winparam}});\n freq_args{w} = arg_report('vals',@flt_spectrum,{'freq',args.freqwnds(w,:)});\n for k=1:2\n % filter trial subrange in time and frequency\n data = exp_eval_optimized(flt_spectrum('signal',flt_window('signal',set_picktrials(args.signal,'rank',k),time_args{w}),freq_args{w}));\n if args.robust_cov\n covar{k} = hlp_diskcache('featuremodels',@cov_blockgeom,reshape(data.data,size(data.data,1),[])',max([data.nbchan*2,data.srate*2,size(data,3)]));\n else\n if args.shrinkage_cov\n covar{k} = hlp_diskcache('featuremodels',@cov_shrink,reshape(data.data,size(data.data,1),[])');\n else\n covar{k} = cov(reshape(data.data,size(data.data,1),[])');\n end\n end\n covar{k}(~isfinite(covar{k})) = 0;\n end\n [V,D] = eig(covar{1},covar{1}+covar{2}); %#ok\n P = inv(V); \n filters = [filters V(:,[1:args.patterns end-args.patterns+1:end])];\n patterns = [patterns P([1:args.patterns end-args.patterns+1:end],:)'];\n end\n model = struct('filters',{filters},'patterns',{patterns},'time_args',{time_args},'freq_args',{freq_args},'chanlocs',{args.signal.chanlocs});\n end\n \n function features = feature_extract(self,signal,featuremodel)\n W = length(featuremodel.freq_args);\n F = size(featuremodel.filters,2);\n T = size(signal.data,3);\n features = zeros(T,F);\n for w = 1:W\n % filter data in time & frequency\n data = exp_eval_optimized(flt_spectrum('signal',flt_window('signal',signal,featuremodel.time_args{w}),featuremodel.freq_args{w}));\n inds = (w-1)*(F/W)+(1:(F/W));\n for t=1:T\n features(t,inds) = log(var(data.data(:,:,t)' * featuremodel.filters(:,inds))); end\n end\n end\n \n function visualize_model(self,varargin) %#ok<*INUSD>\n args = arg_define([0 3],varargin, ...\n arg_norep({'myparent','Parent'},[],[],'Parent figure.'), ...\n arg_norep({'featuremodel','FeatureModel'},[],[],'Feature model. This is the part of the model that describes the feature extraction.'), ...\n arg_norep({'predictivemodel','PredictiveModel'},[],[],'Predictive model. This is the part of the model that describes the predictive mapping.'), ...\n arg({'patterns','PlotPatterns'},true,[],'Plot patterns instead of filters. Whether to plot spatial patterns (forward projections) rather than spatial filters.'), ...\n arg({'weight_scaled','WeightScaled'},false,[],'Scaled by weight. Whether to scale the patterns by weight.'));\n arg_toworkspace(args);\n \n % find the relevant components\n scores = predictivemodel.model.w;\n scores = sqrt(abs(scores));\n % optionally remove the bias if included in w\n if length(scores) == size(featuremodel.patterns,2)+1\n scores = scores(1:end-1); end \n % frequency labels\n % titles = repmat({'delta','theta','alpha','beta','gamma'},8,1); titles = titles(:);\n % extract relevant patterns\n patterns = featuremodel.patterns(:,find(scores)); %#ok\n filters = featuremodel.filters(:,find(scores)); %#ok\n % plot them\n if args.weight_scaled\n if args.patterns\n topoplot_grid(patterns,featuremodel.chanlocs,'scales',scores(find(scores))/max(scores)*1);\n else\n topoplot_grid(filters,featuremodel.chanlocs,'scales',scores(find(scores))/max(scores)*1);\n end\n else\n if args.patterns\n topoplot_grid(patterns,featuremodel.chanlocs);\n else\n topoplot_grid(filters,featuremodel.chanlocs);\n end\n end\n % figure;\n end\n \n function layout = dialog_layout_defaults(self)\n % define the default configuration dialog layout\n layout = {'SignalProcessing.Resampling.SamplingRate', 'SignalProcessing.EpochExtraction', '', ...\n 'Prediction.FeatureExtraction.FreqWindows', 'Prediction.FeatureExtraction.TimeWindows', ...\n 'Prediction.FeatureExtraction.WindowFunction', '', 'Prediction.FeatureExtraction.PatternPairs', '', ...\n 'Prediction.MachineLearning.Learner'};\n end\n \n function tf = needs_voting(self)\n tf = true;\n end\n end\nend\n\n", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/code/paradigms/ParadigmFBCSP.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548646660543, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.34853896456110484}} {"text": "%% Copyright (C) 2011-2012 by Jun He, Laura Balzano, and Arthur Szlam\n% \n% This file is part of the GRASTA library.\n% It is provided without any warranty of fitness\n% for any purpose. You can redistribute this file\n% and/or modify it under the terms of the GNU\n% Lesser General Public License (LGPL) as published\n% by the Free Software Foundation, either version 3\n% of the License or (at your option) any later version.\n% (see http://www.opensource.org/licenses for more info)\n\nfunction [ Unew, STATUSnew, OPTSnew ] = grasta_stream( y_Omega, idx, U0, STATUS,OPTIONS, OPTS)\n% grasta_stream is the streaming version of GRASTA which can be used for\n% online data processing\n%\n% [1] Jun He, Laura Balzano, and John C.S. Lui. Online Robust Subspace Tracking from Partial Information\n% http://arxiv.org/abs/1109.3827\n% [2] Jun He, Laura Balzano, and Arthur Szlam. Incremental gradient on the grassmannian for online foreground \n% and background separation in subsampled video. In IEEE Conference on Computer Vision and Pattern Recognition \n% (CVPR), June 2012.\n%\n% Usage:\n% [ Unew, STATUSnew, OPTSnew ] = grasta_stream( y_Omega, idx, U0, STATUS, OPTIONS, OPTS)\n% Inputs:\n% y_Omega: current partial observation of a full data vector\n% idx: the observed indices of y_Omega\n% U0: the current estimated subspace\n% STATUS: the current status of GRASTA\n% last_mu: \\mu_{t-1} for adaptive step rule\n% step_scale: the estimated step_scale constant for adaptive\n% step-size rule\n% lelve: the current level of the \"Multi-Level\" adaptive rule\n% last_gamma and last_w: previous gradient = last_gamma*last_w'\n%\n% OPTIONS: the options of GRASTA \n% CONSTANT_STEP: default 0, will use multi-level step-size rule; > 0 will\n% use constant step-size rule\n% DIM_M : the ambient dimension\n% RANK : the estimated low-rank of the underlying system\n% rho : ADMM constant step \n% ITER_MAX: the max_iter for ADMM solver\n% TOL : the stopping tolerance of admm_srp / mex_srp\n%\n% OPTS: the current options for the subproblem of GRASTA\n% refer to mex_srp.cpp or admm_srp.m\n% Outputs:\n% Unew: the updated subspace \n% STATUSnew: the updated running status\n% OPTSnew: the updated options for the subproblem of GRASTA\n%\n% Author: Jun He, Laura Balzano\n% Email: hejun.zz@gmail.com, sunbeam@ece.wisc.edu\n% Date: Sept. 01, 2012\n%\n%\n\nLEVEL_FACTOR = 2;\n\nif isfield(OPTIONS,'MIN_MU'),\n MIN_MU = OPTIONS.MIN_MU;\nelse\n MIN_MU = 1;\nend\n\nif isfield(OPTIONS,'MAX_MU'),\n MAX_MU = OPTIONS.MAX_MU;\nelse\n MAX_MU = 15;\nend\n\n\nif isfield(OPTIONS,'USE_MEX'),\n USE_MEX = OPTIONS.USE_MEX;\nelse\n USE_MEX = 1;\nend\n\nif isfield(OPTIONS,'CONSTANT_STEP'),\n CONSTANT_STEP = OPTIONS.CONSTANT_STEP;\nelse\n CONSTANT_STEP = 0;\nend\n\n\nif isfield(OPTIONS,'DIM_M'),\n DIM_M = OPTIONS.DIM_M;\nelse\n error('Should specify OPTIONS.DIM_M data ambient dimension!!!\\n');\nend\n\nif isfield(OPTIONS,'ITER_MIN'),\n MIN_ITER = OPTIONS.ITER_MIN;\nelse\n MIN_ITER = 5;\nend\n\nif isfield(OPTIONS,'ITER_MAX'),\n ITER_MAX = OPTIONS.ITER_MAX;\nelse\n ITER_MAX = 60;\nend\n\nif isfield(OPTIONS,'TOL'),\n TOL = OPTIONS.TOL;\nelse\n TOL = 1e-6;\nend\n\n\nif isfield(OPTIONS,'MAX_LEVEL'),\n MAX_LEVEL = OPTIONS.MAX_LEVEL;\nelse\n MAX_LEVEL = 20;\nend\n\n\n\nif isfield(OPTIONS,'RANK'),\n RANK = OPTIONS.RANK;\nelse\n error('Should specify OPTIONS.RANK!!!\\n');\nend\n\nif isfield(OPTIONS,'QUIET'),\n QUIET = OPTIONS.QUIET;\nelse\n QUIET = 0;\nend\n\nDEFAULT_MU_HIGH = (MAX_MU-1)/2; \nDEFAULT_MU_LOW = MIN_MU + 2;\n\n\n% If we first call GRASTA_stream then do the following initilization \nif STATUS.init == 0, \n STATUS.init = 1; % Do not enter this initial part any longer \n STATUS.curr_iter = 0; % For debug\n \n STATUS.last_mu = MIN_MU; \n STATUS.level = 0;\n STATUS.step_scale = 0;\n STATUS.last_w = zeros(RANK,1);\n STATUS.last_gamma = zeros(DIM_M,1);\n\n OPTS.TOL = TOL;\n OPTS.MAX_ITER = MIN_ITER; % the max iteration of ADMM at level=0\n OPTS.QUIET = 1; \n\n if isfield(OPTIONS,'rho'),\n OPTS.RHO = OPTIONS.rho;\n else\n OPTS.RHO = 1.8;\n end\n \n U0 = orth(randn(DIM_M,RANK));\nend\n\n%%%%%%%%%%%%%%%\n% main framework of GRASTA\nU_Omega = U0(idx,:);\n\nif USE_MEX,\n [s_t, w, ldual] = mex_srp(U_Omega, y_Omega, OPTS);\nelse\n [s_t, w, ldual] = admm_srp(U_Omega, y_Omega, OPTS);\nend\n\ngamma_1 = ldual;% + OPTS.RHO*(U_Omega*w + s_t - y_Omega);\nUtDual_omega = U_Omega' * gamma_1;\ngamma_2 = U0 * UtDual_omega;\ngamma = zeros(DIM_M,1);\ngamma(idx) = gamma_1;\ngamma = gamma - gamma_2;\n\ngamma_norm = norm(gamma);\nw_norm = norm(w);\nsG = gamma_norm * w_norm;\n\n\n% Here we use the adaptive step-size rule for SGD. The adaptive can work\n% well for both dynamic and static subspace tracking tasks\n\n% 1. determine the step scale from the first observation\nif ~STATUS.step_scale,\n STATUS.step_scale = 0.5*pi*(1+MIN_MU)/sG;\n \n if ~QUIET,\n fprintf('Level 0: %.2e\\n',STATUS.step_scale);\n end\nend\n\n% 2. inner product of previous grad and current grad\ngrad_ip = trace(STATUS.last_w * (STATUS.last_gamma' * gamma) * w');\n\n%%% avoid inner product too large\nnormalization = norm(STATUS.last_gamma * STATUS.last_w','fro') * norm(gamma * w','fro');\nif normalization == 0,\n grad_ip_normalization = 0;\nelse\n grad_ip_normalization = grad_ip/normalization;\nend\n%%%\n\n\n% 3. if the two consecutive grad in the same direction, we take a larger\n% step along the gradient direction, otherwise take a small step along the\n% gradient direction\nSTATUS.last_mu = max(STATUS.last_mu + sigmoid(-grad_ip_normalization) , MIN_MU);\n\nif CONSTANT_STEP > 0,\n t = CONSTANT_STEP;\nelse\n % should not take a step larger than pi/2\n t = STATUS.step_scale * LEVEL_FACTOR^(-STATUS.level) * sG / (1+STATUS.last_mu);\n if t>=pi/3,\n t = pi/3;\n end\n \n % Adjust the level\n bShrUpd = 0;\n if STATUS.last_mu <= MIN_MU,\n if STATUS.level > 1,\n bShrUpd = 1;\n STATUS.level = STATUS.level - 1;\n \n if ~QUIET,\n fprintf('multi-level adaption - decreasing, t:%.2e, vectors: %d, level: %d\\n',...\n t,STATUS.curr_iter, STATUS.level);\n end\n STATUS.curr_iter = 0;\n end\n \n STATUS.last_mu = DEFAULT_MU_LOW;\n elseif STATUS.last_mu > MAX_MU,\n if STATUS.level < MAX_LEVEL,\n bShrUpd = 1;\n STATUS.level = STATUS.level + 1;\n \n if ~QUIET,\n fprintf('multi-level adaption - increasing, t:%.2e, vectors: %d, level: %d\\n',...\n t, STATUS.curr_iter, STATUS.level);\n end\n STATUS.curr_iter = 0;\n STATUS.last_mu = DEFAULT_MU_HIGH;\n else\n STATUS.last_mu = MAX_MU;\n end\n end\n \n if bShrUpd,\n if STATUS.level>=0 && STATUS.level <4, % [0,4)\n OPTS.MAX_ITER = MIN_ITER;\n elseif STATUS.level>=4 && STATUS.level <7, % [4,7)\n OPTS.MAX_ITER = min(MIN_ITER*2, ITER_MAX);\n elseif STATUS.level>=7 && STATUS.level <10, % [7,10)\n OPTS.MAX_ITER = min(MIN_ITER*4, ITER_MAX);\n elseif STATUS.level>=10 && STATUS.level <14, % [10,14)\n OPTS.MAX_ITER = min(MIN_ITER*8, ITER_MAX);\n else\n OPTS.MAX_ITER = ITER_MAX; % [14,...)\n end\n \n if ~QUIET,\n fprintf('Will use %d ADMM iterations in level %d\\n',OPTS.MAX_ITER, STATUS.level);\n end\n end\n \nend\n\n% 4. update the gradient for further step size update\nSTATUS.last_gamma = gamma;\nSTATUS.last_w = w;\n\nSTATUS.grad_ip = grad_ip_normalization; % just for debugging\n\n\n% Take the gradient step along Grassmannian geodesic.\nalpha = w/w_norm;\nbeta = gamma/gamma_norm;\nstep = (cos(t)-1)*U0*(alpha*alpha') - sin(t)*beta*alpha';\n\nU0 = U0 + step;\n\n%%\n\nSTATUS.s_t = s_t;\nSTATUS.w = w;\nSTATUS.ldual = ldual;\nSTATUS.SCALE = 1;\nSTATUS.curr_iter = STATUS.curr_iter + 1;\n\nSTATUS.grasta_t = t;\n\n%\n%%%%%%%%%%%%%%%%%%%%%%\n\nUnew = U0;\nSTATUSnew = STATUS;\nOPTSnew = OPTS;\nend\n\n\n%% Function of Sigmoid\n\nfunction fval = sigmoid(x)\nFMIN = -1; FMAX = 1;\nomega = 0.1;\n\nfval = FMIN + (FMAX - FMIN)/(1 - (FMAX/FMIN)*exp(-x/omega));\nend", "meta": {"author": "andrewssobral", "repo": "lrslibrary", "sha": "06d457349cb5f1fc56a583cd61af9f1d5150e3a1", "save_path": "github-repos/MATLAB/andrewssobral-lrslibrary", "path": "github-repos/MATLAB/andrewssobral-lrslibrary/lrslibrary-06d457349cb5f1fc56a583cd61af9f1d5150e3a1/algorithms/st/GRASTA/grasta_stream.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548646660542, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.3485389645611048}} {"text": "function [formula, protons] = getFormulaFromInChI(InChI)\n% Extracts the chemical formula of a given compound from\n% the InChI string provided\n%\n% USAGE:\n%\n% [formula, protons] = getFormulaFromInChI(InChI)\n%\n% INPUT:\n% InChI: The Inchi String of the chemical formula (e.g. InChI=\n% extract formula from `InChI = 1S/C3H4O3/c1-2(4)3(5)6/h1H3, (H,5,6)/p-1` for pyruvate\n%\n% OUTPUTS:\n% formula: The chemical formula (including the protonation state\n% protons: The total number of protons\n\n[token,rem] = strtok(InChI, '/');\nformula=strtok(rem, '/');\n\n%This could be a composite formula, so combine it.\ntokens = strsplit(formula,'.');\n\n%The protonation state can also modify the formula! To get it, we remove\n%any reconstruction fields, as they do not influence it.\nInChI = regexprep(InChI,'/r.*','');\np_layer = regexp(InChI,'/p(.*?)/|/p(.*?)$','tokens');\nprotonationProtons = 0;\nif ~isempty(p_layer)\n individualProtons = cellfun(@(x) {strsplit(x{1},';')},p_layer);\n protonationProtons = cellfun(@(x) sum(cellfun(@(y) eval(y) , x)), individualProtons);\nend\n\n%Calc the coefs for all formulas\nif (numel(tokens) > 1) || (~isempty(regexp(formula,'(^[0-9]+)'))) || (~isempty(p_layer))\n CoefLists = cellfun(@(x) calcFormula(x), tokens,'UniformOutput',0);\n if ~isempty(p_layer)\n %CoefLists = [CoefLists;{{'H';protonationProtons}}];%was crashing\n %with formula C62H90N13O14P.Co.H2O\n CoefLists{end+1} = {'H';protonationProtons};\n end\n %and now, combine them.\n Elements = {};\n Coefficients = [];\n for i = 1:numel(CoefLists)\n if isempty(CoefLists{i})\n %This should only happen, if there was no actual formula.\n continue\n end\n currentForm = CoefLists{i};\n Elements = [Elements,setdiff(currentForm(1,:),Elements)];\n current_coefs = cell2mat(currentForm(2,:));\n [A,B] = ismember(Elements,currentForm(1,:));\n %Extend the coefficients if necessary\n Coefficients(end+1:numel(Elements)) = 0;\n Coefficients(A) = Coefficients(A)+current_coefs;\n end\n\n Coefs = num2cell(Coefficients);\n Coefs(cellfun(@(x) x == 1, Coefs)) = {[]};\n Coefs = cellfun(@(x) num2str(x) , Coefs,'UniformOutput',0);\n if nargout > 1\n protons = Coefficients(ismember(Elements,'H'));\n end\n formula = strjoin([Elements , {''}],Coefs);\nelse\n %had to add this for some inchi, e.g.\n %InChI=1/C21H30O4/c1-19-8-5-14(23)11-13(19)3-4-15-16(19)6-9-20(2)17(15)7-10-21(20,25)18(24)12-22/h11,15-17,22,25H,3-10,12H2,1-2H3/t15-,16+,17+,19+,20+,21+/m1/s1\n protons = numAtomsOfElementInFormula(formula, 'H',0);\nend\n\nzero='0';\nindZero=strfind(formula,zero);\nif ~isempty(indZero)\n if isletter(formula(indZero-1))\n if 0\n warning('Formula contains a zero with a letter preceeding it, replacing with letter.')\n fprintf('%s%s\\n','Formula before:, ', formula)\n end\n formula = strrep(formula, formula(indZero-1:indZero), formula(indZero-1));\n if 0\n fprintf('%s%s\\n','Formula after:, ', formula)\n end\n end\nend\n\nend\n\n\nfunction [CoefList] = calcFormula(Formula)\nmultiplier = 1;\nisReplicated = regexp(Formula,'(^[0-9]+)','tokens');\nElementTokens = regexp(Formula,'([A-Z][a-z]?)([0-9]*)','tokens');\nElements = cellfun(@(x) x{1}, ElementTokens,'UniformOutput',0);\nCoefs = cellfun(@(x) str2num(x{2}), ElementTokens,'UniformOutput',0);\nCoefs(cellfun(@isempty, Coefs)) = {1};\n\nif ~isempty(isReplicated)\n multiplier = str2num(isReplicated{1}{1});\n Coefs = cellfun(@(x) x*multiplier, Coefs,'UniformOutput',0);\nend\n\nCoefList = [Elements;Coefs];\nend\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/src/dataIntegration/chemoInformatics/inchi/getFormulaFromInChI.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7025300698514777, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.34852083267109213}} {"text": "function [returns,interval] = realized_return_filter(price,time,timeType,samplingType,samplingInterval,subsamples)\n% THESE COMMENTS ARE WRONG!!!\n% Computes the Quantile Realized Variance of Christensen, Oomen and Podolskij (2008),\n% the MinRV and MedRV estimator of Andersen, Dobrev and Shaumberg and the\n% general symmetrized version suggested by Sheppard in a discussion of COP\n%\n% USAGE:\n% [RETURN,INTERVAL] = realized_return_filter(PRICE,TIME,TIMETYPE,SAMPLINGTYPE,SAMPLINGINTERVAL,SUBSAMPLES)\n%\n% INPUTS:\n% PRICE - m by 1 vector of high frequency prices\n% TIME - m by 1 vector of times where TIME(i) corresponds to PRICE(i)\n% TIMETYPE - String describing the way times are measured\n% 'wall' 24-hour clock of the form HHMMSS, e.g. 101543 or 153217\n% 'seconds' Time measured in seconds past midnight on the first day.\n% 'unit' Unit normalized date format, e.g. .1, .234, .9\n% Unit normalized times are more general than the other types and can be\n% applied to data from more than one calendar day\n% SAMPLINGTYPE - String describing the type of sampling to use when\n% filtering PRICE\n% 'CalendarTime' - Sample in calendar time using observations separated by\n% SAMPLINGINTERVAL seconds\n% 'CalendarUniform' - Sample in calendar time using SAMPLINGINTERVAL\n% observations spread uniformly between TIME(1) and TIME(m)\n% 'BusinessTime' - Sample in business (tick) time using observation separated\n% by SAMPLINGINTERVALticks\n% 'BusinessUniform' - Sample in business (tick) time using observations\n% uniformly spaced in business time.\n% 'Fixed' - Sample at specific points in time. When using fixed,\n% SAMPLINGINTERVAL must be a n by 1 vector of times with the same TIMETYPE\n% as TIME (i.e. seconds if TIME is in seconds)\n% SAMPLINGINTERVAL - Scalar integer or n by 1 vector whose meaning depends on the selected SAMPLINGTYPE\n% SUBSAMPLES - [OPTIONAL] Integer value containing the number of subsamples to use when\n% computing RRSS. It must be the case that SUBSAMPLE0 will produce an estimator based on jittering the starting\n% point over floor(linspace(0,(SUBSAMPLES)/(SUBSAMPLES+1),SUBSAMPLES+1)*SAMPLESPERBIN)+1\n% For example, if SUBSAMPLES = 3 and SAMPLESPERBIN = 20, then the starting\n% points for the four RR estimators will be observations 1, 6, 11 and 16. If\n% omitted SUBSAMPLE = 0 and RRSS=RR.\n%\n% OUTPUTS:\n% RETURNS - Quantile realized variance vector (k by 1) corresponding to the values in QUANTILES\n% INTERVAL - Subsample based version of RQ. RQSS = RQ if SUBSAMPLES = 0\n%\n% COMMENTS:\n%\n% EXAMPLES:\n%\n%\n\n% Copyright: Kevin Sheppard\n% kevin.sheppard@economics.ox.ac.uk\n% Revision: 1 Date: 5/1/2008\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% InputChecking\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nif nargin<5 || nargin>6\n error('Seven or eight inputs required.')\nend\n\nif size(price,2)>size(price,1)\n price=price';\nend\nif size(price,2)>1\n error('PRICE must be a m by 1 vector.')\nend\nif size(time,2)>size(time,1)\n time=time';\nend\nif any(diff(time)<0)\n error('TIME must be sorted and increasing')\nend\nif size(time,2)>1 || length(time)~=length(price)\n error('TIME must be a m by 1 vector.')\nend\n% Inserted to protect against inputing integer times\ntime = double(time);\n\ntimeType=lower(timeType);\nif ~ismember(timeType,{'wall','seconds','unit'})\n error('TIMETYPE must be one of ''wall'', ''seconds'' or ''unit''.');\nend\nsamplingType=lower(samplingType);\nif ~ismember(samplingType,{'calendartime','calendaruniform','businesstime','businessuniform','fixed'})\n error('SAMPLINGTYPE must be one of ''CalendarTime'', ''CalendarUniform'', ''BusinessTime'', ''BusinessUniform'' or ''Fixed''.');\nend\n\nm=size(price,1);\nt0=time(1);\ntT=time(m);\nif ismember(samplingType,{'calendartime','calendaruniform','businesstime','businessuniform'})\n % Must be a scalar integer\n if ~isscalar(samplingInterval) || floor(samplingInterval)~=samplingInterval || samplingInterval<1\n error('SAMPLINGINTERVAL must be a positive integer for the SAMPLINGTYPE selected.')\n end\nelse\n if size(samplingInterval,2)>size(samplingInterval,1)\n samplingInterval=samplingInterval';\n end\n if ~(any(samplingInterval>=t0) && any(samplingInterval<=tT))\n error('At least one sampling interval must be between min(TIME) and max(TIME) when using ''Fixed'' as SAMPLINGTYPE.')\n end\n if any(diff(samplingInterval)<=0)\n error('When using ''Fixed'' as SAMPLINGTYPE the vector of sampling times in SAMPLINGINTERVAL must be sorted and strictly increasing.')\n end\nend\n\n% SUBSAMPLES\nif nargin==6 && ~isempty(subsamples)\n if ~isscalar(subsamples) || subsamples<0 || floor(subsamples)~=subsamples\n error('SUBSAMPLES must be a non-negative integer.')\n end\nelse\n subsamples=0;\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Input Checking\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% Convert if wall to compute the interval\nif strcmp(timeType,'wall')\n time=wall2seconds(time);\n timeType = 'seconds';\nend\n\n% Initialize the return cell arrays and the interval vector\nreturns=cell(subsamples+1,1);\ninterval=zeros(subsamples+1,1);\n% 1. Filter the price\nlogPrice = log(price);\n[filteredLogPrice,filteredTimes] = realized_price_filter(logPrice ,time,timeType,samplingType,samplingInterval);\nreturns{1} = diff(filteredLogPrice);\ninterval(1) = 1;\n\n\nif subsamples>0\n % Initialize the place holder for rvSS and rvAdjustment\n % Get the number of filtered times\n n = size(filteredTimes,1);\n % Compute the length of time used in computing the realized variance to\n % bias adjust the subsample RVs\n baseDifference = filteredTimes(n) - filteredTimes(1);\n switch lower(samplingType)\n case {'calendartime','calendaruniform','fixed'}\n % Uniform sampling in CT so the gap is constant\n gap=diff(filteredTimes);\n % The stepsize is constant\n step = gap /(subsamples+1);\n if ismember(samplingType,{'calendartime','calendaruniform'})\n step = [step;mean(step)];\n else\n step = [step;step(length(step))];\n end\n for i=1:subsamples\n thisSampleTime = filteredTimes;\n % Need to compute times for this subsample\n thisSampleTime = thisSampleTime(1:n)+i*step;\n % Use these times to filter the price\n filteredLogPrice = realized_price_filter(logPrice,time,'unit','fixed',thisSampleTime);\n % Compute returns\n returns{i+1} = diff(filteredLogPrice);\n % Compute the ith subsample RV\n % The adjustment depends on the amount of time used in this\n % subsample relative to the full sample RV\n interval(i+1) = (thisSampleTime(n-1)-thisSampleTime(1))/baseDifference;\n end\n case {'businesstime', 'businessuniform'}\n % Uniform sampling in business time\n if strcmp(samplingType,'businesstime')\n % If BT then samplingInterval contains the number of ticks to skip\n originalIndices = 1:samplingInterval:m;\n if ~ismember(m,originalIndices)\n originalIndices = [originalIndices m];\n end\n gap=samplingInterval;\n else\n % If businessuniform then gap will be average\n originalIndices = floor(linspace(1,m,samplingInterval));\n if ~ismember(m,originalIndices)\n originalIndices = [originalIndices m];\n end\n gap = m/samplingInterval;\n end\n % The step size is constant\n step = gap/(subsamples+1);\n for i=1:subsamples\n % The indices indicate which points to use since the\n % sampling is linear in ticks\n indices = floor(originalIndices + step*i);\n indices(indices>m) = m;\n returns{i+1} = diff(logPrice(indices));\n interval(i+1) = (time(max(indices))-time(min(indices)))/baseDifference;\n end\n end\nend", "meta": {"author": "bashtage", "repo": "mfe-toolbox", "sha": "9622b6c546bc6d649fd9bf0a36a7fcd53872e04a", "save_path": "github-repos/MATLAB/bashtage-mfe-toolbox", "path": "github-repos/MATLAB/bashtage-mfe-toolbox/mfe-toolbox-9622b6c546bc6d649fd9bf0a36a7fcd53872e04a/realized/realized_return_filter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.34852082649161226}} {"text": "function output = fourier2crsspctrm(cfg, freq)\n\n% FOURIER2CRSSPCTRM transforms a fourier-containing freq-structure \n% into a crsspctrm-containing freq-structure, in which the\n% powerspectra are also contained in the cross-spectra, being a \n% channelcombination of a channel with itself.\n%\n% Use as\n% [freq] = fourier2crsspctrm(cfg, freq)\n%\n% where you have the following configuration options:\n% cfg.channel = cell-array with selection of channels,\n% see CHANNELSELECTION for details\n% cfg.channelcmb = cell-array with selection of combinations between\n% channels, see CHANNELCOMBINATION for details\n% cfg.keeptrials = 'yes' or 'no' (default)\n% cfg.foilim = 2-element vector defining your frequency limits of \n% interest. By default the whole frequency range of the \n% input is taken.\n%\n\n% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org\n% for the documentation and details.\n%\n% FieldTrip is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% FieldTrip is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with FieldTrip. If not, see .\n%\n% $Id$\n\nif ~isfield(cfg, 'channel'), cfg.channel = {'all'}; end\nif ~isfield(cfg, 'channelcmb'), cfg.channelcmb = {}; end\nif ~isfield(cfg, 'foilim'), cfg.foilim = [freq.freq(1) freq.freq(end)]; end\nif ~isfield(cfg, 'keepfourier'), cfg.keepfourier = 'no'; end\nif ~isfield(cfg, 'feedback'), cfg.feedback = 'text'; end\n\n%select the channels on which the power-spectra will be computed\nchn = ft_channelselection(cfg.channel,freq.label);\nfor j = 1:length(chn)\n chnindx(j,1) = find(strcmp(chn(j), freq.label));\n %chnindx(j,1) = find(strcmp(chn{j}, freq.label));\nend\n\n%convert the channelcombinations to indices\nchncmb = ft_channelcombination(cfg.channelcmb, freq.label);\ncmbindx = zeros(size(chncmb,1),2);\nfor j = 1:size(chncmb,1)\n cmbindx(j,1) = find(strcmp(chncmb(j,1), freq.label));\n cmbindx(j,2) = find(strcmp(chncmb(j,2), freq.label));\n %cmbindx(j,1) = find(strcmp(chncmb{j,1}, freq.label));\n %cmbindx(j,2) = find(strcmp(chncmb{j,2}, freq.label));\nend\n\n%dimensionality of the input data\nNrpt = length(freq.cumtapcnt);\nNfrq = size(freq.fourierspctrm,3);\nNtim = size(freq.fourierspctrm,4);\nNchn = length(chnindx);\nNcmb = size(cmbindx,1);\n\n%%FIXME\n%if Ntim>1, ft_error('correct handling of time-frequency data is not yet implemented, no information about tapers is available'); end\n\n%keeping track of the tapers\n%in the case of tfr fourier-data cumtapcnt is highly redundant; for each frequency\n%the number of tapers is equal, as well as for each trial, thus it is sufficient to\n%reduce the original cumtapcnt to a vector of Ntrlx1 containing the number of tapers\ncumtapcnt = freq.cumtapcnt;\nif ~isempty(strfind(freq.dimord, 'time')),\n %cumtapcnt is NtrlxNfrqxNtim; create just one column-vector\n cumtapcnt = ones(size(cumtapcnt,1),1).*unique(cumtapcnt(~isnan(cumtapcnt(:))));\nend\nsumtapcnt = cumsum([0; cumtapcnt(:)]);\n\npowspctrm = zeros(Nrpt, Nchn, Nfrq, Ntim);\nprogress('init', cfg.feedback, 'computing single-trial power-spectral densities');\nfor j = 1:Nrpt\n progress(j/Nrpt, 'trial %d/%d\\n', j, Nrpt);\n tmp1 = freq.fourierspctrm([1+sumtapcnt(j):sumtapcnt(j+1)], chnindx, :, :);\n tmp2 = freq.fourierspctrm([1+sumtapcnt(j):sumtapcnt(j+1)], chnindx, :, :);\n powspctrm(j, :, :, :) = squeeze(sum( tmp1 .* conj(tmp2), 1) ./ size(tmp1,1));\nend\nprogress('close');\n\ncrsspctrm = complex(zeros(Nrpt, Ncmb, Nfrq, Ntim), zeros(Nrpt, Ncmb, Nfrq, Ntim));\nprogress('init', cfg.feedback, 'computing single-trial cross-spectral densities');\nfor j = 1:Nrpt\n progress(j/Nrpt, 'trial %d/%d\\n', j, Nrpt);\n tmp1 = freq.fourierspctrm([1+sumtapcnt(j):sumtapcnt(j+1)], cmbindx(:,1), :, :);\n tmp2 = freq.fourierspctrm([1+sumtapcnt(j):sumtapcnt(j+1)], cmbindx(:,2), :, :);\n crsspctrm(j, :, :, :) = squeeze(sum( tmp1 .* conj(tmp2), 1) ./ size(tmp1,1));\nend\nprogress('close');\n\noutput.dimord = freq.dimord;\noutput.freq = freq.freq;\noutput.label = chn;\noutput.labelcmb(:,1) = freq.label(cmbindx(:,1));\noutput.labelcmb(:,2) = freq.label(cmbindx(:,2));\noutput.cumtapcnt = freq.cumtapcnt;\ntry, output.grad = freq.grad; end\ntry, output.time = freq.time; end\noutput.powspctrm = powspctrm;\noutput.crsspctrm = crsspctrm;\nif strcmp(cfg.keepfourier, 'yes'), output.fourierspctrm = freq.fourierspctrm; end \n\nif isempty(output.crsspctrm), output = rmfield(output, 'crsspctrm'); end\nif isempty(output.labelcmb ), output = rmfield(output, 'labelcmb' ); end\n\n% add information about the version of this function to the configuration\ncfg.version.name = mfilename('fullpath');\ncfg.version.id = '$Id$';\n\n% remember the configuration details of the input data\ntry, cfg.previous = freq.cfg; end\n\n% remember the exact configuration details in the output \noutput.cfg = cfg;\n\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/private/fourier2crsspctrm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.3484376866260385}} {"text": "function parseOut = parser(lexIn)\n%STRCONVPARSER LL(1) parser for mathematical expressions\n% PARSEOUT = STRCONVPARSER(LEXIN) returns a syntax tree of expressions so that\n% it can be converted to a format Chebfun is able to work with. The input,\n% LEXIN, is the output of the method STRCONVLEXER(), and is a cell array of\n% strings, containaining the tokens of strings.\n%\n% This method implements a LL(1) parser, a technique from compiler theory. For\n% more details, see e.g.,\n% [1] Aho, Sethi, Ullman, Compilers: Principles, Techniques, and Tools,\n% Addison-Wesley, 1986.\n%\n% See also: STRINGPARSER, STRINGPARSER/STR2ANON, STRINGPARSER/LEXER.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers. \n% See http://www.chebfun.org/ for Chebfun information.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Developers note: Usually, a parser relies on having access to pointers, which\n% is not possible in MATLAB. We get around this issue using global variables.\n%\n% TODO: Can we now get around this? See #515.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% Initialize all global variables\nglobal NEXT\nglobal COUNTER\nglobal LEX\nglobal STACK\n\n% Enter the main routine\nparseMain(lexIn);\n\n% Return the stored stack\nparseOut = STACK;\n\n% Clear all global variables\nNEXT = [];\nCOUNTER = [];\nLEX = [];\nSTACK = [];\n\nend\n\nfunction parseMain(lexIn)\n%PARSEMAIN The main parsing routine, starts the recursive parsing.\n\nglobal NEXT\nglobal STACK\nglobal LEX\nglobal COUNTER\n\nCOUNTER = 1;\nLEX = lexIn;\nNEXT = char(LEX(COUNTER, 2));\nSTACK = [];\n\n% Our expression can only start with certain labels, make sure we are\n% starting with one of them.\nvalidTypes = {'NUM', 'VAR', 'INDVAR', 'PDEVAR', 'LAMBDA',...\n 'FUNC1', 'FUNC2', 'FUNC3', 'UN-', 'UN+', 'LPAR'};\n\nif ( any(strcmp(NEXT, validTypes)) )\n \n % Enter the recursion and check for successful termination.\n parseExpA();\n \n % We've put a $ at the end of the lexer output. Hence, we have only\n % successfully parsed our string if the only remaining token left is a\n % $ sign.\n success = match('$');\n \n if ( ~success )\n reportError('Parse:end', ...\n 'Input expression ended in unexpected manner.');\n end\n \nelse\n \n reportError('Parse:start', 'Input field started with unaccepted symbol.');\n \nend\n\nend\n\n% The following is the allowed grammar of mathematical expressions in the\n% chebgui (¬ denotes an empty symbol):\n%\n% ExpA -> ExpA COMMA Exp0\n% ExpA -> Exp0\n% Exp0 -> Exp0 OP= Exp05\n% Exp0 -> Exp05\n% Exp05 -> Exp05 OPREL Exp1 where OPREL can be OP>, OP>=, OP<, OP<=\n% Exp05 -> Exp1\n% Exp1 -> Exp1 OP+ Exp2\n% Exp1 -> Exp1 OP- Exp2\n% Exp1 -> Exp2\n% Exp2 -> Exp2 OP* Exp3\n% Exp2 -> Exp2 OP/ Exp3\n% Exp2 -> Exp3\n% Exp3 -> Exp3 OP^ Exp4\n% Exp3 -> Exp4\n% Exp4 -> UN+ Exp4\n% Exp4 -> UN- Exp4\n% Exp4 -> Exp5\n% Exp5 -> NUM\n% Exp5 -> INDVAR\n% Exp5 -> PDEVAR\n% Exp5 -> LAMBDA\n% Exp5 -> VAR\n% Exp5 -> VAR ExpDer\n% Exp5 -> VAR LPAR ExpList RPAR\n% Exp5 -> VAR ExpDer LPAR ExpList RPAR\n% Exp5 -> FUNC1 LPAR Exp1 RPAR\n% Exp5 -> FUNC2 LPAR Exp1 COMMA Exp1 RPAR]\n% Exp5 -> FUNC3 LPAR Exp1 COMMA Exp1 COMMA Exp1 RPAR\n% Exp5 -> LPAR Exp1 RPAR\n% ExpDer -> DER\n% ExpDer -> ¬\n% ExpList -> Exp1\n% ExpList -> Exp1 COMMA STR\n\nfunction parseExpA()\n\nparseExp0();\nparseExpApr();\n\nend\n\nfunction parseExp0()\n\nparseExp05();\nparseExp0pr();\n\nend\n\nfunction parseExp05()\n\nparseExp1();\nparseExp05pr();\n\nend\n\nfunction parseExp1()\n\nparseExp2();\nparseExp1pr();\n\nend\n\nfunction parseExp2()\n\nparseExp3();\nparseExp2pr();\n\nend\n\nfunction parseExp3()\n\nparseExp4();\nparseExp3pr();\n\nend\n\nfunction parseExp4()\n\nparseExp5();\n\nend\n\nfunction parseExp5()\n\nglobal NEXT\nglobal COUNTER\nglobal LEX\n\n% We begin by checking whether we have hit a terminal case. In that case,\n% we push that into the stack. We need to treat variables with _ in the\n% names separately, as we only allow certain operators around the time\n% derivative.\nif ( strcmp(NEXT, 'VAR') )\n % Create a new tree for later use, corresponding to the dependent\n % variable\n tempLeaf = struct('center', {{char(LEX(COUNTER)), char(NEXT)}}, ...\n 'pdeflag', 0);\n \n % Push the variable onto the stack so that we can take the correct\n % actions if we have derivatives or expressions on the form u(...)\n % involved. If not, we'll simply pop it later.\n push(tempLeaf);\n\n % Begin by advancing as usual.\n advance();\n \n % If there follows a derivative symbol, ', we parse that\n parseExpDer();\n \n % If we then have a u(3) or u(3,left) situation (or u'(3) etc.), we\n % parse that as required\n parseExpList();\n \nelseif ( any(strcmp(NEXT, {'NUM', 'INDVAR', 'LAMBDA', 'STR'})) )\n newLeaf = struct('center', {{char(LEX(COUNTER)), char(NEXT)}}, ...\n 'pdeflag', 0);\n push(newLeaf);\n advance();\n \nelseif ( strcmp(NEXT, 'PDEVAR') )\n newLeaf = struct('center', {{char(LEX(COUNTER)), char(NEXT)}}, ...\n 'pdeflag', 1);\n push(newLeaf);\n advance();\n \nelseif ( strcmp(NEXT, 'FUNC1') ) % Functions which take one argument\n parseFunction1();\n \nelseif ( strcmp(NEXT, 'FUNC2') ) % Functions which take two arguments\n parseFunction2();\n \nelseif ( strcmp(NEXT, 'FUNC3') ) % Functions which take three arguments\n parseFunction3();\n\nelseif ( strcmp(NEXT, 'LPAR') )\n advance();\n parseExp05();\n\n % Check if NEXT symbol is ')' as it should be. If not, there is a\n % parenthesis imbalance in the expression and we return an error.\n m = match('RPAR'); \n if ( ~m )\n reportError('Parse:parenths', 'Parenthesis imbalance in input fields.')\n end\n \nelseif ( strcmp(NEXT, 'UN-') || strcmp(NEXT, 'UN+') || ...\n strcmp(NEXT, 'OP-') || strcmp(NEXT,'OP+') )\n % If + or - reaches this far, we have an unary operator.\n % ['UN', char(NEXT(3))] determines whether we have UN+ or UN-.\n newCenterNode = {{char(LEX(COUNTER)), ['UN', char(NEXT(3))]}};\n advance();\n parseExp4();\n \n rightArg = pop();\n \n pdeflag = rightArg.pdeflag;\n\n newTree = struct('center', newCenterNode, 'right', rightArg, ...\n 'pdeflag',pdeflag);\n push(newTree);\nelse\n \n reportError('Parse:terminal', ...\n ['Unrecognized character in input field:', NEXT]);\nend\n\nend\n\nfunction parseFunction1()\n\nglobal COUNTER\nglobal LEX\n\nfunctionName = char(LEX(COUNTER));\nadvance();\n\nif ( match('LPAR') )\n parseExp1();\n \n if ( match('COMMA') )\n reportError('Parse:func1', ...\n ['Method ''', functionName, ''' only takes one input argument.']);\n elseif ( ~match('RPAR') )\n reportError('Parse:parenths', 'Parenthesis imbalance in input fields.')\n end\n \n rightArg = pop();\n if ( rightArg.pdeflag )\n error('CHEBFUN:STRINGPARSER:parser:PDE', ...\n 'Cannot use time derivative as function arguments.')\n end\n % Can assume no pde if we reach here\n newTree = struct('center', {{functionName, 'FUNC1'}}, ...\n 'right', rightArg, 'pdeflag', 0);\n push(newTree);\nelse\n reportError('Parse:parenths', ...\n 'Need parenthesis when using functions in input fields.')\nend\n\nend\n\nfunction parseFunction2()\n\nglobal NEXT\nglobal COUNTER\nglobal LEX\n\n% Function which allow one or two arguments\noneArgAllowed = {'diff', 'cumsum', 'airy', 'mean'};\nfunctionName = char(LEX(COUNTER));\nadvance();\n\n% Here we need ( as the next symbol\nif ( strcmp(NEXT, 'LPAR') )\n advance();\n parseExp1();\n \n firstArg = pop();\n if ( firstArg.pdeflag )\n error('CHEBFUN:STRINGPARSER:parser:PDE', ...\n 'Cannot use time derivative as function arguments.')\n end\n \n % Check whether we have a comma, if so, continue as normal\n if ( match('COMMA') )\n parseExp1();\n m = match('RPAR');\n if ( ~m )\n reportError('Parse:parenths', ...\n 'Parenthesis imbalance in input fields.')\n end\n \n secondArg = pop();\n if ( secondArg.pdeflag )\n error('CHEBFUN:STRINGPARSER:parser:PDE', ...\n 'Cannot use time derivative as function arguments.')\n end\n\n % Can assume no pde if we reach here\n newTree = struct('left', firstArg, ...\n 'center', {{functionName, 'FUNC2'}}, ...\n 'right', secondArg,'pdeflag',0);\n push(newTree);\n \n elseif ( match('RPAR') )\n if ( any(strcmp(functionName, oneArgAllowed)) )\n % Have hit a function which allows one or two args.\n\n % If we only had one argument, we convert the function to type\n % FUNC1. Can assume no PDE if we reach here\n newTree = struct('center', {{functionName, 'FUNC1'}}, ...\n 'right', firstArg, 'pdeflag', 0);\n push(newTree);\n else\n % We tried to call a method which requires two args with only one.\n reportError('Parse:func2', ['Method ''', functionName, ...\n ''' requires two input arguments.']);\n end\n \n else\n reportError('Parse:parenths', 'Parenthesis imbalance in input fields.')\n end\n \nelse\n reportError('Parse:parenths', ...\n 'Need parenthesis when using functions in input fields.')\nend\n\nend\n\nfunction parseFunction3()\n\nglobal NEXT\nglobal COUNTER\nglobal LEX\n\n% Function which allow one or two arguments\noneArgAllowed = {'sum', 'integral'};\ntwoArgAllowed = {'feval', 'fred', 'volt'};\nfunctionName = char(LEX(COUNTER));\nadvance();\n\n% Here we need ( as the next symbol\nif ( strcmp(NEXT, 'LPAR') )\n advance();\n parseExp1();\n firstArg = pop();\n if ( firstArg.pdeflag )\n error('CHEBFUN:STRINGPARSER:parser:PDE', ...\n 'Cannot use time derivative as function arguments.')\n end\n \n % Check whether we have a comma, if so, continue as normal\n if ( match('COMMA') )\n parseExp1();\n secondArg = pop();\n if ( secondArg.pdeflag )\n error('CHEBFUN:STRINGPARSER:parser:PDE', ...\n 'Cannot use time derivative as function arguments.')\n end\n\n if ( match('COMMA') ) % and again\n parseExp1();\n thirdArg = pop();\n\n % Define the new branch\n newTree = struct('left', firstArg, ...\n 'center', {{functionName, 'FUNC3'}}, ...\n 'right', secondArg, 'arg', thirdArg, 'pdeflag', 0);\n\n if ( ~match('RPAR') ) % Check the final parenthesis\n reportError('Parse:parenths', ...\n 'Parenthesis imbalance in input fields.')\n end\n elseif ( match('RPAR') && any(strcmp(functionName, twoArgAllowed)) )\n % This was actually a two argument function in disguise\n newTree = struct('left', firstArg, ...\n 'center', {{functionName, 'FUNC2'}},...\n 'right', secondArg, 'pdeflag', 0);\n else\n reportError('Parse:parenths', ...\n 'Parenthesis imbalance in input fields.')\n end\n push(newTree);\n \n elseif ( match('RPAR') )\n if ( any(strcmp(functionName,oneArgAllowed)) )\n % Have hit a function which allows one or two args.\n\n % If we only had one argument, convert the function to type FUNC1.\n % Can assume no PDE if we reach here.\n newTree = struct('center', {{functionName, 'FUNC1'}}, ...\n 'right', firstArg, 'pdeflag', 0);\n push(newTree);\n else\n % We tried to call a method which requires two args with only one.\n reportError('Parse:func2', ['Method ''', functionName, ...\n ''' requires two input arguments.']);\n end\n \n else\n reportError('Parse:parenths', 'Parenthesis imbalance in input fields.')\n end\n \nelse\n reportError('Parse:parenths', 'Need parenthesis when using functions in input fields.')\nend\n\nend\n\nfunction parseExp1pr()\n\nglobal NEXT\n\nif ( strcmp(NEXT, 'OP+') )\n\n advance();\n leftArg = pop();\n parseExp2();\n rightArg = pop();\n \n pdeflag = leftArg.pdeflag || rightArg.pdeflag;\n \n newTree = struct('left', leftArg, 'center', {{'+', 'OP+'}}, ...\n 'right', rightArg, 'pdeflag', pdeflag);\n push(newTree);\n parseExp1pr();\n \nelseif ( strcmp(NEXT, 'OP-') )\n advance();\n leftArg = pop();\n parseExp2();\n rightArg = pop();\n\n pdeflag = leftArg.pdeflag || rightArg.pdeflag;\n newTree = struct('left', leftArg, 'center', {{'-', 'OP-'}}, ...\n 'right', rightArg, 'pdeflag', pdeflag);\n push(newTree);\n parseExp1pr();\nelseif ( strcmp(NEXT, 'RPAR') || strcmp(NEXT, '$') || strcmp(NEXT, 'OP=') )\n\t% Do nothing\nelse % If we don't have ) or the end symbol now something has gone wrong.\n% reportError('Parse:end','Syntax error in input fields.')\nend\n\nend\n\n\nfunction parseExp2pr()\n\nglobal NEXT\n\nif ( strcmp(NEXT,'OP*') )\n leftArg = pop(); % Pop from the stack the left argument\n advance(); % Advance in the input\n parseExp3();\n rightArg = pop(); % Pop from the stack the right argument\n\n % Check whether we have _ variables\n if ( leftArg.pdeflag || rightArg.pdeflag )\n error('CHEBFUN:STRINGPARSER:parser:PDE','Cannot multiply time derivative')\n end\n\n % Can assume no PDE if we reach here\n newTree = struct('left', leftArg, 'center', {{'.*', 'OP*'}}, ...\n 'right', rightArg, 'pdeflag', 0);\n push(newTree);\n parseExp2pr();\n \nelseif ( strcmp(NEXT,'OP/') )\n leftArg = pop(); % Pop from the stack the left argument\n advance(); % Advance in the input\n parseExp3();\n rightArg = pop(); % Pop from the stack the right argument\n\n % Check whether we have _ variables\n if ( leftArg.pdeflag || rightArg.pdeflag )\n error('CHEBFUN:STRINGPARSER:parser:PDE','Cannot divide with time derivatives')\n end\n\n % Can assume no PDE if we reach here\n newTree = struct('left', leftArg, 'center', {{'./', 'OP/'}}, ...\n 'right', rightArg, 'pdeflag', 0);\n push(newTree);\n parseExp2pr();\nelse\n % Do nothing\nend\n\nend\n\nfunction parseExp3pr()\n\nglobal NEXT\n\nif ( strcmp(NEXT,'OP^') )\n leftArg = pop();\n advance(); \n parseExp4();\n rightArg = pop();\n\n % Check whether we have _ variables\n if ( leftArg.pdeflag || rightArg.pdeflag )\n error('CHEBFUN:STRINGPARSER:parser:PDE','Cannot take powers with time derivative')\n end\n\n % Can assume no pde if we reach here\n newTree = struct('left', leftArg, 'center', {{'.^', 'OP^'}}, ...\n 'right', rightArg, 'pdeflag', 0);\n push(newTree);\n parseExp3pr();\n \nelseif ( ~isempty(strfind(NEXT, 'DER')) )\n leftArg = pop();\n\n % Check whether we have _ variables\n if ( leftArg.pdeflag )\n error('CHEBFUN:STRINGPARSER:parser:PDE','Cannot differentiate time derivative')\n end\n\n newTree = struct('center', {{'D', NEXT}}, 'right', leftArg, 'pdeflag', 0);\n push(newTree);\n advance();\n parseExp3pr();\nelse\n % Do nothing\nend\n\nend\n\nfunction parseExpDer()\n% parseExpDer deals with ' denoting derivatives on the dependent variables\n% in the problem.\n\nglobal NEXT\n\nif ( ~isempty(strfind(NEXT, 'DER')) )\n leftArg = pop();\n\n % Check whether we have _ variables\n if ( leftArg.pdeflag )\n error('CHEBFUN:STRINGPARSER:parser:PDE','Cannot differentiate time derivative')\n end\n\n newTree = struct('center', {{'D', NEXT}}, 'right', leftArg, 'pdeflag', 0);\n push(newTree);\n advance();\nelse\n % Do nothing\nend\n\nend\n\nfunction parseExpList()\n% parseExpList deals with potential arguments to the dependent variables in\n% the problem, e.g. u(3,left).\n\nglobal NEXT\nglobal COUNTER\nglobal LEX\n\nif ( match('LPAR') ) % We are in a u(3) or u(3,left) situation\n % The first argument expression can only be of type EXP05 or higher\n % (no = or comma-dividers are allowed)\n parseExp1();\n % Check whether we are in in u(3) or u(3,left) situation. If we\n % have a match with ), we must have a feval with two arguments. If\n % we have a match with a comma, we must have a feval with three\n % arguments, but if there is no match, we have parenthesis\n % imbalance.\n if ( match('RPAR') )\n % Here we only had one argument in u(...), so we create a feval of type\n % FUNC2 (since the feval method has two input arguments)\n secondArg = pop();\n firstArg = pop();\n\n % Can assume no PDE if we reach here\n newTree = struct('left', firstArg, 'center', {{'feval', 'FUNC2'}}, ...\n 'right', secondArg,'pdeflag', 0);\n push(newTree);\n \n elseif ( match('COMMA') )\n % Here we only had two arguments in u(...), so we create a\n % feval of type FUNC3 (since the feval method has three input\n % arguments)\n \n % Check whether we have any of the allowed option type as the\n % second argument. If not, throw an error.\n if ( strcmp(NEXT,'STR') )\n % We got a match! But we also need to check for parenthesis\n % balance. Store the option as a temporary leaf\n optLeaf = struct('center', {{char(LEX(COUNTER)), char(NEXT)}}, ...\n 'pdeflag', 0);\n % Advance and check for parenth. balance\n advance();\n if ( match('RPAR') )\n % Create a feval of type FUNC3 (since the feval method\n % has three input arguments)\n secondArg = pop();\n firstArg = pop();\n thirdArg = optLeaf;\n\n % Can assume no pde if we reach here\n newTree = struct('left', firstArg, ...\n 'center', {{'feval', 'FUNC3'}}, 'right', secondArg, ...\n 'arg',thirdArg, 'pdeflag', 0);\n push(newTree);\n else\n reportError('Parse:parenths', ...\n 'Parenthesis imbalance in input fields.')\n end\n else\n reportError('Parse:secondArg', ...\n 'Invalid second argument to u(0,...) type of expression.')\n end\n \n else % There must be a parenthesis imbalance.\n reportError('Parse:parenths', 'Parenthesis imbalance in input fields.')\n end\nelse % We reach here for the default behaviour, e.g. u' = 1, no parentheses involved\n % Do nothing, since we've already pushed the variable onto the\n % stack.\nend\n\nend\n\nfunction parseExp0pr()\n\nglobal NEXT\n\nif ( strcmp(NEXT, 'OP=') )\n \n leftArg = pop();\n advance();\n parseExp05();\n\n rightArg = pop();\n\n pdeflag = leftArg.pdeflag || rightArg.pdeflag;\n\n newTree = struct('left', leftArg, 'center', {{'=', 'OP='}}, ...\n 'right', rightArg, 'pdeflag', pdeflag);\n push(newTree); \nelse\n\t% Do nothing\nend\n\nend\n\nfunction parseExpApr()\n\nglobal NEXT\n\nif ( strcmp(NEXT, 'COMMA') )\n \n advance();\n leftArg = pop();\n parseExpA();\n rightArg = pop();\n \n pdeflag = leftArg.pdeflag || rightArg.pdeflag;\n \n newTree = struct('left', leftArg, 'center', {{',', 'COMMA'}}, ...\n 'right', rightArg, 'pdeflag', pdeflag);\n push(newTree);\nelse\n\t% Do nothing\nend\n\nend\n\nfunction parseExp05pr()\n\nglobal NEXT\n\nif ( any(strcmp(NEXT, {'OP>', 'OP>=', 'OP<', 'OP<='})) )\n tempOpType = NEXT;\n tempOpLabel = tempOpType(3:end);\n \n advance();\n leftArg = pop();\n parseExp1();\n rightArg = pop();\n \n pdeflag = leftArg.pdeflag || rightArg.pdeflag;\n \n newTree = struct('left', leftArg, 'center', {{tempOpLabel, tempOpType}}, ...\n 'right', rightArg, 'pdeflag', pdeflag);\n push(newTree);\nelse\n\t% Do nothing\nend\n\nend\n\nfunction advance()\n%ADVANCE Move to the next token in the output from the lexer.\nglobal NEXT\nglobal COUNTER\nglobal LEX\n\nCOUNTER = COUNTER + 1;\nNEXT = char(LEX(COUNTER,2));\n\nend\n\n\n\nfunction m = match(label)\n\nglobal NEXT\nm = strcmp(label, NEXT);\n\n% If we found a match and are not at the end of output, we want to advance\n% to the NEXT symbol\nif ( m && ~strcmp(label, '$') )\n advance();\nend\n\nend\n\n\nfunction push(new)\n%PUSH Push a tree to the stack of syntax trees\nglobal STACK\n\nif ( ~stackRows() )\n STACK = new;\nelse\n % Ensure number of fields matches\n [STACK, new] = mergeFields(STACK, new);\n % Update the Stack\n STACK = [STACK ; new];\nend\n\nend\n\n\nfunction p = pop()\n%POP Pop a tree from the stack.\nglobal STACK\n\n% Throw a sensible error if we have an empty stack\nif ( isempty(STACK) )\n reportError('Parse:end', 'Syntax error in input expression (Empty stack)');\nend\n\np = STACK(end,:);\nSTACK(end,:) = [];\n\nend\n\nfunction m = stackRows()\n\nglobal STACK\n[m, n] = size(STACK); %#ok\n\nend\n\n% TODO: Can we get rid of this function entirely?\nfunction reportError(id, msg)\n\nerror(['CHEBFUN:', id], msg);\n% ME = MException(id,msg);\n% throw(ME);\n\nend\n\n\nfunction [a, b] = mergeFields(a, b)\n\naFields = fieldnames(a); \nbFields = fieldnames(b);\n\nfor k = 1:numel(aFields)\n if ( ~isfield(b, aFields{k}) )\n b.(aFields{k}) = [];\n end\nend\n\nfor k = 1:numel(bFields)\n if ( ~isfield(a, bFields{k}) )\n a.(bFields{k}) = [];\n end\nend\n\nend\n", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/@stringParser/parser.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.34839763850849137}} {"text": "function tdetx = tdet(x,K)\n% tdetx = tdet(x,K)\n%\n% TDET Computes twice determinant for Lorentz block\n%\n% ********** INTERNAL FUNCTION OF SEDUMI **********\n%\n% See also sedumi\n\n% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko\n% Copyright (C) 2005 McMaster University, Hamilton, CANADA (since 1.1)\n%\n% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)\n% Dept. Econometrics & O.R., Tilburg University, the Netherlands.\n% Supported by the Netherlands Organization for Scientific Research (NWO).\n%\n% Affiliation SeDuMi 1.03 and 1.04Beta (2000):\n% Dept. Quantitative Economics, Maastricht University, the Netherlands.\n%\n% Affiliations up to SeDuMi 1.02 (AUG1998):\n% CRL, McMaster University, Canada.\n% Supported by the Netherlands Organization for Scientific Research (NWO).\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA\n% 02110-1301, USA\n\nif isempty(K.q)\n tdetx = zeros(0,1);\nelse\n ix = K.mainblks;\n tdetx = x(ix(1):ix(2)-1).^2 - ddot(x(ix(2):ix(3)-1),x,K.qblkstart);\nend", "meta": {"author": "zarathustr", "repo": "LibQPEP", "sha": "99e5c23e746ace0bac4a86742c31db6fcf7297ba", "save_path": "github-repos/MATLAB/zarathustr-LibQPEP", "path": "github-repos/MATLAB/zarathustr-LibQPEP/LibQPEP-99e5c23e746ace0bac4a86742c31db6fcf7297ba/MATLAB/sedumi/tdet.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6859494550081925, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.3483332715490145}} {"text": "\naddpath Codes1D\naddpath Codes2D\naddpath Codes3D\naddpath ServiceRoutines\naddpath CFD1D\naddpath CFD2D\naddpath Grid/\naddpath Grid/CFD\naddpath Grid/3D\naddpath Grid/CNS2D\naddpath Grid/Euler2D\naddpath Grid/Maxwell2D\naddpath Grid/Other\n\ncpt = cputime;\n\nEulerDriver1D \nfigure; plot(x,Ener); drawnow; pause(.1); \n\nPoissonCDriver1D\nfigure; plot(x,u); drawnow; pause(.1); \n\nAdvecDriver1D \nfigure; plot(x,u); drawnow; pause(.1); \n\nBurgersDriver1D \nfigure; plot(x,u); drawnow; pause(.1); \n\nHeatDriver1D \nfigure; plot(x,u); drawnow; pause(.1); \n\nMaxwellDriver1D \nfigure; plot(x,E); drawnow; pause(.1); \n\n\nCurvedCNSDriver2D \nfigure; PlotField2D(N, x, y, Q(:,:,4)); drawnow; pause(.1); \n\nCurvedPoissonIPDGDriver2D\nfigure; PlotField2D(N, x, y, u); drawnow; pause(.1); \n\nCurvedEulerDriver2D \nfigure; PlotField2D(N, x, y, Q(:,:,4)); drawnow; pause(.1); \n\nMaxwellCurvedDriver2D\nfigure; PlotField2D(N, x, y, Ez); drawnow; pause(.1); \n\nCurvedINSDriver2D \nfigure; PlotField2D(N, x, y, PR); drawnow; pause(.1); \n\nMaxwellDriver2D\nfigure; PlotField2D(N, x, y, Ez); drawnow; pause(.1); \n\nEulerDriver2D \nfigure; PlotField2D(N, x, y, Q(:,:,4)); drawnow; pause(.1); \n\nMaxwellHNonConDriver2D\nfigure; PlotField2D(N, x, y, Ez); drawnow; pause(.1); \n\nEulerShockDriver2D \nfigure; PlotField2D(N, x, y, Q(:,:,4)); drawnow; pause(.1); \n\nPoissonDriver2D\nfigure; PlotField2D(N, x, y, u); drawnow; pause(.1); \n\nMaxwellPNonConDriver2D\n\nAdvecDriver3D\nfigure; PlotContour3D(N, u, linspace(0, 1, 5)); drawnow; pause(.1); \n\nMaxwellDriver3D\nfigure; PlotContour3D(3*N, Ez, linspace(-1, 1, 10)); drawnow; pause(.1); \n\nPoissonIPDGDriver3D\nfigure; PlotContour3D(3*N, u, linspace(.1, 1, 10)); drawnow; pause(.1); \nhold on\nPlotSlice3D(2*N, u, 'x', .4);\nhold off\n\nalldemostook = cputime-cpt\n\n\n", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/JSHesthaven&TWarburton/TestAll.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.3478638190587141}} {"text": "function [ mSynCat, vMain] = calc_SynCat(nNbkg,vSynCat,nSynCat_,nSynMode, vAfter,vEtas,mCatalog,bPSQ,vPSQ,mPSQ)\n % calculates a synthetic catalog with a backgroundrate based number of earthquakes in the catalog of the period before starting date.\n %\n % Example: [mSynCat, vMain] = calc_SynCat(2500,2.5,2.5,8,100,'January 1,1980','December 31,1990',6.5,1,0,a);\n %\n % This function (calc_SynCat) calculates a synthetic catalog with a\n % backgroundrate based number of earthquakes in the catalog of the period\n % before starting date. This function is doing the following:\n % 1) creates a synthetic catalog with background rate based on input parameters.\n % 2) calculate omori-type aftershock and add this to the background catalog,\n % that was created by the properties of the inputbackground catalog. Therefore\n % the program package ETESProject by karen Felzer was used.\n %\n % Author: van Stiphout, Thomas\n % Email: vanstiphout@sed.ethz.ch\n % Created: 2. Mar 2007\n % Changed: -\n %\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % Variables\n % Input:\n % nNbkg Number of events in background catalog during assigned period\n % vSynCat Vektor with contraints on synthetic catalog\n % 1-4: fMinLon fMaxLon fMinLat fMaxLat in degree\n % 5-6: fMinDepth fMaxDepth in km\n % 7-8: fMinTime fMaxTime (duration of catalog)\n % 9: fRate Reduction of earthquakes for entire catalog\n % (0.75 = 25% reduction) in period (fT-fTw) - fT\n % 10: fBValue b-value of the catalog\n % 11: fMc Magnitude of Completness (minimum Magnitude in Catalog)\n % 12: fIncMagnitude increment steps\n % nSynCat_ 1: only backgorund, 2: background + ETAS\n % nSynMode Type of synthetic catalog 0:homogeneous distr; 1:based\n % on real catalog 2:hypocenter based on real catalog, magnitude and focal\n % time is randomly computed\n % vAfter Definition/Constraints for Aftershocks\n % 1: Mmin: Minimum earthquake magnitude to report and simulate\n % 2: MminR: Minimum earthquake magnitude for reporting\n % in the output catalog\n % 3: maxm: Maximum earthquake magnitude\n % 4: DMax: Maximum distance for aftershocks\n % 5: magb: Cutoff magnitude for the point source vs. plane source\n % representation of the mainshock\n % vEtas Parameters for ETAS:[CX, P, A] standard=[0.095, 1.34, 0.008]\n % mCatalog Declustered catalog needed only for nSynMode=1\n % bPSQ with (1) or without (0) PSQ\n % vPSQ values for PSQ (lon, lat, N, Tw, T)\n %\n % Output:\n % SynCat Simulated ETES catalog [yr lon lat month day mag depth hrs min sec]\n % vMain Vector with assignments if main (true) or aftershock (false)\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n \n % initialize:\n clear FaultParam;\n \n % background:\n fBValue=vSynCat(10);\n fMc=vSynCat(11);\n fInc=vSynCat(12);\n fMinLat=vSynCat(3);\n fMaxLat=vSynCat(4);\n fMinLon=vSynCat(1);\n fMaxLon=vSynCat(2);\n fMinDepth=vSynCat(5);\n fMaxDepth=vSynCat(6);\n nRchange=vSynCat(9);\n [fYr1, nMn1, nDay1, nHr1, nMin1, nSec1]=decyear2mat(vSynCat(7));\n [fYr2, nMM2, nDD2, nHH2, nMN2, nSS2]=decyear2mat(vSynCat(8));\n \n \n % vAfter\n Mmin=vAfter(1);\n MminR=vAfter(2);\n maxm=vAfter(3);\n DMax=vAfter(4);\n magb=vAfter(5);\n FaultParam=[0 0 0 0 0 0 0];\n \n % vEtas\n CX=vEtas(1);\n P=vEtas(2);\n A=vEtas(3);\n \n switch nSynCat_\n case 1\n % create background rate\n mSynCat=syn_catalog(nNbkg, fBValue, fMc, fInc, fMinLat,fMaxLat,...\n fMinLon,fMaxLon,fMinDepth,fMaxDepth, fYr1,fYr2,nSynMode,...\n mCatalog);\n if bPSQ\n mSynCat=sr_makePSQ(mSynCat,vPSQ(2),vPSQ(3),vPSQ(4),...\n vPSQ(1),mPSQ);\n end\n % mSynCat(:,1)=mSynCat(randperm(size(mSynCat,1))',1);\n vMain=ones(nNbkg,1);\n case 2 % create background rate + ETAS\n nNbkgA=floor(nNbkg/(1+nRchange)*1);\n nNbkgB=ceil(nNbkg/(1+nRchange)*nRchange);\n if nRchange == 1\n mCat=syn_catalog(nNbkg, fBValue, fMc, fInc, fMinLat,fMaxLat,...\n fMinLon,fMaxLon,fMinDepth,fMaxDepth, fYr1,fYr2,nSynMode,...\n mCatalog);\n else\n mCatA=syn_catalog(nNbkgA, fBValue, fMc, fInc, fMinLat,fMaxLat,...\n fMinLon,fMaxLon,fMinDepth,fMaxDepth,fYr1,(fYr1+fYr2)/2,...\n nSynMode,mCatalog);\n mCatB=syn_catalog(nNbkgB, fBValue, fMc, fInc, fMinLat,fMaxLat,...\n fMinLon,fMaxLon,fMinDepth,fMaxDepth,(fYr1+fYr2)/2,fYr2,...\n nSynMode,mCatalog);\n mCat=[mCatA;mCatB];\n end\n % mCat(:,1)=mCat(randperm(size(mCat,1))',1);\n [Y,Idx]=sort(mCat(:,3),1);\n mCat=mCat(Idx,:);\n if bPSQ\n mCat=sr_makePSQ(mCat,vPSQ(2),vPSQ(3),vPSQ(4),...\n vPSQ(1),mPSQ);\n end\n mCat1=[fix(mCat(:,3)) mCat(:,4) mCat(:,5) mCat(:,8) mCat(:,9) rand(size(mCat,1),1)*60 mCat(:,2) mCat(:,1) mCat(:,7) mCat(:,6)];\n % mCat1(:,1)=mCat1(:,1)-(max(mCat1(:,1))-min(mCat1(:,1)));\n % [N,Mmax,catalog,IDAll,HistoryAll] = ETESProject2(cat1,RateGrid2,0.095,1.34,0.008,Mmin,MminR,maxm,DMax,sYr1,sYr2,6.5,FaultParam)\n [N,Mmax,catalog,IDAll,HistoryAll] = ETESProject3(mCat1,vEtas,vAfter,fYr1,fYr2,FaultParam);\n \n mSynCat(:,1) = catalog(:,8); % lon\n mSynCat(:,2) = catalog(:,7); % lat\n mSynCat(:,3) = catalog(:,1); % years\n mSynCat(:,4) = catalog(:,2); % month\n mSynCat(:,5) = catalog(:,3); % day\n mSynCat(:,6) = catalog(:,10); % mag\n mSynCat(:,7) = catalog(:,9); % depth\n mSynCat(:,8) = catalog(:,4); % hours\n mSynCat(:,9) = catalog(:,5); % minutes\n mSynCat(:,10) = catalog(:,6); % seconds\n \n mSynCat(:,3) = decyear([mSynCat(:,3) mSynCat(:,4) mSynCat(:,5) ...\n mSynCat(:,8) mSynCat(:,9) mSynCat(:,10)]); % yrs decimal\n size(mSynCat)\n vMain=(catalog(:,12)==0);\n end\n % disp('cat fertig')\nend\n", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/src/thomas/synthetic/calc_SynCat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.34755121315699955}} {"text": "% This subroutine assigns creates a grid with\n% spacing dx,dy (in degreees). The size will\n% be selected interactiVELY. The bvalue in each\n% volume around a grid point containing ni earthquakes\n% will be calculated as well as the magnitude\n% of completness\n% Stefan Wiemer 1/95\n\n\ndisplay ('This is /src/bdepth_ratio_auto.m');\n\n\nglobal no1 bo1 inb1 inb2\n\nif sel == 'in'\n % get the grid parameter\n % initial values\n %\n dx = 0.1;\n dy = 0.1 ;\n ni = 1000;\n Nmin = 50;\n stan2 = nan;\n stan = nan;\n prf = nan;\n av = nan;\n mid_point = 5;\n top_zonet = 0;\n top_zoneb = 5;\n bot_zonet = 7;\n bot_zoneb = 15;\n topstan2 = nan;\n botstan2 = nan;\n topstan = nan;\n botstan = nan;\n topav = nan;\n botav = nan;\n\n\n % make the interface\n %\n figure_w_normalized_uicontrolunits(...\n 'Name','Depth Ratio Grid Input Parameter',...\n 'NumberTitle','off', ...\n 'MenuBar','none', ...\n 'NextPlot','new', ...\n 'units','points',...\n 'Visible','off', ...\n 'Position',[ wex+200 wey-200 650 300]);\n axis off\n labelList2=[' Automatic Mcomp (max curvature) | Fixed Mc (Mc = Mmin) | Automatic Mcomp (90% probability) | Automatic Mcomp (95% probability) | Best (?) combination (Mc95 - Mc90 - max curvature)'];\n\n labelPos = [0.2 0.60 0.6 0.08];\n hndl2=uicontrol(...\n 'Style','popup',...\n 'Position',labelPos,...\n 'Units','normalized',...\n 'String',labelList2,...\n 'Callback','inb2 =get(hndl2,''Value''); ');\n\n % set(hndl2,'value',5);\n\n\n % creates a dialog box to input grid parameters\n %\n %\n\n % mid_point_field=uicontrol('Style','edit',...\n % 'Position',[.47 .80 .12 .08],...\n % 'Units','normalized','String',num2str(mid_point),...\n % 'Callback','mid_point=str2double(get(mid_point_field,''String'')); set(mid_point_field,''String'',num2str(mid_point));');\n\n top_zonet_field=uicontrol('Style','edit',...\n 'Position',[.36 .80 .06 .06],...\n 'Units','normalized','String',num2str(top_zonet),...\n 'Callback','top_zonet=str2double(get(top_zonet_field,''String'')); set(top_zonet_field,''String'',num2str(top_zonet));');\n top_zoneb_field=uicontrol('Style','edit',...\n 'Position',[.36 .74 .06 .06],...\n 'Units','normalized','String',num2str(top_zoneb),...\n 'Callback','top_zoneb=str2double(get(top_zoneb_field,''String'')); set(top_zoneb_field,''String'',num2str(top_zoneb));');\n\n bot_zonet_field=uicontrol('Style','edit',...\n 'Position',[.78 .80 .06 .06],...\n 'Units','normalized','String',num2str(bot_zonet),...\n 'Callback','bot_zonet=str2double(get(bot_zonet_field,''String'')); set(bot_zonet_field,''String'',num2str(bot_zonet));');\n bot_zoneb_field=uicontrol('Style','edit',...\n 'Position',[.78 .74 .06 .06],...\n 'Units','normalized','String',num2str(bot_zoneb),...\n 'Callback','bot_zoneb=str2double(get(bot_zoneb_field,''String'')); set(bot_zoneb_field,''String'',num2str(bot_zoneb));');\n\n freq_field=uicontrol('Style','edit',...\n 'Position',[.30 .50 .12 .08],...\n 'Units','normalized','String',num2str(ni),...\n 'Callback','ni=str2double(get(freq_field,''String'')); set(freq_field,''String'',num2str(ni));set(tgl2,''value'',0); set(tgl1,''value'',1)');\n\n\n freq_field0=uicontrol('Style','edit',...\n 'Position',[.70 .50 .12 .08],...\n 'Units','normalized','String',num2str(ra),...\n 'Callback','ra=str2double(get(freq_field0,''String'')); set(freq_field0,''String'',num2str(ra)) ; set(tgl2,''value'',1); set(tgl1,''value'',0)');\n\n freq_field2=uicontrol('Style','edit',...\n 'Position',[.30 .40 .12 .08],...\n 'Units','normalized','String',num2str(dx),...\n 'Callback','dx=str2double(get(freq_field2,''String'')); set(freq_field2,''String'',num2str(dx));');\n\n freq_field3=uicontrol('Style','edit',...\n 'Position',[.30 .30 .12 .08],...\n 'Units','normalized','String',num2str(dy),...\n 'Callback','dy=str2double(get(freq_field3,''String'')); set(freq_field3,''String'',num2str(dy));');\n\n tgl1 = uicontrol('Style','checkbox',...\n 'string','Number of Events:',...\n 'Position',[.09 .50 .2 .08], 'Callback','set(tgl2,''value'',0)',...\n 'Units','normalized');\n\n set(tgl1,'value',1);\n\n tgl2 = uicontrol('Style','checkbox',...\n 'string','OR: Constant Radius',...\n 'Position',[.47 .50 .2 .08], 'Callback','set(tgl1,''value'',0)',...\n 'Units','normalized');\n\n\n freq_field4=uicontrol('Style','edit',...\n 'Position',[.30 .20 .12 .08],...\n 'Units','normalized','String',num2str(Nmin),...\n 'Callback','Nmin=str2double(get(freq_field4,''String'')); % set(freq_field4,''String'',num2str(Nmin));');\n\n\n close_button=uicontrol('Style','Pushbutton',...\n 'Position',[.60 .05 .15 .12 ],...\n 'Units','normalized','Callback','close;done','String','Cancel');\n\n go_button1=uicontrol('Style','Pushbutton',...\n 'Position',[.20 .05 .15 .12 ],...\n 'Units','normalized',...\n 'Callback',' inb1 =get(hndl2,''Value'');tgl1 =get(tgl1,''Value'');tgl2 =get(tgl2,''Value'');close,sel =''ca'', bdepth_ratio',...\n 'String','Go');\n Nmin;\n text(...\n 'Color',[0 0 0 ],...\n 'EraseMode','normal',...\n 'Position',[0.20 .75 0 ],...\n 'Rotation',0 ,...\n 'FontSize',ZmapGlobal.Data.fontsz.m ,...\n 'FontWeight','bold',...\n 'String','Please choose an Mc estimation option ');\n\n mid_txt=text(...\n 'Color',[0 0 0 ],...\n 'EraseMode','normal',...\n 'Position',[0.24 1.0 0 ],...\n 'Rotation',0 ,...\n 'FontSize',ZmapGlobal.Data.fontsz.m ,...\n 'FontWeight','bold',...\n 'String','Depth limits for depth ratio calculation ');\n\n top_txt=text(...\n 'Color',[0 0 0 ],...\n 'EraseMode','normal',...\n 'Position',[-0.10 .85 0 ],...\n 'Rotation',0 ,...\n 'FontSize',ZmapGlobal.Data.fontsz.m ,...\n 'FontWeight','bold',...\n 'String','Top and bottom for TOP zone(km):');\n\n bot_txt=text(...\n 'Color',[0 0 0 ],...\n 'EraseMode','normal',...\n 'Position',[0.40 .85 0 ],...\n 'Rotation',0 ,...\n 'FontSize',ZmapGlobal.Data.fontsz.m ,...\n 'FontWeight','bold',...\n 'String','Top and bottom for BOTTOM zone(km):');\n\n txt3 = text(...\n 'Color',[0 0 0 ],...\n 'EraseMode','normal',...\n 'Position',[0.30 0.64 0 ],...\n 'Rotation',0 ,...\n 'FontSize',ZmapGlobal.Data.fontsz.m ,...\n 'FontWeight','bold',...\n 'String',' Grid Parameter');\n txt5 = text(...\n 'Color',[0 0 0 ],...\n 'EraseMode','normal',...\n 'Position',[-0.06 0.40 0 ],...\n 'Rotation',0 ,...\n 'FontSize',ZmapGlobal.Data.fontsz.m ,...\n 'FontWeight','bold',...\n 'String','Spacing in x (dx) in deg:');\n\n txt6 = text(...\n 'Color',[0 0 0 ],...\n 'EraseMode','normal',...\n 'Position',[-0.06 0.29 0 ],...\n 'Rotation',0 ,...\n 'FontSize',ZmapGlobal.Data.fontsz.m ,...\n 'FontWeight','bold',...\n 'String','Spacing in y (dy) in deg:');\n\n txt7 = text(...\n 'Color',[0 0 0 ],...\n 'EraseMode','normal',...\n 'Position',[-0.06 0.17 0 ],...\n 'Rotation',0 ,...\n 'FontSize',ZmapGlobal.Data.fontsz.m ,...\n 'FontWeight','bold',...\n 'String','Min. No. of events > Mc:');\n\n\n\n set(gcf,'visible','on');\n watchoff\n\nend % if nargin ==0\n\n% get the grid-size interactively and\n% calculate the b-value in the grid by sorting\n% thge seimicity and selectiong the ni neighbors\n% to each grid point\n\nif sel == 'ca'\n selgp\n itotal = length(newgri(:,1));\n if length(gx) < 4 || length(gy) < 4\n errordlg('Selection too small! (Dx and Dy are in degreees! ');\n return\n end\n\n\n zmap_message_center.set_info(' ','Running bdepth_ratio... ');think\n % make grid, calculate start- endtime etc. ...\n %\n t0b = min(a.Date) ;\n n = a.Count;\n teb = a(n,3) ;\n tdiff = round((teb - t0b)*365/par1);\n loc = zeros(3, length(gx)*length(gy));\n\n % loop over all points\n %\n i2 = 0.;\n i1 = 0.;\n bvg = [];\n allcount = 0.;\n nobv = 0;\n wai = waitbar(0,' Please Wait ... ');\n set(wai,'NumberTitle','off','Name','b-value grid - percent done');;\n drawnow\n\n\n % sort by depth\n\n % [s,is] = sort(a.Depth);\n % adepth = a(is(:,1),:);\n\n % find row index of ratio midpoint\n l = a.Depth >= top_zonet & a.Depth < top_zoneb;\n top_zone = a.subset(l);\n\n l = a.Depth >= bot_zonet & a.Depth < bot_zoneb;\n bot_zone = a.subset(l);\n\n\n\n %\n % overall b-value\n [bv magco stan av me mer me2, pr] = bvalca3(top_zone,inb1,inb2);\n tbo1 = bv; tno1 = length(top_zone(:,1));\n\n [bv magco stan av me mer me2, pr] = bvalca3(bot_zone,inb1,inb2);\n bbo1 = bv; bno1 = length(bot_zone(:,1));\n\n depth_ratio = tbo1/bbo1;\n\n disp(depth_ratio);\n\n % loop over all points\n for i= 1:length(newgri(:,1))\n x = newgri(i,1);y = newgri(i,2);\n allcount = allcount + 1.;\n i2 = i2+1;\n\n % calculate distance from center point and sort wrt distance\n l = sqrt(((a.Longitude-x)*cos(pi/180*y)*111).^2 + ((a.Latitude-y)*111).^2) ;\n [s,is] = sort(l);\n b = a(is(:,1),:) ; % re-orders matrix to agree row-wise\n\n if tgl1 == 0 % take point within r\n l3 = l <= ra;\n b = a.subset(l3); % new data per grid point (b) is sorted in distanc (from center point)\n rd = ra;\n else\n % take first ni points\n b = b(1:ni,:); % new data per grid point (b) is sorted in distance\n l2 = sort(l); rd = l2(ni);\n\n end\n\n\n %estimate the completeness and b-value\n newt2 = b;\n\n % sort by depth\n\n l = b(:,7) >= top_zonet & b(:,7) < top_zoneb;\n topb = b(l,:);\n\n l = b(:,7) >= bot_zonet & b(:,7) < bot_zoneb;\n botb = b(l,:);\n\n\n\n\n\n\n if length(topb) >= Nmin && length(botb) >= Nmin\n\n if inb1 == 3\n newt2 = topb;\n mcperc_ca3;\n l = topb(:,6) >= Mc90-0.05; magco = Mc90;\n n1 = length(topb(l,:));\n if length(topb(l,:)) >= Nmin\n [topbv magco stan av me mer me2, pr] = bvalca3(topb(l,:),2,2);\n [topav2 topbv2 topstan2 ] = bmemag(topb(l,:));\n else topbv = nan; topbv2 = nan, magco = nan; av = nan; topav2 = nan;\n nobv = nobv + 1;\n end\n newt2 = botb;\n mcperc_ca3;\n l = botb(:,6) >= Mc90-0.05; magco = Mc90;\n n2 = length(botb(l,:));\n if length(botb(l,:)) >= Nmin\n [botbv magco stan av me mer me2, pr] = bvalca3(botb(l,:),2,2);\n [botav2 botbv2 botstan2 ] = bmemag(botb(l,:));\n\n else botbv = nan; botbv2 = nan; magco = nan; av = nan; botav2 = nan;\n nobv = nobv + 1;\n end\n\n elseif inb1 == 4\n newt2 = topb;\n mcperc_ca3;\n l = topb(:,6) >= Mc95-0.05; magco = Mc95;\n n1 = length(topb(l,:));\n\n if length(topb(l,:)) >= Nmin\n [topbv magco topstan topav topme topmer topme2, toppr] = bvalca3(topb(l,:),2,2);\n [topav2 topbv2 topstan2 ] = bmemag(topb(l,:));\n else\n topbv = nan; topbv2 = nan, magco = nan; topav = nan; topav2 = nan;\n nobv = nobv + 1;\n end\n newt2 = botb;\n mcperc_ca3;\n l = botb(:,6) >= Mc90-0.05; magco = Mc95;\n n2 = length(botb(l,:));\n\n if length(botb(l,:)) >= Nmin\n [botbv magco botstan botav botme botmer botme2, botpr] = bvalca3(botb(l,:),2,2);\n [botav2 botbv2 botstan2 ] = bmemag(botb(l,:));\n else\n botbv = nan; botbv2 = nan, magco = nan; botav = nan; botav2 = nan;\n nobv = nobv + 1;\n end\n\n elseif inb1 == 5\n newt2 = topb;\n mcperc_ca3;\n if isnan(Mc95) == 0 \n magco = Mc95;\n elseif isnan(Mc90) == 0 \n magco = Mc90;\n else\n [bv magco stan av me mer me2, pr] = bvalca3(b,1,1);\n end\n\n l = topb(:,6) >= magco-0.05;\n n1 = length(topb(l,:));\n if length(topb(l,:)) >= Nmin\n [topbv magco topstan topav topme topmer topme2, toppr] = bvalca3(topb(l,:),2,2);\n [topav2 topbv2 topstan2 ] = bmemag(topb(l,:));\n else\n topbv = nan; topbv2 = nan, magco = nan; topav = nan; topav2 = nan;\n nobv = nobv + 1;\n end\n\n newt2 = botb;\n mcperc_ca3;\n l = botb(:,6) >= magco-0.05;\n n2 = length(botb(l,:));\n\n if length(botb(l,:)) >= Nmin\n [botbv magco botstan botav botme botmer botme2, botpr] = bvalca3(botb(l,:),2,2);\n [botav2 botbv2 botstan2 ] = bmemag(botb(l,:));\n else\n botbv = nan; botbv2 = nan, magco = nan; botav = nan; bottopav2 = nan;\n nobv = nobv + 1;\n end\n\n elseif inb1 == 1\n % newt2 = topb;\n % mcperc_ca3;\n [topbv magco topstan topav topme topmer topme2, toppr] = bvalca3(topb,1,1);\n l = topb(:,6) >= magco-0.05;\n if length(topb(l,:)) >= Nmin\n [topav2 topbv2 topstan2 ] = bmemag(topb(l,:));\n n1 = length(topb(l,:));\n else\n topbv = nan; topbv2 = nan; magco = nan; topav = nan; topav2 = nan;\n n1 = nan;\n\n\n nobv = nobv + 1;\n end\n % newt2 = botb;\n % mcperc_ca3;\n [botbv magco botstan botav botme botmer botme2, botpr] = bvalca3(botb,1,1);\n l = botb(:,6) >= magco-0.05;\n if length(botb(l,:)) >= Nmin\n [botav2 botbv2 botstan2 ] = bmemag(botb(l,:));\n n2 = length(botb(l,:));\n\n else\n botbv = nan; botbv2 = nan; magco = nan; botav = nan; botav2 = nan;\n n2 = nan;\n nobv = nobv + 1;\n end\n\n elseif inb1 == 2\n [topbv magco topstan topav topme topmer topme2, toppr] = bvalca3(topb,2,2);\n n1 = length(topb);\n [topav2 topbv2 topstan2 ] = bmemag(topb);\n\n [botbv magco botstan botav botme botmer botme2, botpr] = bvalca3(botb,2,2);\n\n n2 = length(botb);\n [botav2 botbv2 botstan2 ] = bmemag(botb);\n\n end\n\n else\n topbv = nan; topbv2 = nan; magco = nan; topav = nan; topav2 = nan;\n botbv = nan; botbv2 = nan; magco = nan; botav = nan; botav2 = nan;\n nobv = nobv + 1;\n\n end\n\n bv = topbv/botbv; bv2 = topbv2/botbv2; stan2 = topstan2/botstan2; av = topav/botav;\n stan = topstan/botstan;\n n = n1+n2; bo1 = topbv; b2 = botbv;\n da = -2*n*log(n) + 2*n1*log(n1+n2*bo1/b2) + 2*n2*log(n1*b2/bo1+n2) - 2;\n pr = (1 - exp(-da/2-2))*100;\n\n bvg = [bvg ; bv magco x y rd bv2 av pr topbv botbv];\n waitbar(allcount/itotal)\n\n end\n\n snobv = num2str(nobv);\n spnobv = num2str((nobv/allcount)*100.0);\n disp(['Not enough EQs to calculate b values for ', snobv, ' gridnodes. This is ',spnobv,'% of the total'])\n\n save tmpncal.mat\n quit\n\n % for newgr\n %save cnssgrid.mat\n %quit\n % save data\n %\n catSave3 =...\n [ 'zmap_message_center.set_info(''Save Grid'','' '');think;',...\n '[file1,path1] = uiputfile(fullfile(hodi, ''eq_data'', ''*.mat''), ''Grid Datafile Name?'') ;',...\n ' sapa2 = [''save '' path1 file1 '' bvg gx gy dx dy par1 tdiff t0b teb a main faults mainfault coastline yvect xvect tmpgri ll depth_ratio top_zonet top_zoneb bot_zoneb bot_zonet''];',...\n ' if length(file1) > 1, eval(sapa2),end , done']; eval(catSave3)\n\n close(wai)\n watchoff\n\n % plot the results\n % old and re3 (initially ) is the b-value matrix\n %\n normlap2=ones(length(tmpgri(:,1)),1)*nan;\n normlap2(ll)= bvg(:,1);\n re3=reshape(normlap2,length(yvect),length(xvect));\n\n normlap2(ll)= bvg(:,5);\n r=reshape(normlap2,length(yvect),length(xvect));\n\n normlap2(ll)= bvg(:,6);\n meg=reshape(normlap2,length(yvect),length(xvect));\n\n normlap2(ll)= bvg(:,2);\n old1=reshape(normlap2,length(yvect),length(xvect));\n\n % normlap2(ll)= bvg(:,7);\n % pro=reshape(normlap2,length(yvect),length(xvect));\n\n normlap2(ll)= bvg(:,7);\n avm=reshape(normlap2,length(yvect),length(xvect));\n\n % normlap2(ll)= bvg(:,9);\n % stanm=reshape(normlap2,length(yvect),length(xvect));\n\n normlap2(ll)= bvg(:,8);\n Prmap=reshape(normlap2,length(yvect),length(xvect));\n\n\n normlap2(ll)= bvg(:,9);\n top_b=reshape(normlap2,length(yvect),length(xvect));\n\n normlap2(ll)= bvg(:,10);\n bottom_b=reshape(normlap2,length(yvect),length(xvect));\n\n old = re3;\n\n % View the b-value map\n view_bdepth\n\nend % if sel = na\n\n% Load exist b-grid\nif sel == 'lo'\n [file1,path1] = uigetfile(['*.mat'],'b-value gridfile');\n if length(path1) > 1\n think\n load([path1 file1])\n normlap2=ones(length(tmpgri(:,1)),1)*nan;\n\n\n normlap2(ll)= bvg(:,1);\n re3=reshape(normlap2,length(yvect),length(xvect));\n\n normlap2(ll)= bvg(:,5);\n r=reshape(normlap2,length(yvect),length(xvect));\n\n normlap2(ll)= bvg(:,6);\n meg=reshape(normlap2,length(yvect),length(xvect));\n\n normlap2(ll)= bvg(:,2);\n old1=reshape(normlap2,length(yvect),length(xvect));\n\n % normlap2(ll)= bvg(:,7);\n % pro=reshape(normlap2,length(yvect),length(xvect));\n\n normlap2(ll)= bvg(:,7);\n avm=reshape(normlap2,length(yvect),length(xvect));\n\n % normlap2(ll)= bvg(:,9);\n % stanm=reshape(normlap2,length(yvect),length(xvect));\n\n normlap2(ll)= bvg(:,8);\n Prmap=reshape(normlap2,length(yvect),length(xvect));\n\n normlap2(ll)= bvg(:,9);\n top_b=reshape(normlap2,length(yvect),length(xvect));\n\n normlap2(ll)= bvg(:,10);\n bottom_b=reshape(normlap2,length(yvect),length(xvect));\n\n old = re3;\n\n view_bdepth\n else\n return\n end\nend\n", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/zmap_deprecated/orphaned/src/bdepth_ratio_auto.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802735722128, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.3474975639539136}} {"text": "% Check the configuration section to make the necessary adjustments to\n% run this script.\n\n% @\n% Copyright (C) 2017 Jonas Ruesch\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n% @\n\n% Configuration\n% ===================================================================================\ntornadoDirectory = 'F:\\svn\\dev\\matlab\\tornado\\T135_export'; % where is Tornado installed?\nnameTornadoAircraftGeometry = 'ExperimentalCarrier'; % which Tornado model to use?\nestimatedVelocity = 12; % 12; % the velocity at which aerodynamic coefficients are computed.\nvelocityDeviationTol = 0.5; % how much the found trimmed velocity can differ from the estimated velocity to accept the solution.\nairDensity = 1.225;\nelevatorFlapIndex = 1; % which is the elevator flap in the Tornado model?\nrudderFlapIndex = 2; % which is the rudder flap in the Tornado model?\ncenterOfGravity = 0.092; % in meters from zero of Tornado aircraft model reference frame. Tornado x-axis extends aft (!) -> positive.\nmass = 1.56; % aircraft mass in kg (overwrites the value set in the Tornado model).\nInertiaTensor = [1 0 0; 0 1 0; 0 0 1]; % inertia tensor (TODO: compute a realistic one :)\n% The alpha-sweep configuration\nalphaStart = 4; %2;\nalphaEnd = 6; % 6;\nnumAlphas = 5;\n% The beta-sweep configuration\nbetaStart = -1;\nbetaEnd = 1;\nnumBetas = 5;\ncomputeStaticMargin = 0; % [0/1]\n% ===================================================================================\n\nnameLongitudinalModel = 'ExperimentalCarrier_longitudinal';\nnameLateralModel = 'ExperimentalCarrier_lateral';\n\ndisp(' ');\n\n% Compute longitudinal and lateral LTIs for trimmed gliding. \n[ltiLongitudinal, trimmedStateVariablesLongitudinal, ltiLateral, trimmedStateVariablesLateral, Cm_longitudinal, Cn_lateral] = computeLTIs(...\n tornadoDirectory, ... % absolute path to the Tornado root directory\n nameTornadoAircraftGeometry, ... % the name of the Tornado geometry file\n nameLongitudinalModel, ... % the name of the Simulink long. model.\n nameLateralModel,... % the name of the Simulink lateral model. \n alphaStart, alphaEnd, ... % range in degrees over which coefficients are computed for the longitudinal model\n numAlphas, ... % the number of alphas to sample\n betaStart, betaEnd, ... range in degrees over which coefficients are computed for the lateral model\n numBetas, ... the number of betas to sample \n estimatedVelocity, ... % velocity in m/s for which aerodyn. coeffs. are computed\n velocityDeviationTol, ... % factor [0 ... 1].\n airDensity, ... % kg/m^3 -> 1.225 at sea level\n elevatorFlapIndex, ...\n rudderFlapIndex, ...\n mass, ...\n centerOfGravity, ...\n InertiaTensor); % inertia tensor\ntrimmedAlphaRad = atan(trimmedStateVariablesLongitudinal(2)/trimmedStateVariablesLongitudinal(1)); % atan(w/u);\ntrimmedBetaRad = atan(trimmedStateVariablesLateral(1)/trimmedStateVariablesLongitudinal(1)); % atan(w/v);\n\n% Compute static margin of the aircraft.\nif(computeStaticMargin)\n disp('Computing static margin of longitudinal dynamics...');\n [ac, staticMarginMAC, staticMarginInMeters] = computeStaticMargin(nameTornadoAircraftGeometry, ...\n estimatedVelocity, airDensity, tornadoDirectory, centerOfGravity);\n disp(['Static margin as MAC factor : ' num2str(staticMarginMAC)]);\n disp(['Static margin (sm) (m) : ' num2str(staticMarginInMeters)]);\n disp(['Aerodynamic center (ac) (m) : ' num2str(ac)]);\n disp(['ac - sm = center of gravity : ' num2str(ac - staticMarginInMeters)]);\nend\n\n% Longitudinal\n% ========================================================================\n% disp('The longitudinal LTI:');\n% ltiLongitudinal\n\n% sort complex numbers\npolesLongitudinal = cplxpair(pole(ltiLongitudinal)); % sort first complex pairs (each with negative imag. part first, then pure real (ascending?)).\n\n% Poles Map\nfigure();\nh = subplot(2,2,1);\nhold on;\nplot(h, real(polesLongitudinal(1)), imag(polesLongitudinal(1)), 'rx');\nplot(h, real(polesLongitudinal(2)), imag(polesLongitudinal(2)), 'bx');\nplot(h, real(polesLongitudinal(3)), imag(polesLongitudinal(3)), 'ro');\nplot(h, real(polesLongitudinal(4)), imag(polesLongitudinal(4)), 'bo');\nhold off;\nlegend('phugoid mode 1', 'phugoid mode 2', 'short period mode 1', 'short period mode 2');\ntitle('Longitudinal Poles Map');\nxlabel('re');\nylabel('im');\n\n% Step response\n% Remember: for a trimmed glide, LTI state variables are all 0. Thus, the plot \n% shows the resulting deviation of state variables from the trimmed state.\n% Also note: with the current model (very little air resistance -> very\n% good gliding ratio, the non-linear matlab model shows that it is sensible\n% that w (the velocity in body-z) is becoming negative (moving 'upwards' in\n% body-z).\nh = subplot(2,2,2);\nelevatorDeflectionStep = 2*pi/180;\nstepOpt = stepDataOptions('StepAmplitude', elevatorDeflectionStep); % step response for elevatorDeflectionStep radian elevator deflection\nstepplot(h, ltiLongitudinal, stepOpt);\ntitle('Longitudinal Step Response');\nhAllAxes = findobj(gcf,'type','axes');\nhLeg = findobj(hAllAxes,'tag','legend');\nhAxes = setdiff(hAllAxes,hLeg); % All axes which are not\nfor k=1:length(hAxes)\n if ~isempty(strfind(hAxes(k).YLabel.String, '(1)'))\n hAxes(k).Title.String = ['State change for an elevator step of ' num2str(elevatorDeflectionStep*180/pi) ' degrees'];\n hAxes(k).YLabel.String = 'u (m/s)'; % velocity in body x-axis\n elseif ~isempty(strfind(hAxes(k).YLabel.String, '(2)'))\n hAxes(k).YLabel.String = 'w (m/s)'; % velocity in body z-axis\n elseif ~isempty(strfind(hAxes(k).YLabel.String, '(3)'))\n hAxes(k).YLabel.String = 'q (rad/s)'; % rotation velocity around y-axis\n elseif ~isempty(strfind(hAxes(k).YLabel.String, '(4)'))\n hAxes(k).YLabel.String = 'theta (rad)'; % angle body-x vs earth-x\n end\nend\n\n% Impulse response\nh = subplot(2,2,3);\nimpulseplot(h, ltiLongitudinal);\ntitle('Longitudinal Impulse Response');\nhAllAxes = findobj(gcf,'type','axes');\nhLeg = findobj(hAllAxes,'tag','legend');\nhAxes = setdiff(hAllAxes,hLeg); % All axes which are not\nfor k=1:length(hAxes)\n if ~isempty(strfind(hAxes(k).YLabel.String, '(1)'))\n hAxes(k).Title.String = 'State change for an elevator dirac impulse';\n hAxes(k).YLabel.String = 'u (m/s)'; % velocity in body x-axis\n elseif ~isempty(strfind(hAxes(k).YLabel.String, '(2)'))\n hAxes(k).YLabel.String = 'w (m/s)'; % velocity in body z-axis\n elseif ~isempty(strfind(hAxes(k).YLabel.String, '(3)'))\n hAxes(k).YLabel.String = 'q (rad/s)'; % rotation velocity around y-axis\n elseif ~isempty(strfind(hAxes(k).YLabel.String, '(4)'))\n hAxes(k).YLabel.String = 'theta (rad)'; % angle body-x vs earth-x\n end\nend\n\n% Plot pitch moment curve\nh = subplot(2,2,4);\nhold on;\nplot(h, [alphaStart:(alphaEnd-alphaStart)/(numAlphas-1):alphaEnd], Cm_longitudinal, 'r-');\nplot(h, trimmedAlphaRad*180/pi, 0, 'bx');\nhold off;\nlegend('Cm', ['trimmed alpha = ' num2str(trimmedAlphaRad*180/pi) ' (deg)']);\ntitle('Pitch moment');\nxlabel('alpha');\nylabel('Cm');\n\n% Compute damping, frequency, period from poles. See also p83 in Caughey.\n\n% Short period poles\npolesShortPeriod = polesLongitudinal(3:4); % choose last ones from sorted complex numbers\npolesShortPeriodReal = real(polesShortPeriod);\npolesShortPeriodImag = imag(polesShortPeriod);\n\nDamping_sp = sqrt(1./(1+(polesShortPeriodImag./polesShortPeriodReal).^2)); % Damping ratio\nFrequency_sp = -polesShortPeriodReal./Damping_sp; % Undampted, natural frequency per second\nPeriod_sp = 2*pi./(Frequency_sp.*sqrt(1-Damping_sp.^2)); % seconds\nCycles_half_sp = ((log(2))/(2*pi))*sqrt(1-Damping_sp.^2)./Damping_sp; % Number of cycles to damp to half the amplitude\n\n% Output result for longitudinal trimmed state\ndisp('Short Period Mode Properties (longitudinal): ');\ndisp(' Pole 1 Pole 2');\ndisp('==============================================================================');\ndisp(sprintf(['Damping ratio : ' num2str(Damping_sp(:)')]));\ndisp(sprintf(['Undampted, natural frequency (1/s): ' num2str(Frequency_sp(:)')]));\ndisp(sprintf(['Period (s): ' num2str(Period_sp(:)')]));\ndisp(sprintf(['Num. cycles to damp to half the amplitude : ' num2str(Cycles_half_sp(:)')]));\ndisp(' ');\n\n% Phugoid poles\npolesPhugoid = polesLongitudinal(1:2); % choose first ones from sorted complex numbers\npolesPhugoidReal = real(polesPhugoid);\npolesPhugoidImag = imag(polesPhugoid);\n\nDamping_ph = sqrt(1./(1+(polesPhugoidImag./polesPhugoidReal).^2)); % Damping ratio\nFrequency_ph = -polesPhugoidReal./Damping_ph; % Undampted, natural frequency per second\nPeriod_ph = 2*pi./(Frequency_ph.*sqrt(1-Damping_ph.^2)); % seconds\nCycles_half_ph = ((log(2))/(2*pi))*sqrt(1-Damping_ph.^2)./Damping_ph; % Number of cycles to damp to half the amplitude\n\n% Output result for longitudinal trimmed state\ndisp('Phugoid Mode Properties (longitudinal): ');\ndisp(' Pole 1 Pole 2');\ndisp('==============================================================================');\ndisp(sprintf(['Damping ratio : ' num2str(Damping_ph(:)')]));\ndisp(sprintf(['Undampted, natural frequency (1/s): ' num2str(Frequency_ph(:)')]));\ndisp(sprintf(['Period (s): ' num2str(Period_ph(:)')]));\ndisp(sprintf(['Num. cycles to damp to half the amplitude : ' num2str(Cycles_half_ph(:)')]));\ndisp(' ');\n\n% Lateral\n% ========================================================================\n\n%disp('The lateral LTI:');\n%ltiLateral\n\n% sort complex numbers\npolesLateral = cplxpair(pole(ltiLateral)); % sort first complex pairs (each with negative imag. part first, then pure real (ascending?)).\n\n% Poles Map\nfigure();\nh = subplot(2,2,1);\nhold on;\nplot(h, real(polesLateral(1)), imag(polesLateral(1)), 'rx');\nplot(h, real(polesLateral(2)), imag(polesLateral(2)), 'bx');\nplot(h, real(polesLateral(3)), imag(polesLateral(3)), 'ro');\nplot(h, real(polesLateral(4)), imag(polesLateral(4)), 'bo');\nhold off;\nlegend('dutch roll mode 1', 'dutch roll mode 2', 'rolling mode', 'spiral mode');\ntitle('Lateral Poles Map');\nxlabel('re');\nylabel('im');\n\n% Step response\n% Remember: for a trimmed glide, LTI state variables are all 0. Thus, the plot \n% shows the resulting deviation of state variables from the trimmed state.\nh = subplot(2,2,2);\nrudderDeflectionStep = 2*pi/180;\nstepOpt = stepDataOptions('StepAmplitude', rudderDeflectionStep); % step response for elevatorDeflectionStep radian elevator deflection\nstepplot(h, ltiLateral, stepOpt);\ntitle('Lateral Step Response');\nhAllAxes = findobj(gcf,'type','axes');\nhLeg = findobj(hAllAxes,'tag','legend');\nhAxes = setdiff(hAllAxes,hLeg); % All axes which are not\nfor k=1:length(hAxes)\n if ~isempty(strfind(hAxes(k).YLabel.String, '(1)'))\n hAxes(k).Title.String = ['State change for a rudder step of ' num2str(rudderDeflectionStep*180/pi) ' degrees'];\n hAxes(k).YLabel.String = 'v (m/s)'; % velocity in body y-axis\n elseif ~isempty(strfind(hAxes(k).YLabel.String, '(2)'))\n hAxes(k).YLabel.String = 'p (rad/s)'; % rotation velocity around x-axis\n elseif ~isempty(strfind(hAxes(k).YLabel.String, '(3)'))\n hAxes(k).YLabel.String = 'phi (rad)'; % roll angle (euler phi)\n elseif ~isempty(strfind(hAxes(k).YLabel.String, '(4)'))\n hAxes(k).YLabel.String = 'r (rad/s)'; % rotation velocity around z-axis\n end\nend\n\n% Impulse response\nh = subplot(2,2,3);\nimpulseplot(h, ltiLateral);\ntitle('Lateral Impulse Response');\nhAllAxes = findobj(gcf,'type','axes');\nhLeg = findobj(hAllAxes,'tag','legend');\nhAxes = setdiff(hAllAxes,hLeg); % All axes which are not\nfor k=1:length(hAxes)\n if ~isempty(strfind(hAxes(k).YLabel.String, '(1)'))\n hAxes(k).Title.String = 'State change for a rudder dirac impulse';\n hAxes(k).YLabel.String = 'v (m/s)'; % velocity in body y-axis\n elseif ~isempty(strfind(hAxes(k).YLabel.String, '(2)'))\n hAxes(k).YLabel.String = 'p (rad/s)'; % rotation velocity around x-axis\n elseif ~isempty(strfind(hAxes(k).YLabel.String, '(3)'))\n hAxes(k).YLabel.String = 'phi (rad)'; % roll angle (euler phi)\n elseif ~isempty(strfind(hAxes(k).YLabel.String, '(4)'))\n hAxes(k).YLabel.String = 'r (rad/s)'; % rotation velocity around z-axis\n end\nend\n\n% Plot yaw moment curve\nh = subplot(2,2,4);\nhold on;\nplot(h, [betaStart:(betaEnd-betaStart)/(numBetas-1):betaEnd], Cn_lateral, 'r-');\nplot(h, trimmedBetaRad*180/pi, 0, 'bx');\nhold off;\nlegend('Cn', ['trimmed beta = ' num2str(trimmedBetaRad*180/pi) ' (deg)']);\ntitle('Yaw moment');\nxlabel('beta');\nylabel('Cn');\n\n% Compute damping, frequency, period from poles. See also p83 in Caughey.\n\n% Roll pole\npoleRoll = polesLateral(3);\npoleRollReal = real(poleRoll);\npoleRollImag = imag(poleRoll);\n\nDamping_roll = sqrt(1./(1+(poleRollImag./poleRollReal).^2)); % Damping ratio\nFrequency_roll = -poleRollReal./Damping_roll; % Undampted, natural frequency per second\nPeriod_roll = 2*pi./(Frequency_roll.*sqrt(1-Damping_roll.^2)); % seconds\nCycles_half_roll = ((log(2))/(2*pi))*sqrt(1-Damping_roll.^2)./Damping_roll; % Number of cycles to damp to half the amplitude\n\ndisp('Roll Mode Properties (lateral): ');\ndisp(' Pole 1');\ndisp('==============================================================================');\ndisp(sprintf(['Damping ratio : ' num2str(Damping_roll(:)')]));\ndisp(sprintf(['Undampted, natural frequency (1/s): ' num2str(Frequency_roll(:)')]));\ndisp(sprintf(['Period (s): ' num2str(Period_roll(:)')]));\ndisp(sprintf(['Num. cycles to damp to half the amplitude : ' num2str(Cycles_half_roll(:)')]));\ndisp(' ');\n\n% Spiral pole\npoleSpiral = polesLateral(4);\npoleSpiralReal = real(poleSpiral);\npoleSpiralImag = imag(poleSpiral);\n\nDamping_spiral = sqrt(1./(1+(poleSpiralImag./poleSpiralReal).^2)); % Damping ratio\nFrequency_spiral = -poleSpiralReal./Damping_spiral; % Undampted, natural frequency per second\nPeriod_spiral = 2*pi./(Frequency_spiral.*sqrt(1-Damping_spiral.^2)); % seconds\nCycles_half_spiral = ((log(2))/(2*pi))*sqrt(1-Damping_spiral.^2)./Damping_spiral; % Number of cycles to damp to half the amplitude\n\ndisp('Spiral Mode Properties (lateral): ');\ndisp(' Pole 1');\ndisp('==============================================================================');\ndisp(sprintf(['Damping ratio : ' num2str(Damping_spiral(:)')]));\ndisp(sprintf(['Undampted, natural frequency (1/s): ' num2str(Frequency_spiral(:)')]));\ndisp(sprintf(['Period (s): ' num2str(Period_spiral(:)')]));\ndisp(sprintf(['Num. cycles to damp to half the amplitude : ' num2str(Cycles_half_spiral(:)')]));\ndisp(' ');\n\n% Dutch Roll poles\npolesDutchRoll = polesLateral(1:2); % choose first ones from sorted complex numbers\npolesDutchRollReal = real(polesDutchRoll);\npolesDutchRollImag = imag(polesDutchRoll);\n\nDamping_dutch = sqrt(1./(1+(polesDutchRollImag./polesDutchRollReal).^2)); % Damping ratio\nFrequency_dutch = -polesDutchRollReal./Damping_dutch; % Undampted, natural frequency per second\nPeriod_dutch = 2*pi./(Frequency_dutch.*sqrt(1-Damping_dutch.^2)); % seconds\nCycles_half_dutch = ((log(2))/(2*pi))*sqrt(1-Damping_dutch.^2)./Damping_dutch; % Number of cycles to damp to half the amplitude\n\n% Output result for longitudinal trimmed state\ndisp('Dutch Roll Mode Properties (lateral): ');\ndisp(' Pole 1 Pole 2');\ndisp('==============================================================================');\ndisp(sprintf(['Damping ratio : ' num2str(Damping_dutch(:)')]));\ndisp(sprintf(['Undampted, natural frequency (1/s): ' num2str(Frequency_dutch(:)')]));\ndisp(sprintf(['Period (s): ' num2str(Period_dutch(:)')]));\ndisp(sprintf(['Num. cycles to damp to half the amplitude : ' num2str(Cycles_half_dutch(:)')]));\ndisp(' ');\n\n% =========================================================================\n\n% Observability\ndisp(['Number of unobservable states (longitudinal) : ' num2str(length(ltiLongitudinal.a) - rank(obsv(ltiLongitudinal)))]);\ndisp(['Number of unobservable states (lateral) : ' num2str(length(ltiLateral.a) - rank(obsv(ltiLateral)))]);\ndisp(' ');\n\n% Controllability\ndisp(['Number of uncontrollable states (longitudinal): ' num2str(length(ltiLongitudinal.a) - rank(ctrb(ltiLongitudinal)))]);\ndisp(['Number of uncontrollable states (lateral) : ' num2str(length(ltiLateral.a) - rank(ctrb(ltiLateral)))]);\ndisp(' ');\n\n% TODO\n% ========================================================================\n\n% 1) Run this whole thing for different center of gravity settings and plot\n% Cm curve and poles.\n\n", "meta": {"author": "jrgenerative", "repo": "fixed-wing-sim", "sha": "53fd5b616a2bd296f37f1f105617c606c2f63066", "save_path": "github-repos/MATLAB/jrgenerative-fixed-wing-sim", "path": "github-repos/MATLAB/jrgenerative-fixed-wing-sim/fixed-wing-sim-53fd5b616a2bd296f37f1f105617c606c2f63066/ExperimentalCarrierSimulink/code/mainComputeLTIs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7662936430859598, "lm_q2_score": 0.45326184801538605, "lm_q1q2_score": 0.3473316727875848}} {"text": "function [xsol,objp,info,msg,times,x,y,z,s,w] = lipsol(A,b,c,lb,ub,opts)\n% LIPSOL - Main program for LIPSOL\n\n% Yin Zhang, January, 1995\n% Department of Mathematics and Statistics\n% University of Maryland Baltimore County\n% Modified J.Currie AUT May 2013\n\nglobal probData\n\nif(nargin < 6)\n opts = lipsolset; \n opts.maxiter = 100;\n opts.maxtime = 1000;\n opts.tol = 1e-5;\nend\nif(nargin < 5), ub = []; end\nif(nargin < 4), lb = []; end\nif(nargin < 3), error('You must supply at least 3 arguments to lipsol(A,b,c)'); end\n\ntimes = zeros(5,1);\nt0 = tic;\n\n%Problem Data Structure to avoid so many Global Variables\nprobData = struct('NNZA',0,'NNZL',0,'XLNZ',[],'PERM',[],'INVP',[],'LNZ',[],'LOOP_LEVEL',[],...\n 'XSUPER',[],'XLINDX',[],'LINDX',[],'SNODE',[],'SPLIT',[],'TMPSIZ',[],...\n 'LNZ0',[],'b_orig',b,'c_orig',c,'data_changed',0,'isFeasible',1,...\n 'Lbounds_non0',[],'Ubounds_exist',0,'nub',0,'Fixed_exist',0,...\n 'ifix',[],'infx',[],'xfix',[],'Zrcols_exist',0,'izrcol',[],...\n 'inzcol',[],'xzrcol',[],'Sgtons_exist',0,'isolved',[],...\n 'insolved',[],'xsolved',[],'nt',0,'message',[],...\n 'col_scaled',0,'colscl',[],'Dense_cols_exist',0,'Mdense',[],...\n 'idense',[],'ispars',[],'Hist',[],'Sherman_OK',[],'backed',[]);\n%Initial Time \nopts.t0 = tic;\n\n%Save loop_level into problem structure\nprobData.LOOP_LEVEL = opts.loop_level;\n \n%Pretty Printing\nif(opts.verb), fprintf('----------------------------------------------\\n'); end\n \n%Preprocess the Input Data\n[A,b,c,lb,ub] = ls_preprocess(A,b,c,lb,ub,opts); \ntimes(1) = toc(t0);\n\n%Check if preproccesor indicates infeasible\nif(~probData.isFeasible)\n xsol = []; objp = []; info = [-1 0 0]; msg = 'Presolve Indicated Infeasible'; times = [];\n x = []; y = []; z = []; s = []; w = [];\n return;\nend\n\n%Scale the Input Data if Required\n[A,b,c,ub] = scaling(A,b,c,ub,opts);\n%Determine density of the problem\ncheckDense(A,opts);\ntimes(2) = toc(t0) - times(1);\n\n%Solve the Problem\n[x,y,z,s,w,info] = ls_miip(A,b,c,ub,opts); \ntimes(3) = toc(t0) - times(2);\n\n%Display Solve Status\nif(opts.verb && ~isempty(probData.message)), fprintf('\\n Status: %s\\n',probData.message); end\n\n%Post Process the Solution\n[xsol, objp, times ] = ls_postprocess(x,y,lb,opts.verb,times,t0);\nmsg = probData.message;\n\n%Pretty Printing\nif(opts.verb), fprintf('----------------------------------------------\\n'); end\n\n\nfunction [A,b,c,ub] = scaling(A,b,c,ub,opts)\n% SCALING - Scale matrix A. Usage: [A,b,c,ubounds] = scaling(A,b,c,ubounds)\n% Yin Zhang, January, 1995\n% Department of Mathematics and Statistics\n% University of Maryland Baltimore County\n\nglobal probData\n\n[m, n] = size(A);\nbadscl = 1.e-4;\n\nabsnzs = abs(nonzeros(A));\nthescl = min(absnzs)/max(absnzs);\nclear absnzs\n\nif (thescl < badscl)\n if(opts.verb), fprintf('Scaling ...\\n'); end\n\n % ----- scaling vectors ------\n AA = abs(A);\n colscl = full(sqrt(max(AA)'));\n rowscl = full(sqrt(max(AA,[],2)));\n clear AA;\n\n % ----- column scaling -----\n if (probData.Ubounds_exist), ub = ub.*colscl; end\n colscl = reciprocal(colscl);\n A = A*sparse(1:n,1:n,colscl);\n c = c.*colscl;\n probData.col_scaled = 1;\n\n % ----- row scaling -----\n rowscl = reciprocal(rowscl);\n A = sparse(1:m,1:m,rowscl)*A;\n b = b.*rowscl;\n bnrm = norm(b);\n if (bnrm > 0) \n q = median([1 norm(c)/bnrm 1.e+8]);\n if (q > 10), A = q*A; b = q*b; end\n end\n probData.data_changed = 1;\n probData.colscl = colscl;\nend\n\n\nfunction checkDense(A,opts) %#ok\n% CHECKDENSE - Determine and locate dense columns of matrix A.\n% Yin Zhang, January, 1995\n% Department of Mathematics and Statistics\n% University of Maryland Baltimore County\n\n%PROBLEM IN PCG - SKIPPING DENSE COLUMN MANAGEMENT [J.C. 19/5/13]\n\n% global probData\n% \n% [m, n] = size(A);\n% probData.ispars = 1:n; \n% nzratio = 1;\n% if (m > 500), nzratio = 0.20; end;\n% if (m > 1000), nzratio = 0.10; end;\n% if (m > 5000), nzratio = 0.05; end;\n% \n% if (nzratio < 1)\n% checking = sum(spones(A))/m <= nzratio;\n% if any(checking == 0)\n% probData.Dense_cols_exist = 1;\n% probData.idense = find(sparse(1-checking)); % Dense column indices\n% probData.ispars = find(checking); % Sparse column indices\n% if(opts.verb), fprintf('Dense columns (nnz/m > %g): %i\\n',nzratio,length(probData.idense)); end\n% else\n% if(opts.verb), fprintf('No Significant Dense Columns\\n'); end\n% end\n% clear checking\n% else\n% if(opts.verb), fprintf('Problem is Small Enough to Ignore Dense Columns\\n'); end\n% end\n\n\nfunction Y = reciprocal(X)\n% RECIPROCAL - Invert the nonzero entries of a matrix elementwise.\n% Y = RECIPROCAL(X) has the same sparsity pattern as X\n%\t (except possibly for underflow).\n\n% Yin Zhang, January, 1995\n% Department of Mathematics and Statistics\n% University of Maryland Baltimore County\n\nif issparse(X)\n [m, n] = size(X);\n [i,j,Y] = find(X);\n Y = sparse(i,j,1./Y,m,n);\nelse\n Y = 1./X;\nend\nceiling = 1.e+16; Y = min(ceiling,Y);", "meta": {"author": "vigente", "repo": "gerardus", "sha": "4d7c5195b826967781f1bb967872410e66b7cd3d", "save_path": "github-repos/MATLAB/vigente-gerardus", "path": "github-repos/MATLAB/vigente-gerardus/gerardus-4d7c5195b826967781f1bb967872410e66b7cd3d/matlab/ThirdPartyToolbox/OptiToolbox/Solvers/lipsol/lipsol.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442251201477016, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.34722653010511845}} {"text": "function [funOut, indexStart, problemDom, coeffs, totalDiffOrders] = ...\n toFirstOrder(funIn, rhs, domain, numArgs, cellArg)\n%TOFIRSTORDER Convert higher order anonymous functions to first order systems.\n% Calling sequence:\n% [FUNOUT, INDEXSTART, PROBLEMDOM, COEFFS, TOTALDIFFORDERS] = ...\n% TOFIRSTORDER(FUNIN, RHS, DOMAIN)\n% where the inputs are:\n% FUNIN: An anonymous function which describes an ODE, usually including\n% higher order derivatives, e.g. @(x,u) diff(u, 2) + sin(u).\n% Usually, the anonymous function comes from the OP field of a\n% CHEBOP.\n% RHS: The right hand side of the differential equation being solved\n% with a CHEBOP, that is, the right argument of a CHEBOP\n% backslash.\n% DOMAIN: The domain of the problem we're trying to solve.\n% and the outputs are:\n% FUNOUT: An anonymous function that is the first order reformulation\n% of FUNIN, which can be passed to the MATLAB solvers.\n% INDEXSTART: A vector that denotes at which index we should start\n% indexing each variable from so that they're in the correct\n% order for the MATLAB ODE solvers.\n% PROBLEMDOM: The domain on which the problem can be specified, which may\n% include breakpoints originally not included in DOMAIN.\n% COEFFS: A cell array of the coefficients the multiply the highest\n% order derivatives in problem. For example, for the problem\n% @(x,u) 5*diff(u, 2) + u, we will have COEFFS{1} = 5.\n% TOTALDIFFORDERS:\n% A vector that contains the maximum diffOrder applying to\n% each variable in the problem.\n%\n% In addition, one can pass the following arguments to the function, which are\n% only required if working in CHEBMATRIX syntax, for example, \n% @(x,u)[diff(u{1}) + u{2};...]:\n% NVARS: The number of unknown variables in the ODE.\n% CELLARG: Specify as TRUE if FUNIN is specified in CHEBMATRIX syntax.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\n% Independent variable on the domain\nt = chebfun(@(t) t, domain);\n\n% See if we need to determine the number of variables involved, or if it was\n% passed as an argument.\nif ( nargin < 4)\n % We always have at least one argument to FUNIN, even in the scalar case. In\n % the system case, the first argument to funIn must be the independent time\n % variable. So the number of treeVar arguments needed is one less:\n numArgs = max(1, nargin(funIn) - 1);\n % If working in CHEBMATRIX syntax, we need all possible input variables to\n % be passed in as arguments:\n cellArg = false;\nend\nargs = cell(numArgs, 1);\nargsVec = zeros(1, numArgs);\n\n% Populate the args cell\nfor argCount = 1:numArgs\n argsVec(argCount) = 1;\n args{argCount} = treeVar(argsVec, domain);\n % Reset the index vector\n argsVec = 0*argsVec;\nend\n\n% Evaluate FUNIN with the TREEVAR arguments. Need different calling sequences\n% depending on whether we're working with CHEBMATRIX syntax and cells or not:\nif ( cellArg )\n fevalResult = funIn(t, args);\nelse\n % If FUNIN only takes one argument, we just give it the TREEVAR argument. \n % Otherwise, the first input will be the independent variable on the domain:\n if ( nargin(funIn) == 1 )\n fevalResult = funIn(args{:});\n else\n fevalResult = funIn(t, args{:});\n end\nend\n\n% If we got passed the problem as N\\0, i.e. a RHS that did not match the\n% dimensions, we need to repmat it so that the RHS variable has the correct\n% dimensions below:\nif ( isnumeric(rhs) && length(rhs) == 1 )\n rhs = repmat(rhs, size(fevalResult));\nend\n\n% Ensure RHS is a CHEBMATRIX\nif ( ~isa(rhs, 'chebmatrix') )\n rhs = chebmatrix(rhs, domain);\nend\n\n\n% Initialize cells to store the infix forms of the expressions, the coefficients\n% multiplying the highest order derivatives and any variables that appear in the\n% anonymous functions:\nsystemInfix = cell(length(fevalResult), 1);\ncoeffs = systemInfix;\nvarArrays = systemInfix;\n\n% We want to return all potential breakpoints caused by piecewise coefficients\n% in the problem. So loop through fevalResult, and take the union of the\n% breakpoints:\nproblemDom = fevalResult(1).domain;\nfor resCounter = 2:length(fevalResult)\n problemDom = union(problemDom, fevalResult(resCounter).domain);\nend\n\n% Ensure we also include potential breakpoints from the RHS:\nproblemDom = union(problemDom, rhs.domain);\n\n% First look at all diffOrders to ensure we start with the correct indices.\n% INDEXSTART denotes at which index we should start indexing each variable from.\n% E.g., in the coupled system\n% [v'' + w; v + w'']\n% we will have v = u(1), v' = u(2), w = u(3), w' = u(4), so INDEXSTART = [1, 3],\n% since v and its derivatives starts getting counted at 1, and w and its\n% derivatives start getting counted at 3.\n%\n% The vector INDEXSTARTDER is similar, but here, we also assign the highest\n% order derivative of each variable it's own index. This is so that later on, we\n% can correctly evaluate the coefficient multiplying the highest order\n% derivative in problem. Thus, in the example above, we'd have\n% v = u(1), v' = u(2), v'' = u(3), w = u(4), w' = u(5), w'' = u(6)\n% Here, INDEXSTARTDER = [1 4].\n\n% First, we need to find out the maximum diffOrder of each variable appearing in\n% the problem. We loop through the each component of the evaluation tree:\ntotalDiffOrders = zeros(1, numArgs);\nfor wCounter = 1:length(fevalResult)\n totalDiffOrders = max(totalDiffOrders, ...\n fevalResult(wCounter).tree.diffOrder);\nend\n\n% We always start indexing the first variable and its derivative(s) at 1. The\n% index of the other variables depend on the cumulative diffOrders of the\n% variables with lower indices.\nindexStart = [ 1, cumsum(totalDiffOrders(1:end-1)) + 1 ];\n% To get the indices of the derivatives as well, we shift all the previous\n% indices right by 1, in cumulative fashion:\nindexStartDer = indexStart + (0:numArgs-1);\n\n% COEFFARG will be used to evaluate the functions that gives us information\n% about the coefficients multiplying the highest order derivative in each\n% equation. The vector has to be equally long to the total number of derivatives\n% appearing in the problem; we'll then change one of the entries to 1 at a time\n% to get the coefficient information.\ncoeffArg = zeros(1, indexStartDer(end) + totalDiffOrders(end));\n\n% Go through each componenent from the result of evaluating FUNIN,\n% and change it to infix format.\nfor wCounter = 1:length(fevalResult)\n \n % The current result we're looking at.\n res = fevalResult(wCounter);\n \n % Current diffOrders\n diffOrders = res.tree.diffOrder;\n \n % Ensure that we never have the highest derivatives of more than one\n % variable appearing in a single equation:\n if ( sum(totalDiffOrders == diffOrders) > 1 )\n error('CHEBFUN:TREEVAR:toFirstOrder:diffOrders', ...\n ['The highest order derivative of more than one variable ' ...\n 'appears to be\\npresent in the same equation. ' ...\n 'Unable to convert to first order format.'])\n end\n \n % Expand the tree, so that PLUS rather than TIMES is sitting at the top of\n % it.\n expTree = treeVar.expandTree(res.tree, totalDiffOrders);\n \n % Split the tree into derivative part and non-derivative part.\n [newTree, derTree] = treeVar.splitTree(expTree, totalDiffOrders);\n \n % If newTree is empty, we only have a derivative part in the expression,\n % e.g. diff(u) = 0. We must replace it with a 0, as otherwise, we can't\n % evaluate the resulting odeFun in the ODE solvers.\n if ( isempty(newTree) )\n newTree = 0;\n end\n \n % Find what argument corresponds to the highest derivative one in the\n % current expression we're looking at. This will also be the order in which\n % we store the outputs from converting individual expressions to first order\n % form -- if the input is of the form @(x,u,v) [diff(v) - u; diff(u) - v],\n % the equations have to be sorted so that they'll be correctly converted.\n maxDerLoc = find(expTree.diffOrder == totalDiffOrders);\n \n % Convert the derivative part to infix form.\n % Indicate that we are converting a coeffFun\n isCoeffFun = true;\n [infixDer, varArrayDer] = ...\n treeVar.tree2infix(derTree, maxDerLoc, indexStartDer, isCoeffFun);\n \n % Convert the infix form of the expression that gives us the coefficient\n % multiplying the highest order derivative appearing in the expression to an\n % anonymous function we can evaluate:\n coeffFun = treeVar.toAnon(infixDer, varArrayDer);\n \n % Reset coeffArg for next evaluation:\n coeffArg = 0*coeffArg;\n \n % Replace one of the 0s in coeffFun with 1 so that we can evaluate COEFFFUN:\n if ( maxDerLoc == numArgs )\n % The last variable in the system currently appears in the highest order\n % derivate.\n coeffArg(end) = 1;\n else\n % The variable with index maxDerLoc+1 is the next variable we need to\n % start numbering at. So subtract 1 for the index of the highest\n % derivative we're currently interested in.\n coeffArg(indexStartDer(maxDerLoc+1) - 1) = 1;\n end\n \n % Evaluate the COEFFFUN to the coefficient!\n coeffs{maxDerLoc} = coeffFun(t, coeffArg);\n \n % Now work with the remaining syntax tree of the current expression of\n % interest. We need to negate the syntax tree as we're moving it to the\n % right-hand side. But if it already starts with a unary minus, we can\n % simply remove it rather than doing a double negation:\n % [TODO: Remove double UMINUS]\n newTree = struct('method', 'minus', 'numArgs', 2, ...\n 'left', rhs{wCounter}, 'right', newTree);\n % Convert current expression to infix form:\n isCoeffFun = false;\n [infix, varArray] = ...\n treeVar.tree2infix(newTree, maxDerLoc, indexStart, isCoeffFun);\n % Store the infix form and the variables that appeared in the anonymous\n % function.\n systemInfix{maxDerLoc} = infix;\n varArrays{maxDerLoc} = varArray;\nend\n\n% Convert all the infix expressions, coefficients and variables stored to an\n% anonymous function we can evaluate and use as the RHS of our ODE system:\nfunOut = treeVar.toRHS(systemInfix, varArrays, coeffs, ...\n indexStart, totalDiffOrders);\n\nend\n", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/@treeVar/toFirstOrder.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442250928250375, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.34722651537866095}} {"text": "% LIONSIMBA example script\n% Different heat exchange coefficients: this script provides the example simulation shown in the\n% paper.\n\n% This file is part of the LIONSIMBA Toolbox\n%\n%\tOfficial web-site: \thttp://sisdin.unipv.it/labsisdin/lionsimba.php\n% \tOfficial GitHUB: \thttps://github.com/lionsimbatoolbox/LIONSIMBA\n%\n% LIONSIMBA: A Matlab framework based on a finite volume model suitable for Li-ion battery design, simulation, and control\n% Copyright (C) 2016-2018 :Marcello Torchio, Lalo Magni, Davide Raimondo,\n% University of Pavia, 27100, Pavia, Italy\n% Bhushan Gopaluni, Univ. of British Columbia, \n% Vancouver, BC V6T 1Z3, Canada\n% Richard D. Braatz, \n% Massachusetts Institute of Technology, \n% Cambridge, Massachusetts 02142, USA\n% \n% Main code contributors to LIONSIMBA 2.0:\n% Ian Campbell, Krishnakumar Gopalakrishnan,\n% Imperial college London, London, UK\n%\n% LIONSIMBA is a free Matlab-based software distributed with an MIT\n% license.\n\n% Clear the workspace\nclear\n\n% Define the integration times.\nt0 = 0;\ntf = 10^4;\n% Define the parameters structure. By default the hcell parameter is set to\n% 1 [W / (m^2 K)]\nparam{1} = Parameters_init;\n\n% Change the hcell parameter and set it to 0.01 [W / (m^2 K)]\nparam{1}.hcell = 0.01;\n\n% Start the simulation. Note that the final integration time is 10^4 and\n% LIONSIMBA will stop automatically when reached the Cutoff Voltage of\n% 2.5V. Note that no Jacobian among one simulation and the other. This is\n% due to the fact that the model structure changes for each of the\n% simulation (because hcell changes) and consequently also the Jacobian\n% matrix changes and cannot be used for all the scenarios.\n\nout1 = startSimulation(t0,tf,[],-30,param);\n\n% Change the hcell parameter and set it to 1 [W / (m^2 K)]\nparam{1}.hcell = 1;\n\n% Run the simulation\nout2 = startSimulation(t0,tf,[],-30,param);\n\n% Change the hcell parameter and set it to 100 [W / (m^2 K)]\nparam{1}.hcell = 100;\n\n% Run the simulation\nout3 = startSimulation(t0,tf,[],-30,param);\n\n%% Plot the results\n\nfigure(1)\nplot(out1.time{1},out1.Temperature{1}(:,end),'LineWidth',6)\nhold on\nplot(out2.time{1},out2.Temperature{1}(:,end),'--','LineWidth',6)\nplot(out3.time{1},out3.Temperature{1}(:,end),'-.','LineWidth',6)\nxlabel('Time [s]')\nylabel('Temperature [K]')\ngrid on\nbox on\n\nfigure(2)\nplot(out1.time{1},out1.Voltage{1},'LineWidth',6)\nhold on\nplot(out2.time{1},out2.Voltage{1},'--','LineWidth',6)\nplot(out3.time{1},out3.Voltage{1},'-.','LineWidth',6)\nxlabel('Time [s]')\nylabel('Voltage [V]')\ngrid on\nbox on\n\n", "meta": {"author": "lionsimbatoolbox", "repo": "LIONSIMBA", "sha": "d1cf29a4dcfa8e7824fc2416ac3e6ec760bb9b66", "save_path": "github-repos/MATLAB/lionsimbatoolbox-LIONSIMBA", "path": "github-repos/MATLAB/lionsimbatoolbox-LIONSIMBA/LIONSIMBA-d1cf29a4dcfa8e7824fc2416ac3e6ec760bb9b66/example_scripts/different_heat_exchange.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.727975460709318, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.3469382910477655}} {"text": "function [Lmk,Obs] = reparametrizeLmk(Rob,Sen,Lmk,Obs,Opt)\n\n%REPARAMETRIZELMK Reparametrize landmark.\n% [LMK,OBS] = REPARAMETRIZELMK(ROB,SEN,LMK,OBS,OPT) return the\n% reparametrized landmark and Obs structure.\n% The landmark is reparametrized only in the case of an inverse depth \n% point. A linearity test of cartesian point given inverse depth \n% point is performed.\n\n% Copyright 2009 David Marquez @ LAAS-CNRS.\n\n\nglobal Map\n\nswitch Lmk.type\n \n case 'idpPnt' \n % we will convert from inverse-depth to euclidean.\n \n % Test for linearity:\n Ld = idpLinearTest(Rob,Sen,Lmk);\n \n if Ld < Opt.correct.linTestIdp\n \n % ranges\n ir = Lmk.state.r; % idp\n er = ir(1:3); % euclidean\n m = Map.used; % map\n \n % point coordinates\n idp = Map.x(ir); % idp\n [p,P_i] = idp2euc(idp); % euclidean\n \n % map updates\n Map.x(er) = p; % mean\n \n Map.P(er,m) = P_i * Map.P(ir,m); % co- and cross-variances\n Map.P(m,er) = Map.P(m,ir) * P_i';\n \n Map.used(Lmk.state.r(4:6)) = false; % used positions\n \n % Lmk and Obs updates\n Lmk.state.r = er; % new range\n Lmk.type = 'eucPnt'; % new type\n Obs.ltype = 'eucPnt'; % new type\n end\n \n case 'ahmPnt' \n % we will convert from anchored homogeneous to euclidean.\n \n % Test for linearity:\n Ld = ahmLinearTest(Rob,Sen,Lmk);\n \n if Ld < Opt.correct.linTestIdp\n \n % ranges\n ar = Lmk.state.r; % ahmPnt\n er = ar(1:3); % euclidean\n m = Map.used; % map\n \n % point coordinates\n ahm = Map.x(ar); % idp\n [p,P_a] = ahm2euc(ahm); % euclidean\n \n % map updates\n Map.x(er) = p; % mean\n \n Map.P(er,m) = P_a * Map.P(ar,m); % co- and cross-variances\n Map.P(m,er) = Map.P(m,ar) * P_a';\n \n Map.used(Lmk.state.r(4:7)) = false; % used positions\n \n % Lmk and Obs updates\n Lmk.state.r = er; % new range\n Lmk.type = 'eucPnt'; % new type\n Obs.ltype = 'eucPnt'; % new type\n end\n \n case {'eucPnt'}\n % do nothing\n \n case {'hmgPnt','ahmPnt','plkLin','aplLin','idpLin','ahmLin','hmgLin'}\n % do nothing, by now <- probably add here something to do\n % Points should go to euclidean\n % Lines should go to some minimal representation (polar? 'plrLin')\n \n % case 'myLmk' \n % edit this 'myLmk' name to put your own landmark type\n % do something\n \n otherwise\n error('??? Unknown landmark type ''%s''.',Lmk.type)\n\nend\n\n\n\n% ========== End of function - Start GPL license ==========\n\n\n% # START GPL LICENSE\n\n%---------------------------------------------------------------------\n%\n% This file is part of SLAMTB, a SLAM toolbox for Matlab.\n%\n% SLAMTB is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% SLAMTB is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with SLAMTB. If not, see .\n%\n%---------------------------------------------------------------------\n\n% SLAMTB is Copyright:\n% Copyright (c) 2008-2010, Joan Sola @ LAAS-CNRS,\n% Copyright (c) 2010-2013, Joan Sola,\n% Copyright (c) 2014-2015, Joan Sola @ IRI-UPC-CSIC,\n% SLAMTB is Copyright 2009 \n% by Joan Sola, Teresa Vidal-Calleja, David Marquez and Jean Marie Codol\n% @ LAAS-CNRS.\n% See on top of this file for its particular copyright.\n\n% # END GPL LICENSE\n\n", "meta": {"author": "joansola", "repo": "slamtb", "sha": "b4767f6bf38bceed205abb85f1aed12422c9a972", "save_path": "github-repos/MATLAB/joansola-slamtb", "path": "github-repos/MATLAB/joansola-slamtb/slamtb-b4767f6bf38bceed205abb85f1aed12422c9a972/InterfaceLevel/reparametrizeLmk.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7279754489059775, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.34693828542253363}} {"text": "%%***************************************************************************\n%% steplength: compute xstep such that X + xstep*dX >= 0.\n%%\n%% [xstep] = steplength(blk,X,dX,Xchol,invXchol);\n%%\n%% SDPT3: version 3.1\n%% Copyright (c) 1997 by\n%% K.C. Toh, M.J. Todd, R.H. Tutuncu\n%% Last Modified: 16 Sep 2004\n%%***************************************************************************\n\n function [xstep,invXchol] = steplength(blk,X,dX,Xchol,invXchol);\n\n%%\n for p = 1:size(blk,1)\n pblk = blk(p,:); \n numblk = length(pblk{2}); \n pblksize = sum(pblk{2});\n if (any(isnan(dX{p})) | any(isinf(dX{p}))); xstep = 0; break; end; \n if strcmp(pblk{1},'s') \n if (max(pblk{2}) >= 200) \n use_lanczos = 1; \n else\n use_lanczos = 0; \n end \n if (use_lanczos)\n tol = 1e-3; \n maxit = max(min(pblksize,30),round(sqrt(pblksize))); \n [lam,delta,res] = lanczosfun(Xchol{p},-dX{p},maxit,tol);\n %%\n %% Note: lam <= actual largest eigenvalue <= lam + delta.\n %% \n\t d = lam+delta; \n else\n if isempty(invXchol{p}); \n invXchol{p} = inv(Xchol{p}); \n end\n\t tmp = Prod2(pblk,dX{p},invXchol{p},0); \n M = Prod2(pblk,invXchol{p}',tmp,1); \n if (exist('mexblkeig')==3)\n d = mexblkeig(pblk,-M); \n else\n d = blkeig(pblk,-M); \n end\n end\n tmp = max(d) + 1e-15*max(abs(d)); \n if (tmp > 0); \n xstep(p) = 1/max(tmp);\n else \n xstep(p) = 1e12; \n end\n elseif strcmp(pblk{1},'q')\n aa = qops(pblk,dX{p},dX{p},2); \n bb = qops(pblk,dX{p},X{p},2); \n cc = qops(pblk,X{p},X{p},2);\n dd = bb.*bb - aa.*cc; \n tmp = min(aa,bb); \n idx = find(dd > 0 & tmp < 0); \n steptmp = 1e12*ones(numblk,1); \n if ~isempty(idx)\n steptmp(idx) = -(bb(idx)+sqrt(dd(idx)))./aa(idx); \n end\n idx = find(abs(aa) < eps & bb < 0); \n if ~isempty(idx)\n steptmp(idx) = -cc(idx)./(2*bb(idx)); \n end\n %%\n %% also need first component to be non-negative\n %%\n ss = 1 + [0, cumsum(pblk{2})];\n ss = ss(1:length(pblk{2})); \n dX0 = dX{p}(ss); \n X0 = X{p}(ss); \n idx = find(dX0 < 0 & X0 > 0); \n if ~isempty(idx)\n steptmp(idx) = min(steptmp(idx),-X0(idx)./dX0(idx)); \n end\n xstep(p) = min(steptmp); \n elseif strcmp(pblk{1},'l')\n idx = find(dX{p} < 0); \n if ~isempty(idx)\n xstep(p) = min(-X{p}(idx)./dX{p}(idx)); \n else \n xstep(p) = 1e12;\n end\n elseif strcmp(pblk{1},'u')\n xstep(p) = 1e12; \n end\n end\n xstep = min(xstep); \n%%***************************************************************************\n%%***************************************************************************\n%% lanczos: find the largest eigenvalue of \n%% invXchol'*dX*invXchol via the lanczos iteration.\n%%\n%% [lam,delta] = lanczosfun(Xchol,dX,maxit,tol,v)\n%%\n%% lam: an estimate of the largest eigenvalue.\n%% lam2: an estimate of the second largest eigenvalue.\n%% res: residual norm of the largest eigen-pair.\n%% res2: residual norm of the second largest eigen-pair.\n%%***************************************************************************\n\n function [lam,delta,res] = lanczosfun(Xchol,dX,maxit,tol,v) \n \n if (norm(dX,'fro') < 1e-13) \n lam = 0; delta = 0; res = 0; \n return;\n end\n n = length(dX); \n if (nargin < 5); \n state = randn('state'); \n randn('state',0); \n v = randn(n,1); \n randn('state',state); \n end\n if (nargin < 4); tol = 1e-3; end\n if (nargin < 3); maxit = 30; end\n V = zeros(n,maxit+1); H = zeros(maxit+1,maxit); \n v = v/norm(v); \n V(:,1) = v; \n if issparse(Xchol); Xcholtransp = Xchol'; end\n%%\n%% lanczos iteration. \n%%\n for k = 1:maxit\n if issparse(Xchol)\n w = dX*mextriangsp(Xcholtransp,v,1); \n w = mextriangsp(Xchol,w,2); \n else \n w = dX*mextriang(Xchol,v,1); \n w = mextriang(Xchol,w,2); \n end \n wold = w;\n if (k > 1); \n w = w - H(k,k-1)*V(:,k-1); \n end;\n alp = w'*V(:,k); \n w = w - alp*V(:,k); \n H(k,k) = alp; \n %%\n %% one step of iterative refinement if necessary. \n %%\n if (norm(w) <= 0.8*norm(wold));\n s = (w'*V(:,1:k))'; \n w = w - V(:,1:k)*s;\n H(1:k,k) = H(1:k,k) + s;\n end; \n nrm = norm(w); \n v = w/nrm; \n V(:,k+1) = v; \n H(k+1,k) = nrm; H(k,k+1) = nrm; \n %%\n %% compute ritz pairs and test for convergence\n %%\n if (rem(k,5) == 0) | (k == maxit); \n Hk = H(1:k,1:k); Hk = 0.5*(Hk+Hk'); \n [Y,D] = eig(Hk); \n eigH = real(diag(D)); \n [dummy,idx] = sort(eigH);\n res_est = abs(H(k+1,k)*Y(k,idx(k)));\n if (res_est <= 0.1*tol) | (k == maxit);\n lam = eigH(idx(k)); \n lam2 = eigH(idx(k-1)); \n z = V(:,1:k)*Y(:,idx(k));\n z2 = V(:,1:k)*Y(:,idx(k-1));\n if issparse(Xchol) \n tmp = dX*mextriangsp(Xcholtransp,z,1); \n res = norm(mextriangsp(Xchol,tmp,2) -lam*z); \n tmp = dX*mextriangsp(Xcholtransp,z2,1); \n res2 = norm(mextriangsp(Xchol,tmp,2) -lam*z2); \n else\n tmp = dX*mextriang(Xchol,z,1); \n res = norm(mextriang(Xchol,tmp,2) -lam*z); \n tmp = dX*mextriang(Xchol,z2,1); \n res2 = norm(mextriang(Xchol,tmp,2) -lam*z2); \n end\n tmp = lam-lam2 -res2; \n if (tmp > 0); beta = tmp; else; beta = eps; end; \n delta = min(res,res^2/beta); \n if (delta <= tol); break; end;\n end \n end \n end\n%%***************************************************************************\n", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/dependencies/cvx-1.21.b795/sdpt3/Solver/steplength.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.746138993030751, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.3468811903229539}} {"text": "% THIS SOFTWARE AND ANY ACCOMPANYING DOCUMENTATION IS RELEASED \"AS IS.\" THE U.S. GOVERNMENT MAKES NO WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, CONCERNING THIS SOFTWARE AND ANY ACCOMPANYING DOCUMENTATION, INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT WILL THE U.S. GOVERNMENT BE LIABLE FOR ANY DAMAGES, INCLUDING ANY LOST PROFITS, LOST SAVINGS OR OTHER INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE, OR INABILITY TO USE, THIS SOFTWARE OR ANY ACCOMPANYING DOCUMENTATION, EVEN IF INFORMED IN ADVANCE OF THE POSSIBILITY OF SUCH DAMAGES.\n%\n% integrate_poisspdf.m\n% integrates a poisson pdf with respect to lambda from a to b\n%\n% 022300 tdr created\n% 030400 tdr replaced global variable approach to getting x and n to binopdf.\n% 030600 tdr added adjustments to a and b to help quad8 converge quickly.\n% \t\t\tquad8 has trouble with long stretches of near-zero values\n% \t\t\tso we try to bound the interval to avoid these regions\n% 031600 tdr created integrate_poisspdf.m from integrate_binopdf.m\n% 012901 tdr changed quad8 to quadl per MatLab 6 recommendation. Turned off warnings\n% for quadl call because it thinks intervals starting at zero or ending at one \n% involve singularities and generates a warning, although accuracy is okay.\n% 031501 tdr changed thres2 from 0.001 to 1.\n\nfunction y = integrate_poisspdf(x,a,b)\n\nif nargin ~= 3, \n error('Requires three input arguments (x,a,b)');\nend\n\nTRACE = 0;\nlambda_hat = x;\nthres = 1e-6*poisspdf_0ok(x,x); % pdf values less than this are assumed to be negligible.\nthres2 = 1; % resolution of adjustments to a and b.\ntiny_a = (poisspdf_0ok(x,a) < thres);\ntiny_b = (poisspdf_0ok(x,b) < thres);\n\nif tiny_a & tiny_b & (a > lambda_hat | b < lambda_hat),\n\t%both a and b give results near zero, with no non-zero values between them\n y = 0;\n return\nend;\n\n% defaults\nnew_a = a;\nnew_b = b;\n\nif tiny_a,\n\t% a needs to be increased, but not past b or lambda_hat\n\tll = a; ul = min(b, lambda_hat);\n while (abs(ll - ul) > thres2),\n \ttest = (ll + ul)/2;\n if poisspdf_0ok(x,test) < thres,\n \tll = test;\n else\n \tul = test;\n end;\n end;\n\tnew_a = ll; \nend;\n\nif tiny_b,\n\t% b needs to be decreased, but not past a or lambda_hat\n\tll = max(a, lambda_hat); ul = b;\n while (abs(ll - ul) > thres2),\n \ttest = (ll + ul)/2;\n if poisspdf_0ok(x,test) < thres,\n \tul = test;\n else\n \tll = test;\n end;\n end;\n\tnew_b = ul; \nend;\n\n% call quad with increased a\n% quadl thinks interval starting at zero or ending at one might involve \n% a singularity and produces a warning, despite being accurate.\nwarning off; \ny=quadl('poisspdf_of_lambda',new_a,new_b,[],TRACE,x);\nwarning on;\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/3031-accurate-confidence-intervals/ci_tool/integrate_poisspdf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.3467699116908309}} {"text": "function VoigtSpectrGUI\n%this is a GUI program i wrote about simulating absorption lineshape and \n%spectrum from HITRAN output data \n% this program simulate the spectrum using the HITRAN data and \n% Calculating the Voigt porfile According to the paper: \n% Applied spectro. V58, 468(2004);\n% Phi= A*K(x,y) \n% The lineshape depends on Guassian (vD) width and Lorentzian width(vL). \n% Absorption depends on number density and absorption length, I/I0 = Exp(-aNL);\n% Notice the Half Width at Half Maxium for the vD and vL inputs;\n\n fh = figure('Visible','off','Name','Spectrum Simulation',...\n 'position',[50,50, 850, 600]);\n \n hax = axes('Units','pixels','Position',[60,60,500,500]);\n \n %construct the components\n hp = uipanel('Units','pixels','ShadowColor',[0.1,1,0.01],...\n 'Position',[628 160 200 430]);\n \n \n hpb1 = uicontrol('Style','pushbutton','String','Open HITRFile',...\n 'Foregroundcolor',[1 0.1 0.2],'FontWeight','bold',...\n 'Position',[650 540, 110, 30],'Callback',{@fileopen_Callback});\n \n het1 = uicontrol('Style','edit','String','file name',...\n 'Foregroundcolor',[0.2 0.4 0.1],'FontWeight','bold',...\n 'Position',[650,510,110,30],'Callback',{@edittext_Callback});\n \n hst1 = uicontrol('Style','text', 'String','HWHM[vD vL]/cm-1',...\n 'Foregroundcolor',[0.2 0.3 0.3],'FontWeight','bold',...\n 'Backgroundcolor',[0.7 0.98 0.98],...\n 'Position', [650 470 160 15]);\n \n het2 = uicontrol('Style','edit', 'String','0.003',...\n 'Foregroundcolor',[0.30 0.1 1],'FontWeight','bold',...\n 'Backgroundcolor',[0.97842 0.98 1],...\n 'Position', [650 445 75 20]); \n \n het3 = uicontrol('Style','edit', 'String','0.006',...\n 'Foregroundcolor',[0.30 0.1 1],'FontWeight','bold',...\n 'Backgroundcolor',[1 0.99 1],...\n 'Position', [735 445 75 20]); \n\n \n hst2 = uicontrol('Style','text', 'String','NumDensity/Lightpath/cm',...\n 'Foregroundcolor',[0.2 0.3 0.3],'FontWeight','bold',...\n 'Backgroundcolor',[0.7 0.98 1],...\n 'Position', [650 410 160 15]);\n \n het4 = uicontrol('Style','edit', 'String','1E+10',...\n 'Foregroundcolor',[0.30 0.1 1],'FontWeight','bold',...\n 'Backgroundcolor',[0.97842 0.98 1],...\n 'Position', [650 385 75 20]); \n \n het5 = uicontrol('Style','edit', 'String','1E+5',...\n 'Foregroundcolor',[0.30 0.1 1],'FontWeight','bold',...\n 'Backgroundcolor',[1 0.99 1],...\n 'Position', [735 385 75 20]); \n \n hpb2 = uicontrol('Style','pushbutton','String','Simu-LineShape',... \n 'Foregroundcolor',[1 0.1 0.2],'FontWeight','bold',...\n 'Position',[650 340, 110, 30],'Callback',{@SimuLS_Callback}); \n \n het6 = uicontrol('Style','edit', 'String','VoigtWidth',...\n 'Foregroundcolor',[0.30 0.1 1],'FontWeight','bold',...\n 'Backgroundcolor',[0.4 0.9 0.7],...\n 'Position', [735 315 75 20]); \n \n hpb3 = uicontrol('Style','pushbutton','String','Simu-Absorption',... \n 'Foregroundcolor',[1 0.1 0.2],'FontWeight','bold',...\n 'Position',[650 280, 110, 30],'Callback',{@SimuAp_Callback}); \n \n hpb4 = uicontrol('Style','pushbutton','String','Open ExpSpec',... \n 'Foregroundcolor',[1 0.1 0.2],'FontWeight','bold',...\n 'Position',[650 240, 110, 30],'Callback',{@ExpSpectr_Callback});\n \n \n hst4 = uicontrol('Style','text', 'String','Display Options',... \n 'Backgroundcolor',[0.678402 0.98 1],...\n 'Foregroundcolor',[0.2 0.3 0.3],'FontWeight','bold',...\n 'Position',[650 210 130 15]); \n\n\n hpm = uicontrol('Style','popupmenu',...\n 'String',{'LineShape','Absorption','CombinedPlot'},...\n 'Foregroundcolor',[0.99 0.01 0.01],'FontWeight','bold',...\n 'Value',1,'Position',[690 170 110 30],'Callback',{@popup_Callback}); \n \n \n hp2 = uipanel('Units','pixels','ShadowColor',[0.1 0.1 1],...\n 'Position',[628 40 200 100]); \n \n \n het7 = uicontrol('Style','edit','String','FileName.dat',...\n 'Foregroundcolor',[0.2 0.4 0.1],'FontWeight','bold',...\n 'Position',[640,105,90,25]); \n \n hcb1 = uicontrol('Style','checkbox','String','Line Shape',...\n 'Position',[655 75 85 25],'Foregroundcolor',[0.2 0.3 0.9]);\n hcb2 = uicontrol('Style','checkbox','String','Absorption',...\n 'Position',[655 50 85 25],'Foregroundcolor',[0.2 0.3 0.9]);\n \n hpb5 = uicontrol('Style','pushbutton','String','Save',... \n 'Foregroundcolor',[0.6 0.2 0.3],'FontWeight','bold',...\n 'Position',[750 66, 60, 50],'Callback',{@save_Callback});\n \n % to align the controls\n align([hp,het1,het6,hpb1,hpb2,hpb3,hpb4,hst1,hst2,hst4,hpm,hp2],'Center','None');\n\n % Initialize the GUI.\n % Change units to normalized so components resize automatically.\n set([hp,het1,het2,het3,het4,het5,het6,het7,hpb1,hpb2,hax,hst1,hst2,...\n hst4,hpm,hpb3,hpb4,hp2,hcb1,hcb2,hpb5],'Units','normalized');\n \n %make figure visible.\n set(fh, 'Visible','on');\n set(fh, 'NumberTitle','off')%% supress the NumverTitle\n \n % define some variables\n format long e ; %% define numerical format\n stp=0.0002; %% calculation(convolution) stepsize \n Dd = 0.5; %% define the edge extended beyond the spectrum region\n Nd = 1E+10; %% Number density\n L = 1E+5; %% Optical path length cm\n \n gL = 0.001; %% in cm -1, pressure broadening cofffient at 50 torr.\n gD = 0.003; %% 0.0032 doppler broadening in cm-1\n SgmvTot= zeros(1,10); %% initiate the arrays\n expx = zeros(1,10); \n expy = zeros(1,10);\n A = zeros(1,10);\n dtfl = zeros(1,10);\n grd = zeros(1,10); %% default grid\n \n %%file open callback\n function fileopen_Callback(source,eventdata)\n % **********uiputfile for open the save file dialog*********\n \n [flnm, flpth] = uigetfile({'*.out','All Files' },...\n 'Select HITRAN outputfile','fl.out');\n %specify application data, so it can be used by other objects;\n % setappdata(h,'name',value) \n setappdata(hpb1,'fname',flnm);\n \n set(het1, 'String',flnm);\n % set the edit text box value.\n \n end\n \n % read in the HITRAN data and simulate Line Shape spectrum\n function SimuLS_Callback(source, eventdata)%callback is just a regular func\n \n format long e ;\n % get the value of specified data\n % value = getappdata(h,name)\n % values = getappdata(h)\n flnm = getappdata(hpb1,'fname');\n \n fid = fopen(flnm);\n C = textscan(fid,...\n '%d%f%f%u%f%f%f%f %d%d%d%d%d %d%d%d%d %d%d%d%d %d%d%d%d%d%d%d%d%d%d%d%d%d ');\n fclose(fid); %% returned C is a cell \n \n N = length(C{2}); %% Number of lines/ Cell length\n %% define a grid\n rangeL= -Dd + min(C{2}); %% spectrum region: First line minus 1 cm-1\n rangeH = Dd + max(C{2}); %% Last line position + 1 cm-1\n grd=[rangeL:stp:rangeH]; %% define the grid\n \n v = grd;\n gD = str2num(get(het2, 'string'));\n gL = str2num(get(het3, 'string'));\n gV = 0.5346*gL + sqrt(0.2166*gL^2 + gD^2); %% Voigt profile half width\n x = gL/gV;\n SgmvTot = 0;\n \n for i=1:N %% calculate the line shape for each peak\n \n v0(i) = C{2}(i);\n S(i) = C{3}(i);\n y = abs(v-v0(i))/gV;\n Sgmv0(i) = S(i)/(2*gV*(1.065 + 0.447*x + 0.058*x^2));\n Sgmv = Sgmv0(i)*((1-x)*exp(-0.693.*y.^2) + (x./(1+y.^2)) + ...\n 0.016*(1-x)*x*(exp(-0.0841.*y.^2.25)-1./(1 + 0.021.*y.^2.25)));\n \n SgmvTot = SgmvTot + Sgmv; \n \n end\n\n plot(grd,SgmvTot,'-b.');\n xlabel('WaveLength in cm-1');\n ylabel('Effective absorption Cross Section in cm2');\n \n set(hpm, 'Value',1)% change the popup menu settings;\n \n %% display the Voigt width;\n strg = sprintf('gV= %1.4f',gV);\n set(het6,'string',strg);\n set(het6,'Backgroundcolor',[0.9 0.9 0.9])\n\n %%figure, plot(v,A);\n %%ylabel('Absorption')\n end\n \n\n function SimuAp_Callback(source, eventdata) \n %% calculate absorption\n \n Nd = str2num(get(het4, 'string')); %% Number density in molecule/cm3\n L = str2num(get(het5, 'string')); %% effective length path in cm\n A = 1 - exp(-SgmvTot.*Nd*L); %% I/I0 = Exp(-aNL);\n \n plot(grd,A,'-m');\n xlabel('WaveLength in cm-1'); \n set(hpm, 'Value',2)% change the popup menu settings;\n \n end\n\n\n %slice X callback\n function ExpSpectr_Callback(source, eventdata)\n \n format long e ;\n [flnm, flpth] = uigetfile({'*.dat','All Files' },'Select Exp. file','ExpSpectr.dat');\n fid = fopen(flnm, 'r');\n a = fscanf(fid, '%f %f', [2 inf]); % It has two rows now.\n a = a';\n fclose(fid)\n expx = a(:,1);\n expy = a(:,2);\n hold on;\n plot3 = plot(expx,expy,'-.b');\n ylabel('Absorption')\n \n hold off;\n \n end\n\n\n %popup menu callback\n function popup_Callback(source,eventdata)\n str = get(source, 'String');\n val = get(hpm, 'Value'); %use either function handle 'hpm' or 'source';\n % the string of popup menu is a cell array {}, cell{num} returns num th\n % element of the cell.\n switch val\n case 1 %'showImage' \n %disp(str{val});\n hold off;\n plot(grd,SgmvTot,'-b.');\n xlabel('WaveLength in cm-1')\n ylabel('Effective absorption Cross Section in cm2')\n \n case 2 \n hold off;\n plot(grd,A,'-m');\n \n case 3 %combined plot\n hold on;\n plot(expx,expy,'-.b');\n ylabel('Absorption')\n \n hold off;\n \n end\n end\n \n\n function save_Callback(source, eventdata)\n \n if get(hcb1,'Value')> 0.9 % it should be 1.0 \n dtfl = [grd;SgmvTot]; %% create a data matrix for data saving\n fid = fopen(get(het7, 'string'), 'wt');\n fprintf(fid, '%6.4f %e\\n', dtfl); %% set the data format\n fclose(fid);\n \n end\n \n if get(hcb2,'Value')> 0.9 % it should be 1.0 \n \n dtfl = [grd;A]; %% create a data matrix for data saving\n fid = fopen(get(het7, 'string'), 'wt');\n fprintf(fid, '%6.4f %5.6f\\n', dtfl); %% set the data format\n fclose(fid); \n end \n \n if get(hcb1,'Value')> 0.9 && get(hcb2,'Value')> 0.9 % it should be 1.0 \n \n dtfl = [grd;SgmvTot;A]; %% create a data matrix for data saving\n \n fid = fopen(get(het7, 'string'), 'wt');\n fprintf(fid, '%6.4f %e %5.6f\\n', dtfl); %% set the data format\n fclose(fid);\n \n end\n end\n\n%%% read in the HITRAN file to obtain line positions and intensities.\nend\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/26707-voigt-lineshape-spectrum-simulation-gui/VoigtSpectrGUI.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6297745935070806, "lm_q2_score": 0.5506073655352403, "lm_q1q2_score": 0.3467585298119605}} {"text": "function jac = autoJac(fun,x0,varargin)\n%AUTOJAC Returns a Automatically Differentiated (AD) Jacobian\n% \n% jac = autoJac(fun,x0) uses the user supplied Matlab function to\n% generate the Jacobian using automatic differentiation. The user\n% function must be a Matlab function and must not call external code or\n% class / toolbox functions. If your function breaks any of these\n% conditions consider using mklJac instead.\n%\n% The underlying AD algorithm is adiff by William McIlhagga and its\n% documentation pdf is provided in the Differentiation folder. See the\n% BSD license below the code.\n\n% Copyright (C) 2011 Jonathan Currie (I2C2)\n\nif(~isa(fun,'function_handle'))\n error('Fun should be a function handle!');\nend\n\n[~,jac] = adiffget(fun(adiff(x0),varargin{:}));\n\nend\n\n% Copyright (c) 2010, William McIlhagga\n% All rights reserved.\n% \n% Redistribution and use in source and binary forms, with or without \n% modification, are permitted provided that the following conditions are \n% met:\n% \n% * Redistributions of source code must retain the above copyright \n% notice, this list of conditions and the following disclaimer.\n% * Redistributions in binary form must reproduce the above copyright \n% notice, this list of conditions and the following disclaimer in \n% the documentation and/or other materials provided with the distribution\n% \n% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" \n% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE \n% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE \n% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE \n% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR \n% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF \n% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS \n% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN \n% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) \n% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE \n% POSSIBILITY OF SUCH DAMAGE.\n", "meta": {"author": "vigente", "repo": "gerardus", "sha": "4d7c5195b826967781f1bb967872410e66b7cd3d", "save_path": "github-repos/MATLAB/vigente-gerardus", "path": "github-repos/MATLAB/vigente-gerardus/gerardus-4d7c5195b826967781f1bb967872410e66b7cd3d/matlab/ThirdPartyToolbox/OptiToolbox/Utilities/Differentiation/Automatic/autoJac.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6001883735630721, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.34660600397108476}} {"text": "% std_stat() - compute statistics for ERP/spectral traces or ERSP/ITC images\n% of a component or channel cluster in a STUDY. \n% Usage:\n% >> std_stat( data, 'key', 'val', ...)\n% Inputs:\n% data - [cell array] mean data for each subject group and/or data\n% condition. For example, to compute mean ERPs statistics from a \n% STUDY for epochs of 800 frames in two conditions from three \n% groups of 12 subjects:\n%\n% >> data = { [800x12] [800x12] [800x12];... % 3 groups, cond 1\n% [800x12] [800x12] [800x12] }; % 3 groups, cond 2\n% >> pcond = std_stat(data, 'condstats', 'on');\n%\n% By default, parametric statistics are computed across subjects \n% in the three groups. See below and >> help statcond \n% for more information about the statistical computations.\n%\n% Statistics options:\n% 'groupstats' - ['on'|'off'] Compute (or not) statistics across groups.\n% {default: 'off'}\n% 'condstats' - ['on'|'off'] Compute (or not) statistics across groups.\n% {default: 'off'}\n% 'statistics' - ['param'|'perm'] Type of statistics to use: 'param' for\n% parametric; 'perm' for permutations {default: 'param'}\n% 'naccu' - [integer] Number of surrogate averges fo accumulate when \n% computing permutation-based statistics. For example, to\n% test p<0.01 use naccu>=200; for p<0.001, use naccu>=2000. \n% If a non-NaN 'threshold' is set (see below) and 'naccu' \n% is too low, it will be automatically increased. This \n% keyword available only from the command line {default:500}\n% 'threshold' - [NaN|p-value] threshold for computing p-value. In this \n% function, it is only used to compute naccu above. NaN\n% means that no threshold has been set. \n% 'mcorrect' - ['none'|'fdr'] apply correcting for multiple comparisons.\n%\n% Outputs:\n% pcond - [cell] condition pvalues or mask (0 or 1). One element per group.\n% pgroup - [cell] group pvalues or mask (0 or 1). One element per condition.\n% pinter - [cell] three elements, condition pvalues (group pooled),\n% group pvalues (condition pooled) and interaction pvalues.\n%\n% Author: Arnaud Delorme, CERCO, CNRS, 2006-\n% \n% See also: statcond()\n\n% 'statmode' - ['subjects'|'trials'] standard statistics are \n% 'subjects' where the statistics is performed accross\n% the mean ERSP (or ITC) of single subjects. For 'trials'\n% statistics, the single-trial data epochs of all subjects\n% are pooled together. This requires that they were\n% saved on disk using option 'savetrials', 'on' at the time\n% of computation. Note that these single-trial data\n% may use several GB of disk space and that computation \n% of 'trials' statistics requires a lot of RAM.\n\nfunction [pcond, pgroup, pinter] = std_stat(data, varargin)\n\npgroup = {};\npcond = {};\npinter = {};\nif nargin < 1\n help std_stat;\n return;\nend;\n\n% decode inputs\n% -------------\nopt = {};\nif nargin > 1\n if isstruct(varargin{1})\n g = struct(varargin{2:end});\n if isfield(g, 'condstats'), varargin{1} = rmfield(varargin{1}, 'condstats'); end;\n if isfield(g, 'groupstats'), varargin{1} = rmfield(varargin{1}, 'groupstats'); end;\n tmpparams = fieldnames(varargin{1}); tmpparams = tmpparams';\n tmpparams(2,:) = struct2cell(varargin{1});\n varargin = { tmpparams{:} varargin{2:end} };\n end;\nend;\nopt = finputcheck( varargin, { 'threshold' 'real' [] NaN;\n 'mcorrect' 'string' { 'none' 'fdr' } 'none';\n 'naccu' 'integer' [] [];\n 'groupstats' 'string' { 'on' 'off' } 'off';\n 'paired' 'cell' { 'on' 'off' } { 'on' 'on' };\n 'condstats' 'string' { 'on' 'off' } 'off';\n 'statistics' 'string' { 'param' 'perm' 'bootstrap' } 'param' }, ...\n 'std_stat', 'ignore');\n\nif isstr(opt), error(opt); end;\nif ~isnan(opt.threshold(1)) && isempty(opt.naccu), opt.naccu = 1/opt.threshold(end)*2; end;\nif any(any(cellfun('size', data, 2)==1)), opt.groupstats = 'off'; opt.condstats = 'off'; end;\nif strcmpi(opt.mcorrect, 'fdr'), opt.naccu = opt.naccu*20; end;\nif isempty(opt.naccu), opt.naccu = 2000; end;\nif strcmpi(opt.statistics, 'param') && ~isreal(data{1})\n fprintf('*** Cannot use parametric statistics for single-trial ITC significance ***\\n');\n return;\nend;\nnc = size(data,1);\nng = size(data,2);\n\n% compute significance mask\n% --------------------------\nif strcmpi(opt.condstats, 'on') && nc > 1\n for g = 1:ng\n [F df pval] = statcond(data(:,g), 'mode', opt.statistics, 'naccu', opt.naccu, 'paired', opt.paired{1}); \n pcond{g} = squeeze(pval);\n end;\nelse\n pcond = {};\nend;\nif strcmpi(opt.groupstats, 'on') && ng > 1\n for c = 1:nc\n [F df pval] = statcond(data(c,:), 'mode', opt.statistics, 'naccu', opt.naccu, 'paired', opt.paired{2}); \n pgroup{c} = squeeze(pval);\n end;\nelse\n pgroup = {};\nend;\nif ( strcmpi(opt.groupstats, 'on') && strcmpi(opt.condstats, 'on') ) & ng > 1 & nc > 1\n opt.paired = sort(opt.paired); % put 'off' first if present\n [F df pval] = statcond(data, 'mode', opt.statistics, 'naccu', opt.naccu, 'paired', opt.paired{1});\n for index = 1:length(pval)\n pinter{index} = squeeze(pval{index});\n end;\nelse\n pinter = {};\nend;\n\nif ~isempty(opt.groupstats) || ~isempty(opt.condstats) \n if strcmpi(opt.mcorrect, 'fdr'), \n disp('Applying FDR correction for multiple comparisons');\n for ind = 1:length(pcond), pcond{ind} = fdr( pcond{ind} ); end;\n for ind = 1:length(pgroup), pgroup{ind} = fdr( pgroup{ind} ); end;\n if ~isempty(pinter), \n pinter{1} = fdr(pinter{1}); \n pinter{2} = fdr(pinter{2}); \n pinter{3} = fdr(pinter{3}); \n end;\n end;\n if ~isnan(opt.threshold)\n for ind = 1:length(pcond), pcond{ind} = applythreshold(pcond{ind}, opt.threshold); end;\n for ind = 1:length(pgroup), pgroup{ind} = applythreshold(pgroup{ind}, opt.threshold); end;\n for ind = 1:length(pinter), pinter{ind} = applythreshold(pinter{ind}, opt.threshold); end;\n end;\nend;\n\nfunction newdata = applythreshold(data, threshold)\n threshold = sort(threshold);\n newdata = zeros(size(data));\n for index = 1:length(threshold)\n inds = data < threshold(index);\n data(inds) = 1;\n newdata(inds) = length(threshold)-index+1;\n end;\n \n", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/PR_BCI_team/Team_EarEEG/ear-EEG connecting/external/eeglab_10_0_1_0x/functions/studyfunc/std_stat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.34620226997429693}} {"text": "2*((x - x2)*((x - x1)^2 + (y - y1)^2)*(-r12^2 + (r11 -\n ((x - x1)^2 + (y - y1)^2)^(1/2))^2 + (z - z1)^2)*(-r22^2 + (y - \n y2)^2 + (r21 - ((x - x2)^2 + (z - z2)^2)^(1/2))^2) + (x - \n x2)*((x - x1)^2 + (y - y1)^2)*(-r12^2 + (r11 - \n ((x - x1)^2 + (y - y1)^2)^(1/2))^2 + (z - z1)^2)*(-r21 + \n ((x - x2)^2 + (z - z2)^2)^(1/2))*((x - x2)^2 + (z - \n z2)^2)^(1/2) + (x - x1)*(-r11 + \n ((x - x1)^2 + (y - y1)^2)^(1/2))*((x - x1)^2 + (y - \n y1)^2)^(1/2)*(-r22^2 + (y - y2)^2 + (r21 - \n ((x - x2)^2 + (z - z2)^2)^(1/2))^2)*((x - x2)^2 + (z - \n z2)^2) + (x - x1)*(-r12^2 + (r11 - ((x - x1)^2 + (y - y1)^2)^(1/2))^2 +\n (z - z1)^2)*(-r22^2 + (y - y2)^2 + (r21 - \n ((x - x2)^2 + (z - z2)^2)^(1/2))^(2))*((x - x2)^2 + (z - z2)^2));\n\n\n2*(((x - x1)^2 + (y - y1)^2)*(y - \n y2)*(-r12^2 + (r11 - ((x - x1)^2 + (y - y1)^2)^(1/2))^2 +\n (z - z1)^2) + (-r11 + ((x - x1)^2 + (y - y1)^2)^(1/2))*\n ((x - x1)^2 + (y - y1)^2)^(1/2)*(y - y1)*(-r22^2 +\n (y - y2)^2 + (r21 - ((x - x2)^2 + (z - z2)^2)^(1/2))^2) +\n (y - y1)*(-r12^2 + (r11 - ((x - x1)^2 + (y - y1)^2)^(1/2))^2 +\n (z - z1)^2)*(-r22^2 + (y - y2)^2 + (r21 - \n ((x - x2)^2 + (z - z2)^2)^(1/2))^2))*((x - x2)^2 + (z - z2)^2);\n\n2*((x - x1)^2 + (y - y1)^2)*((z - z1)*(-r22^2 + (y - y2)^2 +\n (r21 - ((x - x2)^2 + (z - z2)^2)^(1/2))^2)*((x - x2)^2 +\n (z - z2)^2) + (-r12^2 + (r11 - ((x - x1)^2 + (y - y1)^2)^(1/2))^2 +\n (z - z1)^2)*(-r22^2 + (y - y2)^2 + (r21 - ((x - x2)^2 + (z - z2)^2)^(1/2))^2)*\n (z - z2) + (-r12^2 + (r11 - ((x - x1)^2 + (y - y1)^2)^(1/2))^2+ \n (z - z1)^2)*(-r21 + ((x - x2)^2 + (z - z2)^2)^(1/2))*\n ((x - x2)^2 + (z - z2)^2)^(1/2)*(z - z2));", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/research/IVEM/ExampleFun/TextFD.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.34592666006271156}} {"text": "function [g1, g2] = simXsimKernDiagGradient(simKern1, simKern2, t, covDiag)\n\n% SIMXSIMKERNDIAGGRADIENT Gradient for the diagonal between two SIM kernels.\n% FORMAT\n% DESC computes cross gradient of parameters in the diagonal of a cross \n% kernel between two sim kernels for the multiple output kernel. \n% ARG simKern1 : the kernel structure associated with the first SIM\n% kernel.\n% ARG simKern2 : the kernel structure associated with the second SIM\n% kernel.\n% ARG t : inputs for which kernel is to be computed.\n% ARG covDiag : gradient of the objective function with respect to\n% the elements of the cross kernel matrix.\n% RETURN g1 : gradient of the parameters of the first kernel, for\n% ordering see simKernExtractParam.\n% RETURN g2 : gradient of the parameters of the second kernel, for\n% ordering see simKernExtractParam.\n%\n% SEEALSO : simXsimKernDiagCompute.m, simKernParamInit, simKernExtractParam\n%\n% COPYRIGHT : Mauricio A. Alvarez, 2010\n\n% KERN\n\n\nif size(t, 2) > 1\n error('Input can only have one column');\nend\n\nif simKern1.inverseWidth ~= simKern2.inverseWidth\n error('Kernels cannot be cross combined if they have different inverse widths.')\nend\n% The normalisation in the SIM kernel arises from the use of the normalised\n% version of the RBF kernel. Hence, both have to be normalised or not.\nif ~isfield(simKern1, 'isNormalised')\n isSim1Normalised = false;\nelse\n isSim1Normalised = simKern1.isNormalised;\nend\nif ~isfield(simKern2, 'isNormalised')\n isSim2Normalised = false;\nelse\n isSim2Normalised = simKern2.isNormalised;\nend\nif isSim1Normalised ~= isSim2Normalised\n error('Both SIM kernels have to be either normalised or not.');\nend\n\nsigma = sqrt(2/simKern1.inverseWidth);\n\nif (~simKern1.isStationary || ~ simKern2.isStationary)\n [h1, dh1_dD1, dh1_dD2, dh1_dsigma] = ...\n simXsimComputeDiagH(t, simKern1.decay, simKern2.decay, simKern1.delay, simKern2.delay, sigma);\nelse\n [h1, dh1_dD1, dh1_dD2, dh1_dsigma] = ...\n simXsimComputeDiagHStat(t, simKern1.decay, simKern2.decay, simKern1.delay, simKern2.delay, sigma);\nend\n\n% Avoid making the expensive call twice unless really necessary\nif ((simKern1.decay == simKern2.decay) && (simKern1.delay == simKern2.delay)),\n h2 = h1;\n dh2_dD2 = dh1_dD1;\n dh2_dD1 = dh1_dD2;\n dh2_dsigma = dh1_dsigma;\nelseif (~simKern1.isStationary) || (~simKern2.isStationary)\n [h2, dh2_dD2, dh2_dD1, dh2_dsigma] = ...\n simXsimComputeDiagH(t, simKern2.decay, simKern1.decay, simKern2.delay, simKern1.delay, sigma);\nelse\n [h2, dh2_dD2, dh2_dD1, dh2_dsigma] = ...\n simXsimComputeDiagHStat(t, simKern2.decay, simKern1.decay, simKern2.delay, simKern1.delay, sigma);\nend\n\ndK_dsigma = dh1_dsigma + dh2_dsigma;\n\n\nif isfield(simKern1, 'isVarS') && (simKern1.isVarS)\n K = 0.5 * (h1 + h2);\n if ~isSim1Normalised\n K = sqrt(pi) * K;\n dk_dD1 = (sum(covDiag.*dh1_dD1) + sum(covDiag.*dh2_dD1))*0.5*sqrt(pi)*sigma;\n dk_dD2 = (sum(covDiag.*dh1_dD2) + sum(covDiag.*dh2_dD2))*0.5*sqrt(pi)*sigma;\n dk_dsigma = sum(covDiag.*(dK_dsigma*0.5*sqrt(pi)*sigma + K));\n else\n dk_dD1 = (sum(covDiag.*dh1_dD1) + sum(covDiag.*dh2_dD1))*0.5;\n dk_dD2 = (sum(covDiag.*dh1_dD2) + sum(covDiag.*dh2_dD2))*0.5;\n dk_dsigma = 0.5 * sum(covDiag.*dK_dsigma);\n end\n dk_dinvWidth = -0.5*sqrt(2)/(simKern1.inverseWidth* ...\n sqrt(simKern1.inverseWidth))*dk_dsigma;\n % only pass the gradient with respect to the inverse width to one\n % of the gradient vectors ... otherwise it is counted twice.\n g1 = real([dk_dD1 dk_dinvWidth]);\n g2 = real([dk_dD2 0]);\nelse\n if isfield(simKern1, 'isNegativeS') && (simKern1.isNegativeS == true)\n C1 = simKern1.sensitivity;\n C2 = simKern2.sensitivity;\n else\n C1 = sqrt(simKern1.variance);\n C2 = sqrt(simKern2.variance);\n end\n K = 0.5 * (h1 + h2);\n var2 = C1*C2;\n if ~isSim1Normalised\n K = sqrt(pi) * K;\n dk_dD1 = (sum(covDiag.*dh1_dD1) + sum(covDiag.*dh2_dD1))*0.5*sqrt(pi)*sigma*var2;\n dk_dD2 = (sum(covDiag.*dh1_dD2) + sum(covDiag.*dh2_dD2))*0.5*sqrt(pi)*sigma*var2;\n dk_dsigma = sum(covDiag.*(dK_dsigma*0.5*sqrt(pi)*sigma + K))*var2;\n dk_dC1 = sigma * C2 * sum(covDiag.*K);\n dk_dC2 = sigma * C1 * sum(covDiag.*K);\n else\n dk_dD1 = (sum(covDiag.*dh1_dD1) + sum(covDiag.*dh2_dD1))*0.5*var2;\n dk_dD2 = (sum(covDiag.*dh1_dD2) + sum(covDiag.*dh2_dD2))*0.5*var2;\n dk_dsigma = 0.5 * var2 * sum(covDiag.*dK_dsigma);\n dk_dC1 = C2 * sum(covDiag.*K);\n dk_dC2 = C1 * sum(covDiag.*K);\n end\n if isfield(simKern1, 'isNegativeS') && simKern1.isNegativeS\n dk_dSim1Variance = dk_dC1;\n else\n dk_dSim1Variance = dk_dC1*0.5/C1;\n end\n if isfield(simKern2, 'isNegativeS') && simKern2.isNegativeS\n dk_dSim2Variance = dk_dC2;\n else\n dk_dSim2Variance = dk_dC2*0.5/C2;\n end\n dk_dinvWidth = -0.5*sqrt(2)/(simKern1.inverseWidth* ...\n sqrt(simKern1.inverseWidth))*dk_dsigma;\n % only pass the gradient with respect to the inverse width to one\n % of the gradient vectors ... otherwise it is counted twice.\n g1 = real([dk_dD1 dk_dinvWidth dk_dSim1Variance]);\n g2 = real([dk_dD2 0 dk_dSim2Variance]);\nend\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/kern/simXsimKernDiagGradient.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7025300449389326, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.34577695310633993}} {"text": "function p06_story ( )\n\n%*****************************************************************************80\n%\n%% P06_STORY prints the \"story\" for problem p06.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 01 August 2011\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Carl DeBoor, John Rice,\n% Least-squares cubic spline approximation II - variable knots.\n% Technical Report CSD TR 21,\n% Purdue University, Lafayette, Indiana, 1968.\n%\n% Carl DeBoor,\n% A Practical Guide to Splines,\n% Springer, 2001,\n% ISBN: 0387953663,\n% LC: QA1.A647.v27.\n%\n% Parameters:\n%\n% None\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The data is due to deBoor and Rice.\\n' );\n fprintf ( 1, ' The data represents a temperature dependent property of titanium.\\n' );\n fprintf ( 1, ' The data has been used extensively as an example in spline\\n' );\n fprintf ( 1, ' approximation with variably-spaced knots.\\n' );\n fprintf ( 1, ' DeBoor considers two sets of knots:\\n' );\n fprintf ( 1, ' (595,675,755,835,915,995,1075)\\n' );\n fprintf ( 1, ' and\\n' );\n fprintf ( 1, ' (595,725,850,910,975,1040,1075).\\n' );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_interp/p06_story.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.345654166284816}} {"text": "function Obs = projectLmk(Rob,Sen,Lmk,Obs,Opt)\n\n% PROJECTLMK Project landmark estimate into sensor's measurement space.\n% Obs = PROJECTLMK(Rob,Sen,Lmk,Obs) projects the landmark Lmk into sensor\n% Sen mounted on robot Rob, and updates the information of the\n% observation structure Obs. The observation model is determined from\n% Sen.type and Lmk.type. It is an error if no model exists for the chosen\n% Sen-Lmk pair.\n%\n% The updated fields in Obs are:\n% .sid % sensor ID\n% .lid % landmark ID\n% .ltype % landmark type\n% .vis % flag: true if landmark is visible\n% .meas.R % measurement noise cov. matrix\n% .exp.e % expectation's mean\n% .exp.E % expectation's covariances matrix\n% .exp.um % expectation's uncertainty measure\n% .Jac.E_r % Jacobian wrt robot frame\n% .Jac.E_s % Jacobian wrt sensor frame\n% .Jac.E_l % Jacobian wrt landmark state\n%\n% See also OBSERVEKNOWNLMKS.\n\n% Copyright 2008-2009 Joan Sola @ LAAS-CNRS.\n\nglobal Map\n\n% PREVIOUS TASKS\n% get landmark range and mean\nlr = Lmk.state.r ; % lmk range in Map\nswitch Map.type\n case 'ekf'\n l = Map.x(lr); % lmk mean\n case 'graph'\n l = Lmk.state.x; % lmk mean\n otherwise\n error('??? Unknown Map type ''%s''.',Map.type)\nend\n\n% PROJECTION FUNCTION\n% explore all sensor and landmark types\nswitch Sen.type\n\n case {'pinHole'} % camera pinHole\n\n switch Lmk.type\n\n case {'eucPnt'} % euclidean point\n\n % Point3D --> pixel -(value and Jacobians)-\n [e, depth, E_rf, E_sf, E_k, E_d, E_l] = ...\n projEucPntIntoPinHoleOnRob( ...\n Rob.frame, ...\n Sen.frame, ...\n Sen.par.k, ...\n Sen.par.d, ...\n l) ;\n\n vis = isVisible(e,depth,Sen.par.imSize);\n\n case {'idpPnt'} % inverse depth point\n\n % IDP --> pixel -(value and Jacobians)-\n [e, depth, E_rf, E_sf, E_k, E_d, E_l] = ...\n projIdpPntIntoPinHoleOnRob( ...\n Rob.frame, ...\n Sen.frame, ...\n Sen.par.k, ...\n Sen.par.d, ...\n l) ;\n\n vis = isVisible(e,depth,Sen.par.imSize);\n\n case {'hmgPnt'} % euclidean point\n\n % Point3D --> pixel -(value and Jacobians)-\n [e, depth, E_rf, E_sf, E_k, E_d, E_l] = ...\n projHmgPntIntoPinHoleOnRob( ...\n Rob.frame, ...\n Sen.frame, ...\n Sen.par.k, ...\n Sen.par.d, ...\n l) ;\n\n vis = isVisible(e,depth,Sen.par.imSize);\n \n case {'ahmPnt'}\n\n % Point3D --> pixel -(value and Jacobians)-\n [e, depth, E_rf, E_sf, E_k, E_d, E_l] = ...\n projAhmPntIntoPinHoleOnRob( ...\n Rob.frame, ...\n Sen.frame, ...\n Sen.par.k, ...\n Sen.par.d, ...\n l);\n\n vis = isVisible(e,depth,Sen.par.imSize);\n\n case {'fhmPnt'}\n\n % Point3D --> pixel -(value and Jacobians)-\n [e, depth, E_rf, E_sf, E_k, E_d, E_l] = ...\n projFhmPntIntoPinHoleOnRob( ...\n Rob.frame, ...\n Sen.frame, ...\n Sen.par.k, ...\n Sen.par.d, ...\n l);\n\n vis = isVisible(e,depth,Sen.par.imSize);\n\n case {'plkLin'}\n\n % Plucker line --> homogeneous line (value and Jacs)\n [e, v, E_rf, E_sf, E_k, E_l] = ...\n projPlkLinIntoPinHoleOnRob( ...\n Rob.frame, ...\n Sen.frame, ...\n Sen.par.k, ...\n l); % expectation e is a homogeneous line\n \n % normalize wrt director vector e(1:2):\n ine12 = 1/norm(e(1:2));\n e = e * ine12;\n E_rf = E_rf * ine12;\n E_sf = E_sf * ine12;\n % E_k = E_k * ine12;\n E_l = E_l * ine12;\n\n % 3d Segment from Plucker line and abscissas\n [si,SI_l] = pluckerSegment(l,[Lmk.par.endp.t]);\n\n % projected segment\n [s, d, S_rf, S_sf, S_k, S_si] = projSegLinIntoPinHoleOnRob(...\n Rob.frame, ...\n Sen.frame, ...\n Sen.par.k, ...\n si); \n \n % segment visibility\n [s,vis] = visibleSegment(s,d,Sen.par.imSize);\n \n case 'aplLin'\n \n % Anchored Plucker line --> homogeneous line (value and Jacs)\n [e, v, E_rf, E_sf, E_k, E_l] = ...\n projAplLinIntoPinHoleOnRob( ...\n Rob.frame, ...\n Sen.frame, ...\n Sen.par.k, ...\n l); % expectation e is a homogeneous line\n\n % normalize wrt director vector e(1:2):\n ine12 = 1/norm(e(1:2));\n e = e * ine12;\n E_rf = E_rf * ine12;\n E_sf = E_sf * ine12;\n % E_k = E_k * ine12;\n E_l = E_l * ine12;\n\n % 3d Segment from Plucker line and abscissas\n [si,SI_l] = aPluckerSegment(l,[Lmk.par.endp.t]);\n\n % projected segment\n [s, d, S_rf, S_sf, S_k, S_si] = projSegLinIntoPinHoleOnRob(...\n Rob.frame, ...\n Sen.frame, ...\n Sen.par.k, ...\n si); \n \n % segment visibility\n [s,vis] = visibleSegment(s,d,Sen.par.imSize);\n \n \n case 'idpLin'\n \n % IDP line --> homogeneous line (value and Jacs)\n [s, v, S_rf, S_sf, S_k, S_l] = ...\n projIdpLinIntoPinHoleOnRob( ...\n Rob.frame, ...\n Sen.frame, ...\n Sen.par.k, ...\n l); % expectation s is a 2d segment\n [e, E_s] = seg2hmgLin(s); % expectation e is a homogeneous line\n E_rf = E_s*S_rf;\n E_sf = E_s*S_sf;\n E_l = E_s*S_l;\n\n % normalize wrt director vector e(1:2):\n ine12 = 1/norm(e(1:2));\n e = e * ine12;\n E_rf = E_rf * ine12;\n E_sf = E_sf * ine12;\n % E_k = E_k * ine12;\n E_l = E_l * ine12;\n\n % 3d Segment from Plucker line and abscissas\n [si,SI_l] = idpLinSegment(l,[Lmk.par.endp.t]);\n\n % projected segment\n [s, d, S_rf, S_sf, S_k, S_si] = projSegLinIntoPinHoleOnRob(...\n Rob.frame, ...\n Sen.frame, ...\n Sen.par.k, ...\n si); \n \n % segment visibility\n [s,vis] = visibleSegment(s,d,Sen.par.imSize,0,Opt.obs.lines.minLength);\n\n case 'hmgLin'\n \n % HMG line --> homogeneous line (value and Jacs)\n [s, v, S_rf, S_sf, S_k, S_l] = ...\n projHmgLinIntoPinHoleOnRob( ...\n Rob.frame, ...\n Sen.frame, ...\n Sen.par.k, ...\n l); % expectation s is a 2d segment\n [e, E_s] = seg2hmgLin(s); % expectation e is a homogeneous line\n E_rf = E_s*S_rf;\n E_sf = E_s*S_sf;\n E_l = E_s*S_l;\n\n % normalize wrt director vector e(1:2):\n ine12 = 1/norm(e(1:2));\n e = e * ine12;\n E_rf = E_rf * ine12;\n E_sf = E_sf * ine12;\n % E_k = E_k * ine12;\n E_l = E_l * ine12;\n\n % 3d Segment from Plucker line and abscissas\n [si,SI_l] = hmgLinSegment(l,[Lmk.par.endp.t]);\n\n % projected segment\n [s, d, S_rf, S_sf, S_k, S_si] = projSegLinIntoPinHoleOnRob(...\n Rob.frame, ...\n Sen.frame, ...\n Sen.par.k, ...\n si); \n \n % segment visibility\n [s,vis] = visibleSegment(s,d,Sen.par.imSize,0,Opt.obs.lines.minLength);\n\n case 'ahmLin'\n \n % AHM line --> homogeneous line (value and Jacs)\n [s, v, S_rf, S_sf, S_k, S_l] = ...\n projAhmLinIntoPinHoleOnRob( ...\n Rob.frame, ...\n Sen.frame, ...\n Sen.par.k, ...\n l); % expectation s is a 2d segment\n [e, E_s] = seg2hmgLin(s); % expectation e is a homogeneous line\n E_rf = E_s*S_rf;\n E_sf = E_s*S_sf;\n E_l = E_s*S_l;\n\n % normalize wrt director vector e(1:2):\n ine12 = 1/norm(e(1:2));\n e = e * ine12;\n E_rf = E_rf * ine12;\n E_sf = E_sf * ine12;\n % E_k = E_k * ine12;\n E_l = E_l * ine12;\n\n % 3d Segment from Plucker line and abscissas\n [si,SI_l] = ahmLinSegment(l,[Lmk.par.endp.t]);\n\n % projected segment\n [s, d, S_rf, S_sf, S_k, S_si] = projSegLinIntoPinHoleOnRob(...\n Rob.frame, ...\n Sen.frame, ...\n Sen.par.k, ...\n si); \n \n % segment visibility\n [s,vis] = visibleSegment(s,d,Sen.par.imSize,0,Opt.obs.lines.minLength);\n\n \n otherwise % unknown landmark type for pin hole sensor\n error('??? Unknown landmark type ''%s'' for sensor ''%s''.', Lmk.type, Sen.type);\n\n end\n \n \n case 'pinHoleDepth' % Pin hole sensor with depth information\n switch Lmk.type\n case 'eucPnt'\n \n % Point3D --> pixel+depth -(value and Jacobians)-\n [e, E_rf, E_sf, E_k, E_d, E_l] = ...\n projEucPntIntoPhdOnRob( ...\n Rob.frame, ...\n Sen.frame, ...\n Sen.par.k, ...\n Sen.par.d, ...\n l) ;\n \n vis = isVisible(e(1:2,:),e(3,:),Sen.par.imSize);\n \n otherwise\n error('??? Unknown landmark type ''%s'' for sensor ''%s''.',Lmk.type,Sen.type);\n end\n \n case {'omniCam'} % Omnidirectional camera\n \n switch Lmk.type\n\n case {'eucPnt'} % euclidean point\n\n % Point3D --> pixel -(value and Jacobians)-\n [e, depth, E_rf, E_sf, E_k, E_d, E_l] = ...\n projEucPntIntoOmniCamOnRob( ...\n Rob.frame, ...\n Sen.frame, ...\n Sen.par.k, ...\n Sen.par.d, ...\n l) ;\n\n vis = isVisible(e,depth,Sen.par.imSize);\n \n case {'ahmPnt'}\n\n % Point3D --> pixel -(value and Jacobians)-\n [e, depth, E_rf, E_sf, E_k, E_d, E_l] = ...\n projAhmPntIntoOmniCamOnRob( ...\n Rob.frame, ...\n Sen.frame, ...\n Sen.par.k, ...\n Sen.par.d, ...\n l);\n\n vis = isVisible(e,depth,Sen.par.imSize);\n \n otherwise % unknown landmark type for pin hole sensor\n error('??? Unknown landmark type ''%s'' for sensor ''%s''.',Lmk.type,Sen.type);\n \n end\n \n \n \n otherwise % unknown Sensor type\n error('??? Unknown sensor type ''%s''.',Sen.type);\n\nend % sensor type\n\n\n% COVARIANCES\nif strcmp(Map.type,'ekf')\n\n % Rob-Sen-Lmk range and Jacobian\n if Sen.frameInMap\n rslr = [Rob.frame.r ; Sen.frame.r ; lr]; % range of robot, sensor, and landmark\n E_rsl = [E_rf E_sf E_l];\n else\n rslr = [Rob.frame.r ; lr]; % range of robot and landmark\n E_rsl = [E_rf E_l];\n end\n \n % Expectation covariances matrix\n E = E_rsl*Map.P(rslr,rslr)*E_rsl' ;\n\nelse\n E = [];\nend\n\n% Other parameters\nswitch Lmk.type(4:6)\n case 'Lin'\n % for lines, project endpoints with covariances:\n\n % compute endpoints\n Obs.par.endp(1).e = s(1:2);\n Obs.par.endp(2).e = s(3:4);\n\n if Map.type == 'ekf'\n % Rob-Sen-Lmk Jacobian of projected segment\n if Sen.frameInMap\n S_rsl = [S_rf S_sf S_si*SI_l];\n else\n S_rsl = [S_rf S_si*SI_l];\n end\n % compute covariances\n S = S_rsl*Map.P(rslr,rslr)*S_rsl'; % segment covariance\n Obs.par.endp(1).E = S(1:2,1:2);\n Obs.par.endp(2).E = S(3:4,3:4);\n end\n \nend\n\n\n% UPDATE OBS STRUCTURE\nObs.sid = Sen.id ;\nObs.lid = Lmk.id ;\nObs.ltype = Lmk.type ;\nObs.vis = vis ;\nObs.exp.e = e ;\nObs.exp.E = E ;\nObs.exp.um = det(E); % uncertainty measure proportional to ellipsoid area\nObs.Jac.E_r = E_rf;\nObs.Jac.E_s = E_sf;\nObs.Jac.E_l = E_l;\n\n\n\n% ========== End of function - Start GPL license ==========\n\n\n% # START GPL LICENSE\n\n%---------------------------------------------------------------------\n%\n% This file is part of SLAMTB, a SLAM toolbox for Matlab.\n%\n% SLAMTB is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% SLAMTB is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with SLAMTB. If not, see .\n%\n%---------------------------------------------------------------------\n\n% SLAMTB is Copyright:\n% Copyright (c) 2008-2010, Joan Sola @ LAAS-CNRS,\n% Copyright (c) 2010-2013, Joan Sola,\n% Copyright (c) 2014-2015, Joan Sola @ IRI-UPC-CSIC,\n% SLAMTB is Copyright 2009 \n% by Joan Sola, Teresa Vidal-Calleja, David Marquez and Jean Marie Codol\n% @ LAAS-CNRS.\n% See on top of this file for its particular copyright.\n\n% # END GPL LICENSE\n\n", "meta": {"author": "joansola", "repo": "slamtb", "sha": "b4767f6bf38bceed205abb85f1aed12422c9a972", "save_path": "github-repos/MATLAB/joansola-slamtb", "path": "github-repos/MATLAB/joansola-slamtb/slamtb-b4767f6bf38bceed205abb85f1aed12422c9a972/InterfaceLevel/projectLmk.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7690802476562641, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.3456189986090583}} {"text": "% ==============================================================================\n%\n% Software License Agreement (BSD License)\n% Copyright (c) 2019\n% (www.aimlab.wpi.edu)\n%\n% All rights reserved.\n%\n% Redistribution and use in source and binary forms, with or without\n% modification, are permitted provided that the following conditions\n% are met:\n%\n% * Redistributions of source code must retain the above copyright\n% notice, this list of conditions and the following disclaimer.\n%\n% * Redistributions in binary form must reproduce the above\n% copyright notice, this list of conditions and the following\n% disclaimer in the documentation and/or other materials provided\n% with the distribution.\n%\n% * Neither the name of authors nor the names of its contributors may\n% be used to endorse or promote products derived from this software\n% without specific prior written permission.\n%\n% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n% \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n% LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n% FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n% COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n% INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n% BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n% LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n% CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n% LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n% ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n% POSSIBILITY OF SUCH DAMAGE.\n%\n% \\author: \n% \\author: \n% \\author: Adnan Munawar\n% \\version: 0.1$\n% ==============================================================================\n\nfunction [its,sizePath,run_time] = RRTstar3D(dim,segmentLength,radius,random_world,show_output,samples)\n% if samples < 4000\n% disp('ERROR! SPECIFY ATLEAST 4000 SAMPLES')\n% return\n% end\n\n% dim = 2;\n% radius =0;\n% segmentLength = 5;\n% random_world = 0;\n% n_its = 1000;\n% standard length of path segments\nif dim ==2\n start_cord = [5,5];\n goal_cord = [95,95];\n \nelse\n \n start_cord = [5,5,5];\n goal_cord = [95,95,95];\nend\n\n\n\n% create random world\nSize = 100;\nNumObstacles = 100;\n\nif random_world ==1\n world = createWorld(NumObstacles,ones(1,dim)*Size,zeros(1,dim),dim);\nelse\n [world NumObstacles] = createKnownWorld(ones(1,dim)*Size,[0;0;0],dim);\nend\n% randomly select start and end nodes\n%start_node = generateRandomNode(world,dim)\n%end_node = generateRandomNode(world,dim)\nstart_node = [start_cord,0,0,0];\nend_node = [goal_cord,0,0,0];\n% establish tree starting with the start node\ntree = start_node;\n\nnumPaths = 0;\na = clock;\n% check to see if start_node connects directly to end_node\nif ( (norm(start_node(1:dim)-end_node(1:dim))0\n draw = floor(samples/8);\n its = 0;\n for i = 1:samples\n flag = 0;\n [tree,flag] = extendTree(tree,end_node,segmentLength,radius,world,flag,dim);\n numPaths = numPaths + flag;\n its = its+1;\n \n if its == draw\n tree_1 = tree;\n elseif its == draw*2\n tree_2 = tree;\n elseif its == draw*3\n tree_3 = tree;\n elseif its == draw*4\n tree_4 = tree;\n elseif its == draw*5\n tree_5 = tree;\n elseif its == draw*6\n tree_6 = tree;\n elseif its == draw*7\n tree_7 = tree;\n elseif its == samples\n tree_8 = tree;\n end\n end\n \n else\n its = 0;\n numPaths = 0;\n flag = 0;\n while numPaths < 1,\n [tree,flag] = extendTree(tree,end_node,segmentLength,radius,world,flag,dim);\n numPaths = numPaths + flag;\n its = its+1;\n end\n end\n \nend\nnumPaths\n\n% find path with minimum cost to end_node\npath = findMinimumPath(tree,end_node,dim);\n\nb = clock;\nrun_time = 3600*(b(4)-a(4)) + 60 * (b(5)-a(5)) + (b(6) - a(6));\n\npath_1 = findMinimumPath(tree_1,end_node,dim);\n\npath_2 = findMinimumPath(tree_2,end_node,dim);\n\npath_3 = findMinimumPath(tree_3,end_node,dim);\n\npath_4 = findMinimumPath(tree_4,end_node,dim);\n\npath_5 = findMinimumPath(tree_5,end_node,dim);\n\npath_6 = findMinimumPath(tree_6,end_node,dim);\n\npath_7 = findMinimumPath(tree_7,end_node,dim);\n\npath_8 = findMinimumPath(tree_8,end_node,dim);\n\nsizePath = size(path,1);\n\n\nif show_output == 1\n \n if size(path_1, 1) > 0\n figure;\n plotExpandedTree(world,tree_1,dim);\n plotWorld(world,path_1,dim);\n else\n disp('COULD NOT FIND A CONNECTING TREE TILL 1/8th SAMPLES SO NOT DRAWING THAT PATH')\n end\n if size(path_2, 1) > 0\n figure;\n plotExpandedTree(world,tree_2,dim);\n plotWorld(world,path_2,dim);\n else\n disp('COULD NOT FIND A CONNECTING TREE TILL 2/8th SAMPLES SO NOT DRAWING THAT PATH')\n end\n if size(path_3, 1) > 0\n figure;\n plotExpandedTree(world,tree_3,dim);\n plotWorld(world,path_3,dim);\n else\n disp('COULD NOT FIND A CONNECTING TREE TILL 3/8th SAMPLES SO NOT DRAWING THAT PATH')\n end\n if size(path_4, 1) > 0\n figure;\n plotExpandedTree(world,tree_4,dim);\n plotWorld(world,path_4,dim);\n else\n disp('COULD NOT FIND A CONNECTING TREE TILL 4/8th SAMPLES SO NOT DRAWING THAT PATH')\n end\n if size(path_5, 1) > 0\n figure;\n plotExpandedTree(world,tree_5,dim);\n plotWorld(world,path_5,dim);\n else\n disp('COULD NOT FIND A CONNECTING TREE TILL 5/8th SAMPLES SO NOT DRAWING THAT PATH')\n end\n if size(path_6, 1) > 0\n figure;\n plotExpandedTree(world,tree_6,dim);\n plotWorld(world,path_6,dim);\n else\n disp('COULD NOT FIND A CONNECTING TREE TILL 6/8th SAMPLES SO NOT DRAWING THAT PATH')\n end\n if size(path_7, 1) > 0\n figure;\n plotExpandedTree(world,tree_7,dim);\n plotWorld(world,path_7,dim);\n else\n disp('COULD NOT FIND A CONNECTING TREE TILL 7/8th SAMPLES SO NOT DRAWING THAT PATH')\n end\n if size(path_8, 1) > 0\n figure;\n plotExpandedTree(world,tree_8,dim);\n plotWorld(world,path_8,dim);\n else\n disp('COULD NOT FIND A CONNECTING TREE TILL 8/8th SAMPLES SO NOT DRAWING THAT PATH')\n end\n if size(path, 1) > 0\n figure;\n plotExpandedTree(world,tree,dim);\n plotWorld(world,path,dim);\n else\n disp('COULD NOT FIND A CONNECTING TREE FOR THE SPECIFIED SAMPLES. PLEASE INCREASE THE NUMBER OF SAMPLES')\n end\nend\nend\n\n\n\n\n\nfunction world = createWorld(NumObstacles, endcorner, origincorner,dim)\n\nif dim == 2\n \n % check to make sure that the region is nonempty\n if (endcorner(1) <= origincorner(1)) | (endcorner(2) <= origincorner(2))\n disp('Not valid corner specifications!')\n world=[];\n \n % create world data structure\n else\n world.NumObstacles = NumObstacles;\n world.endcorner = endcorner;\n world.origincorner = origincorner;\n \n % create NumObstacles\n maxRadius = min(endcorner(1)- origincorner(1), endcorner(2)-origincorner(2));\n maxRadius = 5*maxRadius/NumObstacles/2;\n for i=1:NumObstacles,\n % randomly pick radius\n world.radius(i) = maxRadius*rand;\n % randomly pick center of obstacles\n cx = origincorner(1) + world.radius(i)...\n + (endcorner(1)-origincorner(1)-2*world.radius(i))*rand;\n cy = origincorner(2) + world.radius(i)...\n + (endcorner(2)-origincorner(2)-2*world.radius(i))*rand;\n world.cx(i) = cx;\n world.cy(i) = cy;\n end\n end\n \nelseif dim ==3;\n % check to make sure that the region is nonempty\n if (endcorner(1) <= origincorner(1)) || (endcorner(2) <= origincorner(2)) || (endcorner(3) <= origincorner(3))\n disp('Not valid corner specifications!')\n world=[];\n \n % create world data structure\n else\n world.NumObstacles = NumObstacles;\n world.endcorner = endcorner;\n world.origincorner = origincorner;\n \n % create NumObstacles\n bounds = [endcorner(1)- origincorner(1), endcorner(2)-origincorner(2), endcorner(3)-origincorner(3)];\n maxRadius = min(bounds);\n maxRadius = 5*maxRadius/NumObstacles;\n for i=1:NumObstacles,\n % randomly pick radius\n world.radius(i) = maxRadius*rand;\n % randomly pick center of obstacles\n cx = origincorner(1) + world.radius(i)...\n + (endcorner(1)-origincorner(1)-2*world.radius(i))*rand;\n cy = origincorner(2) + world.radius(i)...\n + (endcorner(2)-origincorner(2)-2*world.radius(i))*rand;\n cz = origincorner(2) + world.radius(i)...\n + (endcorner(2)-origincorner(2)-2*world.radius(i))*rand;\n world.cx(i) = cx;\n world.cy(i) = cy;\n world.cz(i) = cz;\n end\n end\nend\nend\n\nfunction [world NumObstacles] = createKnownWorld(endcorner, origincorner,dim)\nNumObstacles = 5;\nif dim == 2\n % check to make sure that the region is nonempty\n if (endcorner(1) <= origincorner(1)) | (endcorner(2) <= origincorner(2)),\n disp('Not valid corner specifications!')\n world=[];\n % create world data structure\n else\n world.NumObstacles = NumObstacles;\n world.endcorner = endcorner;\n world.origincorner = origincorner;\n \n % create NumObstacles\n maxRadius = 10;\n \n world.radius(1) = maxRadius;\n cx = 50;\n cy = 50;\n world.cx(1) = cx;\n world.cy(1) = cy;\n \n world.radius(2) = maxRadius;\n cx = 75;\n cy = 25;\n world.cx(2) = cx;\n world.cy(2) = cy;\n \n world.radius(3) = maxRadius;\n cx = 25;\n cy = 75;\n world.cx(3) = cx;\n world.cy(3) = cy;\n \n world.radius(4) = maxRadius;\n cx = 25;\n cy = 25;\n world.cx(4) = cx;\n world.cy(4) = cy;\n \n world.radius(5) = maxRadius;\n cx = 75;\n cy = 75;\n world.cx(5) = cx;\n world.cy(5) = cy;\n end\n \nelseif dim == 3\n \n NumObstacles = 9;\n % check to make sure that the region is nonempty\n if (endcorner(1) <= origincorner(1)) | (endcorner(2) <= origincorner(2)) | (endcorner(3) <= origincorner(3)),\n disp('Not valid corner specifications!')\n world=[];\n \n % create world data structure\n else\n world.NumObstacles = NumObstacles;\n world.endcorner = endcorner;\n world.origincorner = origincorner;\n \n % create NumObstacles\n maxRadius = 10;\n \n world.radius(1) = maxRadius;\n cx = 50;\n cy = 50;\n cz = 50;\n world.cx(1) = cx;\n world.cy(1) = cy;\n world.cz(1) = cz;\n \n world.radius(2) = maxRadius;\n cx = 25;\n cy = 25;\n cz = 25;\n world.cx(2) = cx;\n world.cy(2) = cy;\n world.cz(2) = cz;\n \n world.radius(3) = maxRadius;\n cx = 75;\n cy = 75;\n cz = 75;\n world.cx(3) = cx;\n world.cy(3) = cy;\n world.cz(3) = cz;\n \n world.radius(4) = maxRadius;\n cx = 25;\n cy = 25;\n cz = 75;\n world.cx(4) = cx;\n world.cy(4) = cy;\n world.cz(4) = cz;\n \n world.radius(5) = maxRadius;\n cx = 75;\n cy = 75;\n cz = 25;\n world.cx(5) = cx;\n world.cy(5) = cy;\n world.cz(5) = cz;\n \n world.radius(6) = maxRadius;\n cx = 25;\n cy = 75;\n cz = 25;\n world.cx(6) = cx;\n world.cy(6) = cy;\n world.cz(6) = cz;\n \n world.radius(7) = maxRadius;\n cx = 75;\n cy = 25;\n cz = 25;\n world.cx(7) = cx;\n world.cy(7) = cy;\n world.cz(7) = cz;\n \n world.radius(8) = maxRadius;\n cx = 75;\n cy = 25;\n cz = 75;\n world.cx(8) = cx;\n world.cy(8) = cy;\n world.cz(8) = cz;\n \n \n world.radius(9) = maxRadius;\n cx = 25;\n cy = 75;\n cz = 75;\n world.cx(9) = cx;\n world.cy(9) = cy;\n world.cz(9) = cz;\n end\nend\nend\n\n\n\n\n\nfunction node=generateRandomNode(world,dim)\n\nif dim ==2;\n % randomly pick configuration\n px = (world.endcorner(1)-world.origincorner(1))*rand;\n py = (world.endcorner(2)-world.origincorner(2))*rand;\n \n chi = 0;\n cost = 0;\n node = [px, py, chi, cost, 0];\n \n % check collision with obstacle\n while collision(node, node, world,dim),\n px = (world.endcorner(1)-world.origincorner(1))*rand;\n py = (world.endcorner(2)-world.origincorner(2))*rand;\n \n chi = 0;\n cost = 0;\n node = [px, py, chi, cost, 0];\n end\n \nelseif dim ==3;\n % randomly pick configuration\n px = (world.endcorner(1)-world.origincorner(1))*rand;\n py = (world.endcorner(2)-world.origincorner(2))*rand;\n pz = (world.endcorner(3)-world.origincorner(3))*rand;\n \n chi = 0;\n cost = 0;\n node = [px, py, pz, chi, cost, 0];\n \n % check collision with obstacle\n while collision(node, node, world,dim),\n px = (world.endcorner(1)-world.origincorner(1))*rand;\n py = (world.endcorner(2)-world.origincorner(2))*rand;\n pz = (world.endcorner(3)-world.origincorner(3))*rand;\n \n chi = 0;\n cost = 0;\n node = [px, py, pz, chi, cost, 0];\n end\n \nend\n\nend\n\n\n\n\n\nfunction collision_flag = collision(node, parent, world,dim)\n\ncollision_flag = 0;\n\n\nfor i=1:dim\n if (node(i)>world.endcorner(i))|(node(i)1\n size_near = size(near_idx,1);\n \n for i = 1:size_near\n if collision(new_node, tree(near_idx(i),:), world,dim)==0\n \n cost_near = tree(near_idx(i),dim+2)+line_cost(tree(near_idx(i),:),new_point,dim);\n \n if cost_near < min_cost\n min_cost = cost_near;\n min_parent_idx = near_idx(i);\n end\n \n end\n end\n end\n \n new_node = [new_point, 0 , min_cost, min_parent_idx];\n new_tree = [tree; new_node];\n new_node_idx = size(new_tree,1);\n \n if size(near_idx,1)>1\n reduced_idx = near_idx;\n for j = 1:size(reduced_idx,1)\n near_cost = new_tree(reduced_idx(j),dim+2);\n lcost = line_cost(new_tree(reduced_idx(j),:),new_point,dim);\n if near_cost > min_cost + lcost ...\n && collision(new_tree(reduced_idx(j),:),new_node,world,dim)\n before = new_tree(reduced_idx(j),dim+3)\n new_tree(reduced_idx(j),dim+3) = new_node_idx;\n after = new_tree(reduced_idx(j),dim+3)\n end\n \n end\n end\n flag1=1;\n end\nend\n\n\nif flag_chk == 0\n % check to see if new node connects directly to end_node\n if ( (norm(new_node(1:dim)-end_node(1:dim)) 0\n \n % find minimum cost last node\n [tmp,idx] = min(connectingNodes(:,dim+2));\n \n % construct lowest cost path\n path = [connectingNodes(idx,:); end_node];\n parent_node = connectingNodes(idx,dim+3);\n while parent_node>1,\n parent_node = tree(parent_node,dim+3);\n path = [tree(parent_node,:); path];\n end\n \nelse\n path = [];\nend\n\nend\n\n\nfunction plotExpandedTree(world,tree,dim)\nind = size(tree,1);\nwhile ind>0\n branch = [];\n node = tree(ind,:);\n branch = [ branch ; node ];\n parent_node = node(dim+3);\n while parent_node > 1\n cur_parent = parent_node;\n branch = [branch; tree(parent_node,:)];\n parent_node = tree(parent_node,dim+3);\n end\n ind = ind - 1;\n \n if dim == 2\n X = branch(:,1);\n Y = branch(:,2);\n \n p = plot(X,Y);\n set(p,'Color','r','LineWidth',0.5,'Marker','.','MarkerEdgeColor','g');\n hold on;\n \n elseif dim == 3\n X = branch(:,1);\n Y = branch(:,2);\n Z = branch(:,3);\n \n p = plot3(X,Y,Z);\n set(p,'Color','r','LineWidth',0.5,'Marker','.','MarkerEdgeColor','g');\n hold on;\n end\nend\nend\n\n\n\n\nfunction plotWorld(world,path,dim)\n% the first element is the north coordinate\n% the second element is the south coordinate\nif dim ==2\n \n N = 10;\n th = 0:2*pi/N:2*pi;\n axis([world.origincorner(1),world.endcorner(1),...\n world.origincorner(2), world.endcorner(2)]);\n hold on\n \n for i=1:world.NumObstacles,\n X = world.radius(i)*sin(th) + world.cx(i);\n Y = world.radius(i)*cos(th) + world.cy(i);\n fill(X,Y,'blue');\n end\n \n X = path(:,1);\n Y = path(:,2);\n p = plot(X,Y);\n \nelseif dim ==3\n axis([world.origincorner(1),world.endcorner(1),...\n world.origincorner(2), world.endcorner(2),...\n world.origincorner(3), world.endcorner(3)]);\n hold on\n \n for i=1:world.NumObstacles,\n [X Y Z] = sphere(10);\n X = (X*world.radius(i));\n Y = (Y*world.radius(i));\n Z = (Z*world.radius(i));\n surf(X+world.cx(i),Y+world.cy(i),Z+world.cz(i));\n colormap([0.5 0.2 0.3]);\n end\n \n X = path(:,1);\n Y = path(:,2);\n Z = path(:,3);\n p = plot3(X,Y,Z);\nend\nset(p,'Color','black','LineWidth',3)\nxlabel('X axis');\nylabel('Y axis');\nzlabel('Z axis');\ntitle('RRT Star Algorithm');\nend\n", "meta": {"author": "adnanmunawar", "repo": "matlab-rrt-variants", "sha": "47b2ec61b8c444a27b7ac58f7c79c1279aff5187", "save_path": "github-repos/MATLAB/adnanmunawar-matlab-rrt-variants", "path": "github-repos/MATLAB/adnanmunawar-matlab-rrt-variants/matlab-rrt-variants-47b2ec61b8c444a27b7ac58f7c79c1279aff5187/RRTstar3D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6959583376458153, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.3452606368749277}} {"text": "function model = Learning_MLE_Basis_Stoc( Seqs, model, alg )\n \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Learning Hawkes processes via maximum likelihood estimation\n% Different regularizers (low-rank, sparse, group sparse) of parameters and\n% their combinations are considered, which are solved via StochasticADMM.\n%\n% Reference:\n% Xu, Hongteng, Mehrdad Farajtabar, and Hongyuan Zha. \n% \"Learning Granger Causality for Hawkes Processes.\" \n% International Conference on Machine Learning (ICML). 2016.\n%\n% Provider:\n% Hongteng Xu @ Georgia Tech\n% June. 10, 2017\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% initial \nAest = model.A; \nmuest = model.mu;\n% KerFint = struct('dGK', []);\n% KerF = struct('gij', []);\n\nif alg.LowRank\n UL = zeros(size(Aest));\n ZL = Aest;\nend\n\nif alg.Sparse\n US = zeros(size(Aest));\n ZS = Aest;\nend\n\nif alg.GroupSparse\n UG = zeros(size(Aest));\n ZG = Aest;\nend\n\nD = size(Aest, 1);\n\nif alg.storeLL\n model.LL = zeros(alg.epoch, 1);\nend\nif alg.storeErr\n model.err = zeros(alg.epoch, 3);\nend\n\n\ntic;\nfor o = 1:alg.epoch % the number of epoch for stochastic opt\n \n rho = alg.rho * (1.1^o);\n \n idx_seq = randperm(length(Seqs));\n if length(Seqs)1\n start = max([1, i-alg.historyL]);\n tj = Time(start:i-1);\n uj = Event(start:i-1);\n\n %if o==1 || isempty(KerF(c).gij)\n dt = ti - tj;\n dt1 = ti1 - tj;\n gij = Kernel(dt, model);\n \n %KerF(c).gij(1:length(dt),:,i-1) = gij;\n \n GK = Kernel_Integration(dt, model);\n GK1 = Kernel_Integration(dt1, model);\n dGK = GK - GK1;\n %KerFint(c).dGK(1:length(dt),:,i-1) = dGK;\n %end\n \n auiuj = Aest(uj, :, ui);\n %pij = auiuj .* KerF(c).gij(1:length(uj),:,i-1);%\n pij = auiuj .* gij;\n lambdai = lambdai + sum(pij(:));\n end\n pii = pii./lambdai;\n \n \n if i>1\n pij = pij./lambdai;\n if ~isempty(pij) && sum(pij(:))>0\n for j = 1:length(uj)\n uuj = uj(j);\n CmatA(uuj,:,ui) = CmatA(uuj,:,ui) - pij(j,:);\n \n BmatA(uuj,:,:) = BmatA(uuj,:,:) + ...\n double(Aest(uuj,:,:)>0).*...\n repmat( dGK(j,:), [1,1,D] );\n %repmat( KerFint(c).dGK(j,:,i-1), [1,1,D] );\n end\n end\n end\n Bmu(ui) = Bmu(ui) + pii;\n \n end\n end\n \n% Amu = Amu + Tstop - Tstart;\n% \n% dT = Tstop - Time;\n% GK = Kernel_Integration(dT, model);\n% \n% Nc = length(Time);\n% idx_event = randperm(Nc);\n% \n% if Nc0).*repmat( GK(i,:), [1,1,D] );\n% \n% ti = Time(i); \n% lambdai = muest(ui);\n% pii = muest(ui);\n% pij = [];\n% \n% if i>1\n% start = max([1, i-alg.historyL]);\n% tj = Time(start:i-1);\n% uj = Event(start:i-1);\n% \n% dt = ti - tj;\n% gij = Kernel(dt, model);\n% auiuj = Aest(uj, :, ui);\n% pij = auiuj .* gij;\n% lambdai = lambdai + sum(pij(:));\n% end\n% \n% pii = pii./lambdai;\n% \n% if i>1\n% pij = pij./lambdai;\n% if ~isempty(pij) && sum(pij(:))>0\n% for j = 1:length(uj)\n% uuj = uj(j);\n% CmatA(uuj,:,ui) = CmatA(uuj,:,ui) - pij(j,:);\n% end\n% end\n% end\n% \n% Bmu(ui) = Bmu(ui) + pii;\n% end\n% end \n else\n warning('Sequence %d is empty!', c)\n end\n end\n \n % M-step: update parameters\n mu = Bmu./Amu; \n if alg.Sparse==0 && alg.GroupSparse==0 && alg.LowRank==0\n A = -CmatA./BmatA;%( -BA+sqrt(BA.^2-4*AA*CA) )./(2*AA);\n A(isnan(A))=0;\n A(isinf(A))=0;\n else \n A = ( -BmatA + sqrt(BmatA.^2 - 4*AmatA.*CmatA) )./(2*AmatA);\n A(isnan(A))=0;\n A(isinf(A))=0;\n end\n \n \n \n % check convergence\n Err=sum(sum(sum(abs(A-Aest))))/sum(abs(Aest(:)));\n Aest = A;\n muest = mu;\n model.A = Aest;\n model.mu = muest;\n fprintf('Epoch=%d, EventBatch=%d, RelErr=%f, Time=%0.2fsec\\n',...\n o, n, Err, toc);\n \n if ErrZMAP)\n % choice Nr. of M5+ aftershock\n %\n % Output parameters:\n % opt_radius radius around large aftershock\n % opt_interval time interval before large aftershock\n % result matrix containing relative seismic quiescences\n % r, alldt vectors with radii, forecast intervals\n % numreal,nummod observed/modeled nr. of aftershocks in interval\n % sigma uncertainty of forecast\n %\n % Samuel Neukomm\n % last update 25.02.2004\n\nreport_this_filefun(mfilename('fullpath'));\n % get mainshock / calculate delay times / cut catalogue at mainshock\n [m_main, main] = max(a.Magnitude);\n if size(a,2) == 9\n date_matlab = datenum(a.Date.Year,a.Date.Month,a.Date.Day,a.Date.Hour,a.Date.Minute,zeros(size(a,1),1));\n else\n date_matlab = datenum(a.Date.Year,a.Date.Month,a.Date.Day,a.Date.Hour,a.Date.Minute,a(:,10));\n end\n date_main = date_matlab(main);\n time_aftershock = date_matlab-date_main;\n l = time_aftershock(:) > 0;\n tas = time_aftershock(l);\n eqcatalogue = a.subset(l);\n\n % choose one of large aftershocks\n l = eqcatalogue(:,6) >= 5;\n largeas = eqcatalogue(l,:);\n largetime = tas(l);\n eq = largeas(choice,:);\n eqt = largetime(choice);\n\n % get optimum parameters\n dist_lon = eqcatalogue(:,1)-eq(1);\n dist_lat = eqcatalogue(:,2)-eq(2);\n dist_dep = km2deg(eqcatalogue(:,7)-eq(7),6371);\n result = []; i = 1;\n numreal = []; nummod = []; sigma = [];\n for r = rmin:rstep:rmax % range of collection radius\n disp(num2str(r/rmax))\n l = (dist_lon.^2+dist_lat.^2+dist_dep.^2).^0.5 <= r;\n gpi = eqcatalogue(l,:);\n time_as = tas(l);\n l = time_as < eqt;\n gpi = gpi(l,:); % sub-catalogue to be analysed\n time_as = time_as(l); % corresponding delay times\n\n if length(time_as) >= Nmin\n dt = tmin; % interval before large aftershock\n j = 1; alldt = [];\n while dt < eqt % Changed eqt/2 to eqt\n [rc,realnum,modnum,sig] = calc_optrc(gpi,time_as,eqt-dt,eqt,bootloops,maepi); % determine significance\n if isnan(rc)==0\n result(i,j) = rc;\n numreal(i,j) = realnum;\n nummod(i,j) = modnum;\n sigma(i,j) = sig;\n else\n result(i,j) = 0;\n numreal(i,j) = 0;\n nummod(i,j) = 0;\n sigma(i,j) = 0;\n end\n alldt = [alldt; dt];\n dt = dt+tstep;\n j = j+1;\n end\n end\n i = i+1;\n end\n r = (rmin:rstep:rmax)';\n\n if isempty(result) == 0 && max(max(result)) > 0\n % find minimum\n [dum, j] = min(min(result));\n [dum, i] = min(result(:,j));\n opt_radius = r(i);\n opt_interval = alldt(j);\n\n % contourplot of results\n figure_w_normalized_uicontrolunits('Numbertitle','off','Name','Optimum quiescence')\n lim = ceil(abs(dum));\n pcolor(alldt,r,result)\n set(gca,'pos',[0.15 0.15 0.7 0.7])\n shading interp\n caxis([-lim lim]);\n load fourcolors\n j = [j(256:-1:1,:) ];\n colormap(j)\n set(gcf,'renderer','zbuffer');\n set(gca,'TickDir','out')\n h5 = colorbar;\n set(h5,'Tickdir','out','pos',[0.8 0.3 0.02 0.4]);\n hold on\n plot(opt_interval,opt_radius','*','Markersize',8,'linewidth',2,'color','k');\n string =['Radius = ' num2str(opt_radius) ' deg; Interval = ' num2str(opt_interval) ' days; RC = ' num2str(dum,3) ];\n title(string)\n string = ['Time interval before t1 = ' num2str(round(100*eqt)/100) ' [days]'];\n xlabel(string)\n ylabel('Radius [deg]');\n set(gcf,'color','w');\n\n l = (dist_lon.^2+dist_lat.^2+dist_dep.^2).^0.5 <= opt_radius;\n optcat = eqcatalogue(l,:);\n time_as = tas(l);\n l = time_as < eqt;\n optcat = optcat(l,:);\n plot_optfit(optcat,eqt-opt_interval,opt_interval,bootloops,maepi);\n else\n opt_radius = NaN;\n opt_interval = NaN;\n alldt = NaN;\n end\n", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/zmap_deprecated/orphaned/src/afterrate/calc_optim.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.344623109741221}} {"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Spherical Harmonic Modeling and Analysis Toolkit (SPHARM-MAT) is a 3D \n% shape modeling and analysis toolkit. \n% It is a software package developed at Shenlab in Center for Neuroimaging, \n% Indiana University (SpharmMat@gmail.com, http://www.iupui.edu/~shenlab/)\n% It is available to the scientific community as copyright freeware \n% under the terms of the GNU General Public Licence.\n% \n% Copyright 2009, 2010, ShenLab, Center for Neuroimaging, Indiana University\n% \n% This file is part of SPHARM-MAT.\n% \n% SPHARM-MAT is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% SPHARM-MAT is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with SPHARM-MAT. If not, see .\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% ============================================\n% read_coef.m\n% function for reading *.coef file and saving the coefficients to *_des.mat\n% file\n\n% INPUT: filename, which is the name of the input coef file. \n% If not specifying a filename, a dialogue window will be activated for choosing a\n% gipl file. \n%\n% Wan Jing\n% 11/06/2008 - create\n%============================================\n\nfunction fvec = read_coef(filename)\n\nfid = fopen(filename,'r');\nif(fid<0)\n fprintf('could not open file %s\\n',filename);\n return\nend\n\n\nCount = fscanf(fid, '{ %d,', 1);\nif(isempty(Count))\n fprintf('The type of this file is not coef. \\n');\n return;\nend\n\n% read the coefficients to C\nC = fscanf(fid, '{%lf, %lf, %lf},\\n', [3 inf]);\nC = C';\nfprintf('The number of coefficients are: %d .\\n ',length(C));\n\nif (Count ~= length(C))\n fprintf('The file has error about the number of coefficients');\nend\n\nfvec = [];\ni = 1;\n\nmd = sqrt(length(C))-1;\nfor L = 0:md\n for M=-L:L\n% disp(sprintf('i=%d, L=%d, M=%d',i,L,M));\n switch sign(M)\n case -1\n fvec(end+1,:) = [0 0 0];\n case 0\n fvec(end+1,:) = C(i,:); i=i+1;\n case 1\n fvec(end+1,:) = complex(C(i,:),C(i+1,:)); i=i+2;\n end\n end\nend\n\nfclose('all');\n\nreturn\n\n ", "meta": {"author": "vigente", "repo": "gerardus", "sha": "4d7c5195b826967781f1bb967872410e66b7cd3d", "save_path": "github-repos/MATLAB/vigente-gerardus", "path": "github-repos/MATLAB/vigente-gerardus/gerardus-4d7c5195b826967781f1bb967872410e66b7cd3d/matlab/ThirdPartyToolbox/SpharmToolbox/code/read_coef.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.3445189262749576}} {"text": "function sys = sdpvar(varargin)\n%SDPVAR Create symbolic decision variable\n%\n% You can create a sdpvar variable by:\n% X = SDPVAR(n) Symmetric nxn matrix\n% X = SDPVAR(n,n) Symmetric nxn matrix\n% X = SDPVAR(n,m) Full nxm matrix (n~=m)\n%\n% Definition of multiple scalars can be simplified\n% SDPVAR x y z w\n%\n% The parametrizations supported are\n% X = SDPVAR(n,n,'full') Full nxn matrix\n% X = SDPVAR(n,n,'symmetric') Symmetric nxn matrix\n% X = SDPVAR(n,n,'toeplitz') Symmetric Toeplitz\n% X = SDPVAR(n,n,'hankel') Symmetric Hankel\n% X = SDPVAR(n,n,'skew') Skew-symmetric\n%\n% The letters 'sy','f','ha', 't' and 'sk' are searched for in the third argument\n% hence sdpvar(n,n,'toeplitz') gives the same result as sdpvar(n,n,'t')\n%\n% Only square Toeplitz and Hankel matries are supported\n%\n% A scalar is defined as a 1x1 matrix\n%\n% Higher-dimensional matrices are also supported, although this currently\n% is an experimental feature with limited use. The type flag applies to\n% the lowest level slice.\n%\n% X = SDPVAR(n,n,n,'full') Full nxnxn matrix\n%\n% In addition to the matrix type, a fourth argument\n% can be used to obtain a complex matrix. All the\n% matrix types above apply to a complex matrix, and\n% in addition a Hermitian type is added\n%\n% X = SDPVAR(n,n,'hermitian','complex') Complex Hermitian nxn matrix (X=X'=conj(X.'))\n%\n% The other types are obtained as above\n% X = SDPVAR(n,n,'symmetric','complex') Complex symmetric nxn matrix (X=X.')\n% X = SDPVAR(n,n,'full','complex') Complex full nxn matrix\n% ... and the same for Toeplitz, Hankel and skew-symmetric\n%\n% See also @SDPVAR/SET, INTVAR, BINVAR, methods('sdpvar'), SEE\n\nsuperiorto('sdpvar');\nif nargin==0 \n return\nend\n\nif isstruct(varargin{1})\n sys = class(varargin{1},'ncvar');\n return\nend\n\n% To speed up dualization, we keep track of primal SDP cones\n% [0 0] : Nothing known (cleared in some operator, or none-cone to start with)\n% [1 0] : Primal cone\n% [1 1] : Primal cone + DOUBLE\n% [1 2 x] : Primal cone + SDPVAR\n% [-1 1] : -Primal cone + DOUBLE\n% [-1 2 x] : -Primal cone + SDPVAR\n\nconicinfo = [0 0];\n\nif ischar(varargin{1})\n switch varargin{1}\n case 'clear'\n disp('Obsolete comand');\n return\n case 'nvars'\n sys = yalmip('nvars');%THIS IS OBSAOLETE AND SHOULD NOT BE USED\n return\n otherwise\n n = length(varargin);\n varnames = varargin;\n for k = 1:n\n varcmd{k}='(1,1)';\n lp=strfind(varargin{k},'(');\n rp=strfind(varargin{k},')');\n if isempty(lp) & isempty(rp)\n if ~isvarname(varargin{k})\n error('Not a valid variable name.')\n end\n else\n if (~isempty(lp))&(~isempty(rp))\n if min(lp) 2 & isa(varargin{3},'double') & ~isempty(varargin{3})\n sys = ndsdpvar(varargin{:});\n return\nend\n\n\n% Supported matrix types\n% - symm\n% - full\n% - skew\n% - hank\n% - toep\nswitch nargin\n case 1 %Bug in MATLAB 5.3!! sdpvar called from horzcat!!!!????\n if isempty(varargin{1})\n sys = varargin{1};\n return\n end\n if isa(varargin{1},'sdpvar')\n sys = varargin{1};\n sys.typeflag = 0;\n return\n end\n n = varargin{1};\n m = varargin{1};\n if sum(n.*m)==0\n sys = zeros(n,m);\n return\n end\n if (n==m)\n matrix_type = 'symm';\n nvar = sum(n.*(n+1)/2);\n conicinfo = [1 0];\n else\n matrix_type = 'full';\n nvar = sum(n.*m);\n end\n case 2\n n = varargin{1};\n m = varargin{2};\n if length(n)~=length(m)\n error('The dimensions must have the same lengths')\n end\n if sum(n.*m)==0\n sys = zeros(n,m);\n return\n end\n if (n==m)\n matrix_type = 'symm';\n nvar = sum(n.*(n+1)/2);\n conicinfo = [1 0];\n else\n matrix_type = 'full';\n nvar = sum(n.*m);\n end\n case {3,4}\n n = varargin{1};\n m = varargin{2};\n if sum(n.*m)==0\n sys = zeros(n,m);\n return\n end\n\n % Check for complex or real\n if (nargin == 4)\n if isempty(varargin{4})\n varargin{4} = 'real';\n else\n if ~ischar(varargin{4})\n help sdpvar\n error('Fourth argument should be ''complex'' or ''real''')\n end\n end\n index_cmrl = strmatch_octavesafe(varargin{4},{'real','complex'});\n if isempty(index_cmrl)\n error('Fourth argument should be ''complex'' or ''real''. See help above')\n end\n else\n if ~ischar(varargin{3})\n help sdpvar\n error('Third argument should be ''symmetric'', ''full'', ''hermitian'',...See help above')\n end\n index_cmrl = 1;\n end;\n\n if isempty(varargin{3})\n if n==m\n index_type = 7; %Default symmetric\n else\n index_type = 4;\n end\n else\n if ~isempty(strmatch_octavesafe(varargin{3},{'complex','real'}))\n % User had third argument as complex or real\n error(['Third argument should be ''symmetric'', ''full'', ''toeplitz''... Maybe you meant sdpvar(n,n,''full'',''' varargin{3} ''')'])\n end\n index_type = strmatch_octavesafe(varargin{3},{'toeplitz','hankel','symmetric','full','rhankel','skew','hermitian'});\n end\n\n if isempty(index_type)\n error(['Matrix type \"' varargin{3} '\" not supported'])\n else\n switch index_type+100*(index_cmrl-1)\n case 1\n if n~=m\n error('Toeplitz matrix must be square')\n else\n matrix_type = 'toep';\n nvar = n;\n end\n\n case 2\n if n~=m\n error('Hankel matrix must be square')\n else\n matrix_type = 'hank';\n nvar = n;\n end\n\n case 3\n if n~=m\n error('Symmetric matrix must be square')\n else\n matrix_type = 'symm';\n nvar = sum(n.*(n+1)/2);\n end\n\n case 4\n matrix_type = 'full';\n nvar = sum(n.*m);\n if nvar==1\n matrix_type = 'symm';\n end\n\n case 5\n if n~=m\n error('Hankel matrix must be square')\n else\n matrix_type = 'rhankel';\n nvar = 2*n-1;\n end\n\n case 6\n if n~=m\n error('Skew symmetric matrix must be square')\n else\n matrix_type = 'skew';\n nvar = (n*(n+1)/2)-n;\n end\n\n case 7\n if n~=m\n error('Symmetric matrix must be square')\n else\n matrix_type = 'symm';\n nvar = n*(n+1)/2;\n end\n\n case 101\n if n~=m\n error('Toeplitz matrix must be square')\n else\n matrix_type = 'toep complex';\n nvar = 2*n;\n end\n\n case 102\n if n~=m\n error('Hankel matrix must be square')\n else\n matrix_type = 'hank complex';\n nvar = (2*n);\n end\n\n case 103\n if n~=m\n error('Symmetric matrix must be square')\n else\n matrix_type = 'symm complex';\n nvar = 2*n*(n+1)/2;\n end\n\n case 104\n matrix_type = 'full complex';\n nvar = 2*n*m;\n if nvar==1\n matrix_type = 'symm complex';\n end\n\n case 105\n if n~=m\n error('Hankel matrix must be square')\n else\n matrix_type = 'rhankel complex';\n nvar = 2*(2*n-1);\n end\n\n case 106\n if n~=m\n error('Skew symmetric matrix must be square')\n else\n matrix_type = 'skew complex';\n nvar = 2*((n*(n+1)/2)-n);\n end\n\n case 107\n if n~=m\n error('Hermitian matrix must be square')\n else\n matrix_type = 'herm complex';\n nvar = n*(n+1)/2+(n*(n+1)/2-n);\n end\n\n\n otherwise\n error('Bug! Report!');\n end\n\n end\n\n case 5 % Fast version for internal use\n sys.basis = varargin{5};\n sys.lmi_variables=varargin{4};\n sys.dim(1) = varargin{1};\n sys.dim(2) = varargin{2};\n sys.typeflag = 0;\n sys.savedata = [];\n sys.extra = [];\n sys.extra.expanded = [];\n sys.extra.createTime = definecreationtime;\n sys.originalbasis = [];\n sys.leftfactors{1} = [];\n sys.rightfactors{1} = [];\n sys.midfactors{1} = [];\n sys.conicinfo = 0;\n \n % Find zero-variables\n constants = find(sys.lmi_variables==0);\n if ~isempty(constants);\n sys.lmi_variables(constants)=[];\n sys.basis(:,1) = sys.basis(:,1) + sum(sys.basis(:,1+constants),2);\n sys.basis(:,1+constants)=[];\n end\n if isempty(sys.lmi_variables)\n sys = full(reshape(sys.basis(:,1),sys.dim(1),sys.dim(2)));\n else\n sys = class(sys,'sdpvar');\n end\n return\n case 6 % Fast version for internal use\n sys.basis = varargin{5};\n sys.lmi_variables=varargin{4};\n sys.dim(1) = varargin{1};\n sys.dim(2) = varargin{2};\n sys.typeflag = varargin{6};\n sys.savedata = [];\n sys.extra = [];\n sys.extra.expanded = []; \n sys.extra.createTime = definecreationtime;\n sys.conicinfo = 0;\n sys.originalbasis = [];\n sys.leftfactors{1} = [];\n sys.rightfactors{1} = [];\n sys.midfactors{1} = [];\n % Find zero-variables\n constants = find(sys.lmi_variables==0);\n if ~isempty(constants);\n sys.lmi_variables(constants)=[];\n sys.basis(:,1) = sys.basis(:,1) + sum(sys.basis(:,1+constants),2);\n sys.basis(:,1+constants)=[];\n end\n if isempty(sys.lmi_variables)\n sys = full(reshape(sys.basis(:,1),sys.dim(1),sys.dim(2)));\n else\n sys = class(sys,'ncvar');\n end\n return\n case 7 % Fast version for internal use\n sys.basis = varargin{5};\n sys.lmi_variables=varargin{4};\n sys.dim(1) = varargin{1};\n sys.dim(2) = varargin{2};\n sys.typeflag = varargin{6};\n sys.savedata = [];\n sys.extra = varargin{7};\n sys.extra.expanded = []; \n sys.extra.createTime = definecreationtime;\n sys.conicinfo = varargin{7};\n % Find zero-variables\n constants = find(sys.lmi_variables==0);\n if ~isempty(constants);\n sys.lmi_variables(constants)=[];\n sys.basis(:,1) = sys.basis(:,1) + sum(sys.basis(:,1+constants),2);\n sys.basis(:,1+constants)=[];\n end\n if isempty(sys.lmi_variables)\n sys = full(reshape(sys.basis(:,1),sys.dim(1),sys.dim(2)));\n else\n sys = class(sys,'sdpvar');\n end\n return\n\n otherwise\n error('Wrong number of arguments in sdpvar creation');\nend\n\nif isempty(n) | isempty(m)\n error('Size must be integer valued')\nend;\nif ~((abs((n-ceil(n)))+ abs((m-ceil(m))))==0)\n error('Size must be integer valued')\nend\n\nnonCommutingTable = yalmip('nonCommutingTable');\n[monomtable,variabletype] = yalmip('monomtable');\nlmi_variables = (1:nvar)+max(size(nonCommutingTable,1),size(monomtable,1));\n\nfor blk = 1:length(n)\n switch matrix_type\n\n case 'full'\n basis{blk} = [spalloc(n(blk)*m(blk),1,0) speye(n(blk)*m(blk))];%speye(nvar)];\n\n case 'full complex'\n basis = [spalloc(n*m,1,0) speye(nvar/2) speye(nvar/2)*sqrt(-1)];\n\n case 'symm'\n if 0\n basis = spalloc(n^2,1+nvar,n^2);\n l = 2;\n an_empty = spalloc(n,n,2);\n for i=1:n\n temp = an_empty;\n temp(i,i)=1;\n basis(:,l)=temp(:);\n l = l+1;\n for j=i+1:n,\n temp = an_empty;\n temp(i,j)=1;\n temp(j,i)=1;\n basis(:,l)=temp(:);\n l = l+1;\n end\n end\n else\n % Hrm...fast but completely f*d up\n\n Y = reshape(1:n(blk)^2,n(blk),n(blk));\n Y = tril(Y);\n Y = (Y+Y')-diag(sparse(diag(Y)));\n [uu,oo,pp] = unique(Y(:));\n if 1\n basis{blk} = sparse(1:n(blk)^2,pp+1,1);\n else \n basis{blk} = lazybasis(n^2,1+(n*(n+1)/2),1:n(blk)^2,pp+1,ones(n(blk)^2,1));\n end\n \n end\n \n case 'symm complex'\n basis = spalloc(n^2,1+nvar,2);\n l = 2;\n an_empty = spalloc(n,n,2);\n for i=1:n\n temp = an_empty;\n temp(i,i)=1;\n basis(:,l)=temp(:);\n l = l+1;\n for j=i+1:n,\n temp = an_empty;\n temp(i,j)=1;\n temp(j,i)=1;\n basis(:,l)=temp(:);\n l = l+1;\n end\n end\n for i=1:n\n temp = an_empty;\n temp(i,i)=sqrt(-1);\n basis(:,l)=temp(:);\n l = l+1;\n for j=i+1:n,\n temp = an_empty;\n temp(i,j)=sqrt(-1);\n temp(j,i)=sqrt(-1);\n basis(:,l)=temp(:);\n l = l+1;\n end\n end\n\n case 'herm complex'\n basis = spalloc(n^2,1+nvar,2);\n l = 2;\n an_empty = spalloc(n,n,2);\n for i=1:n\n temp = an_empty;\n temp(i,i)=1;\n basis(:,l)=temp(:);\n l = l+1;\n for j=i+1:n,\n temp = an_empty;\n temp(i,j)=1;\n temp(j,i)=1;\n basis(:,l)=temp(:);\n l = l+1;\n end\n end\n for i=1:n\n for j=i+1:n,\n temp = an_empty;\n temp(i,j)=sqrt(-1);\n temp(j,i)=-sqrt(-1);\n basis(:,l)=temp(:);\n l = l+1;\n end\n end\n\n case 'skew'\n basis = spalloc(n^2,1+nvar,2);\n l = 2;\n an_empty = spalloc(n,n,2);\n for i=1:n\n for j=i+1:n,\n temp = an_empty;\n temp(i,j)=1;\n temp(j,i)=-1;\n basis(:,l)=temp(:);\n l = l+1;\n end\n end\n\n case 'skew complex'\n basis = spalloc(n^2,1+nvar,2);\n l = 2;\n an_empty = spalloc(n,n,2);\n for i=1:n\n for j=i+1:n,\n temp = an_empty;\n temp(i,j)=1;\n temp(j,i)=-1;\n basis(:,l)=temp(:);\n l = l+1;\n end\n end\n for i=1:n\n for j=i+1:n,\n temp = an_empty;\n temp(i,j)=sqrt(-1);\n temp(j,i)=-sqrt(-1);\n basis(:,l)=temp(:);\n l = l+1;\n end\n end\n\n case 'toep'\n basis = spalloc(n^2,1+nvar,2);\n an_empty = spalloc(n,1,1);\n for i=1:n,\n v = an_empty;\n v(i)=1;\n temp = sparse(toeplitz(v));\n basis(:,i+1) = temp(:);\n end\n\n % Notice, complex Toeplitz not Hermitian\n case 'toep complex'\n basis = spalloc(n^2,1+nvar,2);\n an_empty = spalloc(n,1,1);\n for i=1:n,\n v = an_empty;\n v(i)=1;\n temp = sparse(toeplitz(v));\n basis(:,i+1) = temp(:);\n end\n for i=1:n,\n v = an_empty;\n v(i)=sqrt(-1);\n temp = sparse(toeplitz(v));\n basis(:,n+i+1) = temp(:);\n end\n\n case 'hank'\n basis = spalloc(n^2,1+nvar,2);\n an_empty = spalloc(n,1,1);\n for i=1:n,\n v = an_empty;\n v(i)=1;\n temp = sparse(hankel(v));\n basis(:,i+1) = temp(:);\n end\n\n case 'hank complex'\n basis = spalloc(n^2,1+nvar,2);\n an_empty = spalloc(n,1,1);\n for i=1:n,\n v = an_empty;\n v(i)=1;\n temp = sparse(hankel(v));\n basis(:,i+1) = temp(:);\n end\n for i=1:n,\n v = an_empty;\n v(i)=sqrt(-1);\n temp = sparse(hankel(v));\n basis(:,n+i+1) = temp(:);\n end\n\n case 'rhankel'\n basis = spalloc(n^2,1+nvar,2);\n an_empty = spalloc(2*n-1,1,1);\n for i=1:nvar,\n v = an_empty;\n v(i)=1;\n temp = sparse(hankel(v(1:n),[v(n);v(n+1:2*n-1)]));\n basis(:,i+1) = temp(:);\n end\n\n case 'rhankel complex'\n basis = spalloc(n^2,1+nvar,2);\n an_empty = spalloc(2*n-1,1,1);\n for i=1:nvar/2,\n v = an_empty;\n v(i)=1;\n temp = sparse(hankel(v(1:n),[v(n);v(n+1:2*n-1)]));\n basis(:,i+1) = temp(:);\n end\n for i=1:nvar/2,\n v = an_empty;\n v(i)=sqrt(-1);\n temp = sparse(hankel(v(1:n),[v(n);v(n+1:2*n-1)]));\n basis(:,nvar/2+i+1) = temp(:);\n end\n\n otherwise\n error('Bug! Report')\n end\n\nend\n\n% Update noncommuting table and monomtables\nnonCommutingTable(lmi_variables,1) = nan;\nnonCommutingTable(lmi_variables,2) = lmi_variables;\nyalmip('nonCommutingTable',nonCommutingTable);\nvariabletype(lmi_variables) = 0;\nmonomtable(lmi_variables(end),lmi_variables(end)) = 0;\nyalmip('setmonomtable',monomtable,variabletype);\n%if strcmp(matrix_type,'NonHermitian')\n% yalmip('setNonHermitianNonCommuting',lmi_variables);\n%end\n\n% Create an object\nif isa(basis,'cell')\n top = 1;\n for blk = 1:length(n)\n sys{blk}.basis=basis{blk};\n nn = size(sys{blk}.basis,2)-1;\n sys{blk}.lmi_variables = lmi_variables(top:top+nn-1);\n top = top + nn;\n sys{blk}.dim(1) = n(blk);\n sys{blk}.dim(2) = m(blk);\n sys{blk}.typeflag = 0;\n sys{blk}.savedata = [];\n sys{blk}.extra = [];\n sys{blk}.extra.expanded = [];\n sys{blk}.extra.createTime = definecreationtime;\n sys{blk}.conicinfo = conicinfo;\n sys{blk}.originalbasis = [];\n sys{blk}.leftfactors{1} = [];\n sys{blk}.rightfactors{1} = [];\n sys{blk}.midfactors{1} = [];\n sys{blk} = class(sys{blk},'ncvar');\n end\n if length(n)==1\n sys = sys{1};\n end\nelse\n sys.basis=basis;\n sys.lmi_variables = lmi_variables;\n sys.dim(1) = n;\n sys.dim(2) = m;\n sys.typeflag = 0;\n sys.savedata = [];\n sys.extra = [];\n sys.extra.expanded = []; \n sys.extra.createTime = definecreationtime;\n sys.conicinfo = conicinfo;\n sys.originalbasis = [];\n sys.leftfactors{1} = [];\n sys.rightfactors{1} = [];\n sys.midfactors{1} = [];\n sys = class(sys,'ncvar');\n if ~isreal(basis)\n % Add internal information about complex pairs\n complex_elements = find(any(imag(basis),2));\n complex_pairs = [];\n for i = 1:length(complex_elements)\n complex_pairs = [complex_pairs;lmi_variables(find(basis(complex_elements(i),:))-1)];\n end\n complex_pairs = uniquesafe(complex_pairs,'rows');\n yalmip('addcomplexpair',complex_pairs);\n end\nend\n", "meta": {"author": "zarathustr", "repo": "LibQPEP", "sha": "99e5c23e746ace0bac4a86742c31db6fcf7297ba", "save_path": "github-repos/MATLAB/zarathustr-LibQPEP", "path": "github-repos/MATLAB/zarathustr-LibQPEP/LibQPEP-99e5c23e746ace0bac4a86742c31db6fcf7297ba/MATLAB/YALMIP/extras/@ncvar/ncvar.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813030761371502, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.34451891767704657}} {"text": "function fem = update10nbr(fem_struct,jj)\n% update10nbr takes a node with 10 elements connected to it \n% (which defines a region) and addes 3 nodes and 6 elements to\n% that region then regroups so that no node has more than six \n% elements connected to it. The new nodes and elements are sprung.\n% \n% NOTE: fem_struct.nei must be a component.\n%\n% Variables\n% fem_struct -- finite element structure from opnml.\n% jj -- the node number that has 10 elements connected to it.\n% fem -- the updated finite element structure.\n% Note: Only fem.x,fem.y,fem.z,fem.e, and fem.nei\n% get updated. fem.bnd does not need to be updated.\n%\n% Usage -- fem = update10nbr(fem_struct,jj)\n%\n% Name: update10nbr.m\n% Written by: Ben Holladay (SEAP Student, 2004)\n% Date: June 22,2004\n% Modified: Aug. 30, 2004 -- Chris Massey\n% Last Modifed: \n% Sept. 19, 2006 -- Chris Massey, NRL Code 7322, S.S.C. MS 39529\n% % Add test to make sure the correct nodal neighbor\n% connectivity existed for the requested update\n% and added a test to create the nodal neighbor list\n% if not present.\n% April 9, 2007 -- Chris Massey, NRL Code 7322\n% Fixed an apparent bug in the code that updates\n% nodal neighbor list. \n% Aug. 13, 2007 -- Chris Massey, NRL Code 7322\n% Fixed a bug in the code that updates nodal neighbor\n% list for nodes getting extra connectivity.\n% July 14, 2008 -- Chris Massey, NRL Code 7322\n% moved test for 4 neighbors to after the test for nei.\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%Checks if the fem_struct has an nei. If not one is generated.\ntry\n nei = fem_struct.nei;\ncatch\n fem_struct.nei = ele2nei(fem_struct.e,fem_struct.x,fem_struct.y);\n nei = fem_struct.nei;\nend\n\ntempnc = sum(~ismember((fem_struct.nei(jj,:)),0));\nif tempnc ~= 10\n error(['There are ',num2str(tempnc),' nodal neighbors for node number ',...\n num2str(jj),'. This routine only works for 10 nodal neighbors.']);\nend\n\n%Sets the intial fem_struct variables.\nx = fem_struct.x;\ny = fem_struct.y;\nz = fem_struct.z;\nenodes = fem_struct.e;\nvod = [1:10,1:10];\n\n%Adds new nodes and elements and labels the bad node, neighboring nodes,\n%and neighboring elements.\n[nnodes,nc] = size(nei);\nnelems = size(enodes,1);\nnewnode = nnodes + [1:3];\nnewelem = nelems + [1:6];\nbadnode = jj;\nnbrnode = nei(jj,1:10);\n[nbrelem,~] = find(enodes == badnode);\ninrad = max(sqrt((x(nbrnode)-x(badnode)).^2 + (y(nbrnode)-y(badnode)).^2));\n\n%First guess of the new coordinates and bathymetry.\nBx = sum(x([(nbrnode([1:4])),badnode]))./5;\nBy = sum(y([(nbrnode([1:4])),badnode]))./5;\nBz = sum(z([(nbrnode([1:4])),badnode]))./5;\n\nDx = sum(x([(nbrnode([6:9])),badnode]))./5;\nDy = sum(y([(nbrnode([6:9])),badnode]))./5;\nDz = sum(z([(nbrnode([6:9])),badnode]))./5;\n\n\nCx = sum([(x([(nbrnode([4:6])),badnode]))',Bx,Dx])./6;\nCy = sum([(y([(nbrnode([4:6])),badnode]))',By,Dy])./6;\nCz = sum([(z([(nbrnode([4:6])),badnode]))',Bz,Dz])./6;\n\nAx = sum([(x([nbrnode([9,10,1])]))',Bx,Dx,Cx])./6;\nAy = sum([(y([nbrnode([9,10,1])]))',By,Dy,Cy])./6;\nAz = sum([(z([nbrnode([9,10,1])]))',Bz,Dz,Cz])./6;\n\nx(badnode) = Ax;\ny(badnode) = Ay;\nz(badnode) = Az;\nx(newnode(1)) = Bx;\ny(newnode(1)) = By;\nz(newnode(1)) = Bz;\nx(newnode(2)) = Cx;\ny(newnode(2)) = Cy;\nz(newnode(2)) = Cz;\nx(newnode(3)) = Dx;\ny(newnode(3)) = Dy;\nz(newnode(3)) = Dz;\n\n%Updates the effected elements. J variables are used to represent which\n%elements are connected each node.\ni = 1;\nwhile i <= 8\n j1 = ismember((enodes((nbrelem),:)),(nbrnode(vod(i))));\n j2 = ismember((enodes((nbrelem),:)),(nbrnode(vod(i+1))));\n spb = [1,1,1,2,2,3,3,3];\n j = sum([j1,j2],2);\n temp = nbrelem(find (j == 2));\n if ~isempty(temp)\n enodes(temp(1),:) = ([nbrnode(vod(i)),nbrnode(vod(i+1)),newnode(spb(i))]);\n end\n i = i + 1;\n clear j j1 j2 temp;\nend\n\n%Addes the 6 new elements.\nenodes(newelem(1),:) = [nbrnode(4),newnode(2),newnode(1)];\nenodes(newelem(2),:) = [badnode,newnode(1),newnode(2)];\nenodes(newelem(3),:) = [nbrnode(1),newnode(1),badnode];\nenodes(newelem(4),:) = [nbrnode(6),newnode(3),newnode(2)];\nenodes(newelem(5),:) = [badnode,newnode(2),newnode(3)];\nenodes(newelem(6),:) = [nbrnode(9),badnode,newnode(3)];\n\n%Springs the region.\nM(1,:) = [Ax,Ay,Az];\nM(2,:) = [Bx,By,Bz];\nM(3,:) = [Cx,Cy,Cz];\nM(4,:) = [Dx,Dy,Dz];\n\nimax = 20;\nstoptol = 10e-8 * inrad;\ni = 1;\ntol = stoptol + 10;\nwhile i <= imax && tol > stoptol\n M2(2,1) = sum([(x([(nbrnode([1:4])),badnode]))',M(3,1)]);\t\n M2(2,2) = sum([(y([(nbrnode([1:4])),badnode]))',M(3,2)]);\n M2(2,3) = sum([(z([(nbrnode([1:4])),badnode]))',M(3,3)]);\n\n M2(4,1) = sum([(x([(nbrnode([6:9])),badnode]))',M(3,1)]);\n M2(4,2) = sum([(y([(nbrnode([6:9])),badnode]))',M(3,2)]);\n M2(4,3) = sum([(z([(nbrnode([6:9])),badnode]))',M(3,3)]);\n\n M2(3,1) = sum([(x([(nbrnode([4:6])),badnode]))',M(2,1),M(4,1)]);\n M2(3,2) = sum([(y([(nbrnode([4:6])),badnode]))',M(2,2),M(4,2)]);\n M2(3,3) = sum([(z([(nbrnode([4:6])),badnode]))',M(2,3),M(4,3)]);\n\n M2(1,1) = sum([(x([nbrnode([9,10,1])]))',M(2,1),M(3,1),M(4,1)]);\n M2(1,2) = sum([(y([nbrnode([9,10,1])]))',M(2,2),M(3,2),M(4,2)]);\n M2(1,3) = sum([(z([nbrnode([9,10,1])]))',M(2,3),M(3,3),M(4,3)]);\n M2 = M2 ./ 6;\n \n tol = max(sqrt((M2(:,1)-M(:,1)).^2 + (M2(:,2)-M(:,2)).^2));\n \n M = M2;\n x([badnode,([newnode(1:3)])]) = ([M(:,1)]);\n y([badnode,([newnode(1:3)])]) = ([M(:,2)]);\n z([badnode,([newnode(1:3)])]) = ([M(:,3)]);\n i = i+1;\nend\n\n%Creates the output structure.\nfem = fem_struct;\nfem.e = enodes;\nfem.x = x;\nfem.y = y;\nfem.z = z;\nfem.nei = nei; \n\n%Update the connectivity for the bad node and adds the connections for \n%the new nodes.\nfem.nei(badnode,1:nc) = ([newnode([1:3]),nbrnode([9,10,1]),zeros(1,nc-6)]);\nfem.nei(newnode(1),1:nc) = ([badnode,nbrnode(1:4),newnode(2),zeros(1,nc-6)]);\nfem.nei(newnode(2),1:nc) = ([badnode,newnode(1),nbrnode(4:6),newnode(3),zeros(1,nc-6)]);\nfem.nei(newnode(3),1:nc) = ([badnode,newnode(2),nbrnode(6:9),zeros(1,nc-6)]);\n\n%Updates the nei for neighbor nodes. These nodes get an additional\n%connector.\nspb = ([1,4,6,9]);\nfor i = 1:4\n addconn = ([badnode,newnode([1:3]),badnode]);\n tmp = nei(nbrnode(spb(i)),:);\n\tij = find(tmp == badnode);\n ik = min((find(tmp == 0)) + 1);\n if isempty(ik) % TCM 08/13/2007 -- Added this check in case ik was empty.\n ik= size(nei,2)+1;\n end\n fem.nei(nbrnode(spb(i)),1:ik) = ([tmp(1:(ij-1)),addconn(i+1),addconn(i),tmp((ij+1):(ik-1))]);\nend\n\n%Updates the nei for neighbor nodes. These nodes get different connector.\nspn = ([2,3,5,7,8]); \nfor i = 1:5\n addnode = ([newnode(1),newnode(1),newnode(2),newnode(3),newnode(3)]);\n tmp = nei(nbrnode(spn(i)),:);\n ij = find(tmp == badnode);\n % TCM 04/09/2007 -- Begin\n tmp2 = ([tmp(1:(ij-1)),addnode(i),tmp((ij+1):end)]);\n fem.nei(nbrnode(spn(i)),:) = 0; %Zero out the list\n fem.nei(nbrnode(spn(i)),1:length(tmp2)) = tmp2; %Fill in the list\n %fem.nei(nbrnode(spn(i)),1:end) = ([tmp(1:(ij-1)),addnode(i),tmp((ij+1):end)]);\n % TCM 04/09/2007 -- End\nend \n\n%Determine the triqual for the final form to see if has very low quality \n%elements.\ntmp1 = (nbrelem);\ntempL3=(fem.x(fem.e(tmp1,1))-fem.x(fem.e(tmp1,2))).^2+(fem.y(fem.e(tmp1,1))-...\n fem.y(fem.e(tmp1,2))).^2;\ntempL1=(fem.x(fem.e(tmp1,2))-fem.x(fem.e(tmp1,3))).^2+(fem.y(fem.e(tmp1,2))-...\n fem.y(fem.e(tmp1,3))).^2;\ntempL2=(fem.x(fem.e(tmp1,3))-fem.x(fem.e(tmp1,1))).^2+(fem.y(fem.e(tmp1,3))-...\n fem.y(fem.e(tmp1,1))).^2;\ntempLs = ([tempL1 + tempL2 + tempL3]);\nxnodes = fem.x(fem.e(tmp1,:));\nynodes = fem.y(fem.e(tmp1,:));\ntemparea = 0.5*(xnodes(:,1).*(ynodes(:,2)-ynodes(:,3))+xnodes(:,2).*...\n (ynodes(:,3)-ynodes(:,1))+xnodes(:,3).*(ynodes(:,1)-ynodes(:,2)));\nfem.ar(tmp1) = temparea;\ntempq = (4 * sqrt(3) * temparea) ./ tempLs;\nclear tempL3 tempL2 tempL1 tempLs xnodes ynodes temparea;\n\nfem1 = fem;\n%Identify very low quality elements and attempts to use a line swap to fix.\npoor = find(tempq < .1);\nnflag = 1;good = 1;\nif ~isempty(poor)\n for it = 1:length(poor)\n je = tmp1(poor(it));\n nodes = fem.e(je,:);\n nflag = 0;\n \n %Determine the angles to see if an edge can be fliped\n a2 = (x(enodes(je,3))-x(enodes(je,2))).^2+(y(enodes(je,3))-y(enodes(je,2))).^2;\n b2 = (x(enodes(je,1))-x(enodes(je,3))).^2+(y(enodes(je,1))-y(enodes(je,3))).^2;\n c2 = (x(enodes(je,2))-x(enodes(je,1))).^2+(y(enodes(je,2))-y(enodes(je,1))).^2;\n A = (180/pi)*acos((b2+c2-a2)./(2*sqrt(b2).*sqrt(c2)));\n B = (180/pi)*acos((c2+a2-b2)./(2*sqrt(c2).*sqrt(a2)));\n C = (180/pi)*acos((a2+b2-c2)./(2*sqrt(a2).*sqrt(b2)));\n [test,ind] = max([A,B,C]);\n if test > 160\n %Find the element numbers to flip the edge.\n nogood = nodes(ind);\n swap = setdiff(nodes,nogood);\n [temp1,tc] = find(enodes == swap(1) | enodes == swap(2));\n [b,j,k] = unique(temp1);\n temp2 = setdiff(1:length(temp1),j);\n swap = temp1(temp2);\n try\n fem1 = line_swap(fem,swap(1),swap(2));\n catch\n fem1 = fem;\n end\n \n %Spring the new mesh after the line swap.\n for itt = 1:2\n temp = find(fem1.nei(newnode(1),:) ~= 0);\n tempnei = fem1.nei(newnode(1),temp);\n fem1.x(newnode(1)) = mean(fem1.x(tempnei));\n fem1.y(newnode(1)) = mean(fem1.y(tempnei));\n fem1.z(newnode(1)) = mean(fem1.z(tempnei));\n temp = find(fem1.nei(newnode(2),:) ~= 0);\n tempnei = fem1.nei(newnode(2),temp);\n fem1.x(newnode(2)) = mean(fem1.x(tempnei));\n fem1.y(newnode(2)) = mean(fem1.y(tempnei));\n fem1.z(newnode(2)) = mean(fem1.z(tempnei));\n temp = find(fem1.nei(newnode(3),:) ~= 0);\n tempnei = fem1.nei(newnode(3),temp);\n fem1.x(newnode(3)) = mean(fem1.x(tempnei));\n fem1.y(newnode(3)) = mean(fem1.y(tempnei));\n fem1.z(newnode(3)) = mean(fem1.z(tempnei));\n temp = find(fem1.nei(badnode,:) ~= 0);\n tempnei = fem1.nei(badnode,temp);\n fem1.x(badnode) = mean(fem1.x(tempnei));\n fem1.y(badnode) = mean(fem1.y(tempnei));\n fem1.z(badnode) = mean(fem1.z(tempnei));\n end\n \n %Use triqual to determine if the new mesh is better quality.\n tmp1 = (nbrelem);\n tempL3=(fem1.x(fem1.e(tmp1,1))-fem1.x(fem1.e(tmp1,2))).^2+(fem1.y(fem1.e(tmp1,1))-...\n fem1.y(fem1.e(tmp1,2))).^2;\n tempL1=(fem1.x(fem1.e(tmp1,2))-fem1.x(fem1.e(tmp1,3))).^2+(fem1.y(fem1.e(tmp1,2))-...\n fem1.y(fem1.e(tmp1,3))).^2;\n tempL2=(fem1.x(fem1.e(tmp1,3))-fem1.x(fem1.e(tmp1,1))).^2+(fem1.y(fem1.e(tmp1,3))-...\n fem1.y(fem1.e(tmp1,1))).^2;\n tempLs = ([tempL1 + tempL2 + tempL3]);\n xnodes = fem1.x(fem1.e(tmp1,:));\n ynodes = fem1.y(fem1.e(tmp1,:));\n temparea = 0.5*(xnodes(:,1).*(ynodes(:,2)-ynodes(:,3))+xnodes(:,2).*...\n (ynodes(:,3)-ynodes(:,1))+xnodes(:,3).*(ynodes(:,1)-ynodes(:,2)));\n fem1.ar(tmp1) = temparea;\n tempq = (4 * sqrt(3) * temparea) ./ tempLs;\n clear tempL3 tempL2 tempL1 tempLs xnodes ynodes temparea;\n if min(tempq) > .4\n fem = fem1;\n nflag = 1;\n else\n nflag = 0;\n good = 6;\n end\n end\n end\nend\n\n% If problems with new mesh, then retriangulate\n\n%Correct output if line swap failed to run\nif sum(nflag) == 0\n fem = patch_update(fem_struct,fem1,jj);\n good = 6;\nend\n\n% Correct output if invalid elements were created.\nif sum(fem.ar < 0) > 0\n fem = patch_update(fem_struct,fem1,jj);\n good = 6;\nend\n\n%Display message if invalid elements where created.\nif good == 6\n disp('The nodally updated mesh contained invalid or badly conditioned');\n disp('elements, therefore the patch was retriangulated which should');\n disp('reduce the connecitivity but is not guaranteed to do so.');\nend\nif sum(fem.ar < 0) > 0\n disp(' ');\n disp('returning original mesh');\n fem = fem_struct;\nend\n\nreturn\n", "meta": {"author": "CHLNDDEV", "repo": "OceanMesh2D", "sha": "56222604a5c1fe897d10c8b08cb3380ef8b43740", "save_path": "github-repos/MATLAB/CHLNDDEV-OceanMesh2D", "path": "github-repos/MATLAB/CHLNDDEV-OceanMesh2D/OceanMesh2D-56222604a5c1fe897d10c8b08cb3380ef8b43740/utilities/Nodal_Reduce_Matlab_Codes/update10nbr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.672331699179286, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.34404329433900654}} {"text": "function [EI,Pth,Qthth] = lme_mass_RgEI1(X,Zcols,W,CBhat,L,phi,ni,G,GDa,GDb)\n% [EI,Pth,Qthth] = lme_mass_RgEI1(X,Zcols,W,CBhat,L,phi,ni,G,GDa,GDb)\n%\n% Expected information matrix of the restricted log-likelihood of a whole\n% region. This is less computationally efficient than lme_mass_RgEI \n% but more numerically stable.\n%\n% Input\n% X: Ordered design Matrix (according to time for each subject).\n% Zcols: Vector with the indices of the colums of X that will be considered\n% as random effects.\n% W: Inverses of the estimated temporal covariance matrices for each \n% subject stacked in W.\n% CBhat: Asymptotic covariance matrix of the fixed effects.\n% L: Cholesky factor of the covariance matrix of the random effects (D).\n% phi: Within-subject standard deviation of the errors.\n% ni: Vector whose entries are the number of repeated measures for each\n% subject in the study (ordered according to X).\n% G: Spatial covariance matrix.\n% GDa: Derivative of the spatial covariance matrix for the first spatial \n% parameter.\n% GDb: Derivative of the spatial covariance matrix for the second spatial \n% parameter (empty for spatial models with a single parameter).\n%\n% Output\n% EI: Expected information matrix.\n% Pth,Qthth: Matrices that are useful for inferences on the fixed effects.\n%\n% $Revision: 1.2 $ $Date: 2015/01/06 17:14:55 $\n% Original Author: Jorge Luis Bernal Rusiel\n% CVS Revision Info:\n% $Author: mreuter $\n% $Date: 2015/01/06 17:14:55 $\n% $Revision: 1.2 $\n% References: Bernal-Rusiel J.L., Greve D.N., Reuter M., Fischl B., Sabuncu\n% M.R., 2012. Statistical Analysis of Longitudinal Neuroimage Data with Linear \n% Mixed Effects Models, NeuroImage, doi:10.1016/j.neuroimage.2012.10.065.\n%\nm = length(ni);\nn = sum(ni);\nnv = size(G,1);\nq = length(Zcols);\nnth = q*(q+1)/2+1;\np = size(X,2);\nPth = zeros(nth,p,p);\nQthth = zeros(nth,nth,p,p);\nDer = zeros(nth,n,max(ni));\n%Computation of the first order derivatives of the temporal covariance matrix\njk = 0;\nfor k=1:q\n for j=1:k\n jk = jk + 1;\n posi = 1;\n for i=1:m\n posf = posi+ni(i)-1;\n Zi = X(posi:posf, Zcols);\n Zki = Zi(:,k); \n Mjki = Zki*L(j,:)*Zi';\n Mjki = Mjki + Mjki'; \n Der(jk,posi:posf,1:ni(i)) = Mjki;\n posi = posf+1;\n end;\n end;\nend;\nposi = 1; \nfor i=1:m\n posf = posi+ni(i)-1;\n Der(nth,posi:posf,1:ni(i)) = 2*phi*eye(ni(i));\n posi = posf+1;\nend;\n%Computation of Pis,Qijs and the expected information matrix EI.\nfor j=1:nth\n posi = 1; Pj = 0;\n Bj = squeeze(Der(j,:,:));\n for i=1:m\n posf = posi+ni(i)-1;\n Wi = W(posi:posf,1:ni(i));\n Pj = Pj - X(posi:posf,:)'*Wi*Bj(posi:posf,1:ni(i))*Wi*X(posi:posf,:);\n posi = posf+1;\n end;\n Pth(j,:,:) = Pj;\nend;\nEI = zeros(nth+2,nth+2);\n%Expected information among Lijs (including phi)\nfor k=1:nth\n Bk = squeeze(Der(k,:,:));\n Pk = squeeze(Pth(k,:,:));\n for j=1:k \n Bj = squeeze(Der(j,:,:));\n Pj = squeeze(Pth(j,:,:));\n posi = 1; Qkj = 0;\n traceBkj = 0; \n for i=1:m\n posf = posi+ni(i)-1;\n Wi = W(posi:posf,1:ni(i));\n Bkji = Wi*Bk(posi:posf,1:ni(i))*Wi*Bj(posi:posf,1:ni(i));\n traceBkj = traceBkj + trace(Bkji); \n Bkji = Bkji*Wi;\n Qkji = X(posi:posf,:)'*Bkji*X(posi:posf,:);\n Qkj = Qkj + Qkji;\n posi = posf+1;\n end;\n Qthth(k,j,:,:) = Qkj;\n Qthth(j,k,:,:) = Qkj;\n EI(k,j) = nv*(traceBkj - trace(CBhat*(2*Qkj-Pk*CBhat*Pj)));\n EI(j,k) = EI(k,j);\n end;\nend;\n%Expected information between Lijs (including phi) and a (first spatial parameter)\nMauxa = G\\GDa;\ntrMauxa = trace(Mauxa);\nfor k=1:nth\n Bk = squeeze(Der(k,:,:));\n Pk = squeeze(Pth(k,:,:));\n posi = 1; \n traceBk = 0;\n for i=1:m\n posf = posi+ni(i)-1;\n Wi = W(posi:posf,1:ni(i));\n Bki = Wi*Bk(posi:posf,1:ni(i));\n traceBk = traceBk + trace(Bki); \n posi = posf+1;\n end;\n EI(k,nth+1) = trMauxa*(traceBk + trace(CBhat*Pk));\n EI(nth+1,k) = EI(k,nth+1);\nend\n%Expected information between a and a\nEI(nth+1,nth+1) = (n-p)*trace(Mauxa*Mauxa);\nif ~isempty(GDb)\n %Expected information between Lijs (including phi) and b (second spatial parameter)\n Mauxb = G\\GDb;\n trMauxb = trace(Mauxb);\n for k=1:nth\n Bk = squeeze(Der(k,:,:));\n Pk = squeeze(Pth(k,:,:));\n posi = 1;\n traceBk = 0;\n for i=1:m\n posf = posi+ni(i)-1;\n Wi = W(posi:posf,1:ni(i));\n Bki = Wi*Bk(posi:posf,1:ni(i));\n traceBk = traceBk + trace(Bki);\n posi = posf+1;\n end;\n EI(k,nth+2) = trMauxb*(traceBk + trace(CBhat*Pk));\n EI(nth+2,k) = EI(k,nth+2);\n end\n %Expected information between b and b\n EI(nth+2,nth+2) = (n-p)*trace(Mauxb*Mauxb);\n %Expected information between a and b\n EI(nth+1,nth+2) = (n-p)*trace(Mauxa*Mauxb);\n EI(nth+2,nth+1) = EI(nth+1,nth+2);\nelse\n EI = EI(1:nth+1,1:nth+1);\nend;\nEI = 0.5*EI;\n\n\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/external/freesurfer/lme/mass_univariate/lme_mass_RgEI1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7217432182679957, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.3439681311197359}} {"text": "function U = som_umat(sMap, varargin)\n\n%SOM_UMAT Compute unified distance matrix of self-organizing map.\n%\n% U = som_umat(sMap, [argID, value, ...])\n%\n% U = som_umat(sMap); \n% U = som_umat(M,sTopol,'median','mask',[1 1 0 1]);\n%\n% Input and output arguments ([]'s are optional): \n% sMap (struct) map struct or\n% (matrix) the codebook matrix of the map\n% [argID, (string) See below. The values which are unambiguous can \n% value] (varies) be given without the preceeding argID.\n%\n% U (matrix) u-matrix of the self-organizing map \n%\n% Here are the valid argument IDs and corresponding values. The values which\n% are unambiguous (marked with '*') can be given without the preceeding argID.\n% 'mask' (vector) size dim x 1, weighting factors for different \n% components (same as BMU search mask)\n% 'msize' (vector) map grid size\n% 'topol' *(struct) topology struct\n% 'som_topol','sTopol' = 'topol'\n% 'lattice' *(string) map lattice, 'hexa' or 'rect'\n% 'mode' *(string) 'min','mean','median','max', default is 'median'\n%\n% NOTE! the U-matrix is always calculated for 'sheet'-shaped map and\n% the map grid must be at most 2-dimensional.\n% \n% For more help, try 'type som_umat' or check out online documentation.\n% See also SOM_SHOW, SOM_CPLANE.\n\n%%%%%%%%%%%%% DETAILED DESCRIPTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% som_umat\n%\n% PURPOSE\n%\n% Computes the unified distance matrix of a SOM.\n%\n% SYNTAX\n%\n% U = som_umat(sM) \n% U = som_umat(...,'argID',value,...)\n% U = som_umat(...,value,...)\n%\n% DESCRIPTION\n%\n% Compute and return the unified distance matrix of a SOM. \n% For example a case of 5x1 -sized map:\n% m(1) m(2) m(3) m(4) m(5)\n% where m(i) denotes one map unit. The u-matrix is a 9x1 vector:\n% u(1) u(1,2) u(2) u(2,3) u(3) u(3,4) u(4) u(4,5) u(5) \n% where u(i,j) is the distance between map units m(i) and m(j)\n% and u(k) is the mean (or minimum, maximum or median) of the \n% surrounding values, e.g. u(3) = (u(2,3) + u(3,4))/2. \n%\n% Note that the u-matrix is always calculated for 'sheet'-shaped map and\n% the map grid must be at most 2-dimensional.\n%\n% REFERENCES\n%\n% Ultsch, A., Siemon, H.P., \"Kohonen's Self-Organizing Feature Maps\n% for Exploratory Data Analysis\", in Proc. of INNC'90,\n% International Neural Network Conference, Dordrecht,\n% Netherlands, 1990, pp. 305-308.\n% Kohonen, T., \"Self-Organizing Map\", 2nd ed., Springer-Verlag, \n% Berlin, 1995, pp. 117-119. \n% Iivarinen, J., Kohonen, T., Kangas, J., Kaski, S., \"Visualizing \n% the Clusters on the Self-Organizing Map\", in proceedings of\n% Conference on Artificial Intelligence Research in Finland,\n% Helsinki, Finland, 1994, pp. 122-126.\n% Kraaijveld, M.A., Mao, J., Jain, A.K., \"A Nonlinear Projection\n% Method Based on Kohonen's Topology Preserving Maps\", IEEE\n% Transactions on Neural Networks, vol. 6, no. 3, 1995, pp. 548-559.\n% \n% REQUIRED INPUT ARGUMENTS\n%\n% sM (struct) SOM Toolbox struct or the codebook matrix of the map.\n% (matrix) The matrix may be 3-dimensional in which case the first \n% two dimensions are taken for the map grid dimensions (msize).\n%\n% OPTIONAL INPUT ARGUMENTS\n%\n% argID (string) Argument identifier string (see below).\n% value (varies) Value for the argument (see below).\n%\n% The optional arguments are given as 'argID',value -pairs. If the \n% value is unambiguous, it can be given without the preceeding argID.\n% If an argument is given value multiple times, the last one is used. \n%\n% Below is the list of valid arguments: \n% 'mask' (vector) mask to be used in calculating\n% the interunit distances, size [dim 1]. Default is \n% the one in sM (field sM.mask) or a vector of\n% ones if only a codebook matrix was given.\n% 'topol' (struct) topology of the map. Default is the one\n% in sM (field sM.topol).\n% 'sTopol','som_topol' (struct) = 'topol'\n% 'msize' (vector) map grid dimensions\n% 'lattice' (string) map lattice 'rect' or 'hexa'\n% 'mode' (string) 'min', 'mean', 'median' or 'max'\n% Map unit value computation method. In fact, \n% eval-function is used to evaluate this, so \n% you can give other computation methods as well.\n% Default is 'median'. \n%\n% OUTPUT ARGUMENTS\n%\n% U (matrix) the unified distance matrix of the SOM \n% size 2*n1-1 x 2*n2-1, where n1 = msize(1) and n2 = msize(2)\n%\n% EXAMPLES\n%\n% U = som_umat(sM); \n% U = som_umat(sM.codebook,sM.topol,'median','mask',[1 1 0 1]);\n% U = som_umat(rand(10,10,4),'hexa','rect'); \n% \n% SEE ALSO\n%\n% som_show show the selected component planes and the u-matrix\n% som_cplane draw a 2D unified distance matrix\n\n% Copyright (c) 1997-2000 by the SOM toolbox programming team.\n% http://www.cis.hut.fi/projects/somtoolbox/\n\n% Version 1.0beta juuso 260997\n% Version 2.0beta juuso 151199, 151299, 200900\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% check arguments\n\nerror(nargchk(1, Inf, nargin)); % check no. of input arguments is correct\n\n% sMap\nif isstruct(sMap), \n M = sMap.codebook;\n sTopol = sMap.topol; \n mask = sMap.mask;\nelseif isnumeric(sMap),\n M = sMap; \n si = size(M);\n dim = si(end);\n if length(si)>2, msize = si(1:end-1);\n else msize = [si(1) 1];\n end\n munits = prod(msize);\n sTopol = som_set('som_topol','msize',msize,'lattice','rect','shape','sheet'); \n mask = ones(dim,1);\n M = reshape(M,[munits,dim]);\nend\nmode = 'median';\n\n% varargin\ni=1; \nwhile i<=length(varargin), \n argok = 1; \n if ischar(varargin{i}), \n switch varargin{i}, \n % argument IDs\n case 'mask', i=i+1; mask = varargin{i}; \n case 'msize', i=i+1; sTopol.msize = varargin{i}; \n case 'lattice', i=i+1; sTopol.lattice = varargin{i};\n case {'topol','som_topol','sTopol'}, i=i+1; sTopol = varargin{i};\n case 'mode', i=i+1; mode = varargin{i};\n % unambiguous values\n case {'hexa','rect'}, sTopol.lattice = varargin{i};\n case {'min','mean','median','max'}, mode = varargin{i};\n otherwise argok=0; \n end\n elseif isstruct(varargin{i}) && isfield(varargin{i},'type'), \n switch varargin{i}(1).type, \n case 'som_topol', sTopol = varargin{i};\n case 'som_map', sTopol = varargin{i}.topol;\n otherwise argok=0; \n end\n else\n argok = 0; \n end\n if ~argok, \n disp(['(som_umat) Ignoring invalid argument #' num2str(i+1)]); \n end\n i = i+1; \nend\n\n% check\n[munits dim] = size(M);\nif prod(sTopol.msize)~=munits, \n error('Map grid size does not match the number of map units.')\nend\nif length(sTopol.msize)>2, \n error('Can only handle 1- and 2-dimensional map grids.')\nend\nif prod(sTopol.msize)==1,\n warning('Only one codebook vector.'); U = []; return;\nend\nif ~strcmp(sTopol.shape,'sheet'), \n disp(['The ' sTopol.shape ' shape of the map ignored. Using sheet instead.']);\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% initialize variables\n\ny = sTopol.msize(1);\nx = sTopol.msize(2);\nlattice = sTopol.lattice;\nshape = sTopol.shape;\nM = reshape(M,[y x dim]);\n\nux = 2 * x - 1; \nuy = 2 * y - 1;\nU = zeros(uy, ux);\n\ncalc = sprintf('%s(a)',mode);\n\nif size(mask,2)>1, mask = mask'; end\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% u-matrix computation\n\n% distances between map units\n\nif strcmp(lattice, 'rect'), % rectangular lattice\n \n for j=1:y, for i=1:x,\n if i1,\n\t dz = (M(j,i,:) - M(j+1,i-1,:)).^2; \n\t U(2*j,2*i-2) = sqrt(mask'*dz(:));\n\tend\n end\n end\n end\n \nend\n\n% values on the units\n\nif (uy == 1 || ux == 1),\n % in 1-D case, mean is equal to median \n\n ma = max([ux uy]);\n for i = 1:2:ma,\n if i>1 && i1 && j>1 && i1 && i1 && i1 && j1 && j1 && j>1 && i1 && i1 && i1 && j1 && j 0, U = U / ma; end\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\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/som/som_umat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.3439531166114479}} {"text": "function [Eft, Varft, lpyt, Eyt, Varyt] = gpep_pred(gp, x, y, varargin)\n%GPEP_PRED Predictions with Gaussian Process EP approximation\n%\n% Description\n% [EFT, VARFT] = GPEP_PRED(GP, X, Y, XT, OPTIONS)\n% takes a GP structure together with matrix X of training\n% inputs and vector Y of training targets, and evaluates the\n% predictive distribution at test inputs XT. Returns a posterior\n% mean EFT and variance VARFT of latent variables.\n%\n% [EFT, VARFT, LPYT] = GPEP_PRED(GP, X, Y, XT, 'yt', YT, OPTIONS)\n% returns also logarithm of the predictive density LPYT of the\n% observations YT at test input locations XT. This can be used\n% for example in the cross-validation. Here Y has to be a vector.\n%\n% [EFT, VARFT, LPYT, EYT, VARYT] = GPEP_PRED(GP, X, Y, XT, OPTIONS)\n% returns also the posterior predictive mean EYT and variance VARYT.\n%\n% [EF, VARF, LPY, EY, VARY] = GPEP_PRED(GP, X, Y, OPTIONS)\n% evaluates the predictive distribution at training inputs X\n% and logarithm of the predictive density LPY of the training\n% observations Y.\n%\n% OPTIONS is optional parameter-value pair\n% predcf - an index vector telling which covariance functions are\n% used for prediction. Default is all (1:gpcfn).\n% See additional information below.\n% tstind - a vector/cell array defining, which rows of X belong\n% to which training block in *IC type sparse models.\n% Default is []. In case of PIC, a cell array\n% containing index vectors specifying the blocking\n% structure for test data. IN FIC and CS+FIC a\n% vector of length n that points out the test inputs\n% that are also in the training set (if none, set\n% TSTIND = [])\n% yt - optional observed yt in test points (see below)\n% z - optional observed quantity in triplet (x_i,y_i,z_i)\n% Some likelihoods may use this. For example, in case of\n% Poisson likelihood we have z_i=E_i, that is, expected value\n% for ith case.\n% zt - optional observed quantity in triplet (xt_i,yt_i,zt_i)\n% Some likelihoods may use this. For example, in case of\n% Poisson likelihood we have z_i=E_i, that is, the expected\n% value for the ith case.\n% fcorr - Method used for latent marginal posterior corrections. \n% Default is 'off'. For EP possible method is 'fact'.\n% If method is 'on', 'fact' is used for EP.\n%\n% NOTE! In case of FIC and PIC sparse approximation the\n% prediction for only some PREDCF covariance functions is just\n% an approximation since the covariance functions are coupled in\n% the approximation and are not strictly speaking additive\n% anymore.\n%\n% For example, if you use covariance such as K = K1 + K2 your\n% predictions Eft1 = gpep_pred(GP, X, Y, X, 'predcf', 1) and\n% Eft2 = gpep_pred(gp, x, y, x, 'predcf', 2) should sum up to\n% Eft = gpep_pred(gp, x, y, x). That is Eft = Eft1 + Eft2. With\n% FULL model this is true but with FIC and PIC this is true only\n% approximately. That is Eft \\approx Eft1 + Eft2.\n%\n% With CS+FIC the predictions are exact if the PREDCF covariance\n% functions are all in the FIC part or if they are CS\n% covariances.\n%\n% NOTE! When making predictions with a subset of covariance\n% functions with FIC approximation the predictive variance can\n% in some cases be ill-behaved i.e. negative or unrealistically\n% small. This may happen because of the approximative nature of\n% the prediction.\n%\n% See also\n% GPEP_E, GPEP_G, GP_PRED, DEMO_SPATIAL, DEMO_CLASSIFIC\n\n% Copyright (c) 2007-2010 Jarno Vanhatalo\n% Copyright (c) 2010 Heikki Peura\n% Copyright (c) 2011 Pasi Jylänki\n% Copyright (c) 2012 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 = 'GPEP_PRED';\n ip.addRequired('gp', @isstruct);\n ip.addRequired('x', @(x) ~isempty(x) && isreal(x) && all(isfinite(x(:))))\n ip.addRequired('y', @(x) ~isempty(x) && isreal(x) && all(isfinite(x(:))))\n ip.addOptional('xt', [], @(x) isempty(x) || (isreal(x) && all(isfinite(x(:)))))\n ip.addParamValue('yt', [], @(x) isreal(x) && all(isfinite(x(:))))\n ip.addParamValue('z', [], @(x) isreal(x) && all(isfinite(x(:))))\n ip.addParamValue('zt', [], @(x) isreal(x) && all(isfinite(x(:))))\n ip.addParamValue('predcf', [], @(x) isempty(x) || ...\n isvector(x) && isreal(x) && all(isfinite(x)&x>0))\n ip.addParamValue('tstind', [], @(x) isempty(x) || iscell(x) ||...\n (isvector(x) && isreal(x) && all(isfinite(x)&x>0)))\n ip.addParamValue('fcorr', 'off', @(x) ismember(x, {'off', ...\n 'cm2', 'fact', 'on','lr'}))\n if numel(varargin)==0 || isnumeric(varargin{1})\n % inputParser should handle this, but it doesn't\n ip.parse(gp, x, y, varargin{:});\n else\n ip.parse(gp, x, y, [], varargin{:});\n end\n xt=ip.Results.xt;\n yt=ip.Results.yt;\n z=ip.Results.z;\n zt=ip.Results.zt;\n predcf=ip.Results.predcf;\n tstind=ip.Results.tstind;\n fcorr=ip.Results.fcorr;\n if isempty(xt)\n xt=x;\n if isempty(tstind)\n if iscell(gp)\n gptype=gp{1}.type;\n else\n gptype=gp.type;\n end\n switch gptype\n case {'FULL' 'VAR' 'DTC' 'SOR'}\n tstind = [];\n case {'FIC' 'CS+FIC'}\n tstind = 1:size(x,1);\n case 'PIC'\n if iscell(gp)\n tstind = gp{1}.tr_index;\n else\n tstind = gp.tr_index;\n end\n end\n end\n if isempty(yt)\n yt=y;\n end\n if isempty(zt)\n zt=z;\n end\n end\n\n \n if isfield(gp, 'monotonic') && gp.monotonic\n [gp,x,y,z,xt,zt] = gp.fh.setUpDataForMonotonic(gp,x,y,z,xt,zt);\n end\n \n [tn, tnin] = size(x);\n [n, nout] = size(y);\n\n if isfield(gp.lik, 'nondiagW')\n switch gp.type\n % ============================================================\n % FULL\n % ============================================================\n case 'FULL'\n %[e, edata, eprior, tautilde, nutilde, BKnu, B, cholP, invPBKnu]= gpep_e(gp_pak(gp), gp, x, y, 'z', z);\n [e, edata, eprior, p]= gpep_e(gp_pak(gp), gp, x, y, 'z', z);\n if isnan(e)\n Eft=NaN; Varft=NaN; lpyt=NaN; Eyt=NaN; Varyt=NaN;\n return\n end\n [nutilde, BKnu, B, cholP, invPBKnu]=deal(p.nutilde, p.BKnu, p.B, p.cholP, p.invPBKnu);\n \n if isfield(gp, 'comp_cf') % own covariance for each ouput component\n multicf = true;\n if length(gp.comp_cf) ~= nout\n error('GPEP_PRED: the number of component vectors in gp.comp_cf must be the same as number of outputs.')\n end\n if ~isempty(predcf)\n if ~iscell(predcf) || length(predcf)~=nout\n error(['GPEP_PRED: if own covariance for each output component is used,'...\n 'predcf has to be cell array and contain nout (vector) elements. '])\n end\n else\n predcf = gp.comp_cf;\n end\n else\n multicf = false;\n for i1=1:nout\n predcf2{i1} = predcf;\n end\n predcf=predcf2;\n end\n \n ntest=size(xt,1);\n % covariances between the training and test latents\n Kt = zeros(ntest,n,nout);\n if multicf\n for i1=1:nout\n Kt(:,:,i1) = gp_cov(gp,xt,x,predcf{i1});\n end\n else\n for i1=1:nout\n Kt(:,:,i1) = gp_cov(gp,xt,x,predcf{i1});\n end\n end\n \n % full ep with non-diagonal site covariances\n zz=zeros(n*nout,1);\n for k1=1:nout\n zz((1:n)+(k1-1)*n)=BKnu(:,k1)-B(:,:,k1)*invPBKnu;\n end\n \n \n %- posterior predictive mean\n Eft=zeros(ntest*nout,1);\n for z1=1:nout\n Eft((1:ntest)+(z1-1)*ntest)=Kt(:,:,z1)*(nutilde(:,z1)-zz((1:n)+(z1-1)*n));\n end\n \n if nargout > 1\n % posterior predictive covariance\n Covf=zeros(nout, nout, ntest);\n \n invcholPBKt=zeros(n,ntest,nout);\n for k1=1:nout\n invcholPBKt(:,:,k1)=cholP\\(B(:,:,k1)*Kt(:,:,k1)');\n end\n \n %- update posterior covariance\n for k1=1:nout\n % covariances for the test latents\n kstarstar = gp_trvar(gp,xt,predcf{i1});\n \n Covf(k1,k1,:)=kstarstar-sum(Kt(:,:,k1)'.*(B(:,:,k1)*Kt(:,:,k1)'))'+sum(invcholPBKt(:,:,k1).*invcholPBKt(:,:,k1))';\n for j1=(k1+1):nout\n Covf(k1,j1,:)=sum(invcholPBKt(:,:,k1).*invcholPBKt(:,:,j1));\n Covf(j1,k1,:)=Covf(k1,j1,:);\n end\n end\n Varft=Covf;\n \n end\n \n % ============================================================\n % FIC\n % ============================================================\n case 'FIC' % Predictions with FIC sparse approximation for GP\n % ============================================================\n % PIC\n % ============================================================\n case {'PIC' 'PIC_BLOCK'} % Predictions with PIC sparse approximation for GP\n % ============================================================\n % CS+FIC\n % ============================================================\n case 'CS+FIC' % Predictions with CS+FIC sparse approximation for GP\n end\n \n else % isfield(gp.lik, 'nondiagW')\n switch gp.type\n % ============================================================\n % FULL\n % ============================================================\n case 'FULL' % Predictions with FULL GP model\n %[e, edata, eprior, tautilde, nutilde, L] = gpep_e(gp_pak(gp), gp, x, y, 'z', z);\n if isfield(gp.lik, 'int_likparam')\n \n [e, edata, eprior, p] = gpep_e(gp_pak(gp), gp, x, y, 'z', z);\n if isnan(e)\n Eft=NaN; Varft=NaN; lpyt=NaN; Eyt=NaN; Varyt=NaN;\n return\n end\n [tautildee, nutildee, L, L2] = deal(p.tautilde, p.nutilde, p.L, p.La2);\n \n tautilde=tautildee(:,1);\n nutilde=nutildee(:,1);\n if isfield(gp.lik,'int_likparam') && gp.lik.int_likparam && ~gp.lik.inputparam\n % Give q(theta) to likelihood function to integrate ovet \n zt=[p.mf2 L2'*L2];\n end\n if isfield(gp.lik, 'int_magnitude') && gp.lik.int_magnitude && ~gp.lik.inputmagnitude\n zt=[zt p.mf3 p.La3'*p.La3];\n end\n if (isfield(gp.lik, 'int_likparam') && gp.lik.inputparam) || ...\n (isfield(gp.lik, 'int_magnitude') && gp.lik.inputmagnitude) ...\n || (isfield(gp.lik, 'int_likparam') && isfield(gp, 'comp_cf'))\n [K,C]=gp_trcov(gp,x,gp.comp_cf{1});\n kstarstar = gp_trvar(gp, xt, gp.comp_cf{1});\n K_nf=gp_cov(gp,xt,x,gp.comp_cf{1});\n else\n [K, C]=gp_trcov(gp,x);\n kstarstar = gp_trvar(gp, xt, predcf);\n K_nf=gp_cov(gp,xt,x,predcf);\n end\n ntest=size(xt,1);\n [n,nin] = size(x);\n \n if size(tautildee,2)==1 && all(tautilde > 0) && ~isequal(gp.latent_opt.optim_method, 'robust-EP')\n % This is the usual case where likelihood is log concave\n % for example, Poisson and probit\n sqrttautilde = sqrt(tautilde(:,1));\n Stildesqroot = sparse(1:n, 1:n, sqrttautilde, n, n);\n \n if ~isfield(gp,'meanf')\n if issparse(L) % If compact support covariance functions are used\n % the covariance matrix will be sparse\n zz=Stildesqroot*ldlsolve(L,Stildesqroot*(C*nutilde));\n else\n zz=Stildesqroot*(L'\\(L\\(Stildesqroot*(C*nutilde))));\n end\n Eft=K_nf*(nutilde-zz); % The mean, zero mean GP\n else\n zz = Stildesqroot*(L'\\(L\\(Stildesqroot*(C))));\n \n Eft_zm=K_nf*(nutilde-zz*nutilde); % The mean, zero mean GP\n Ks = eye(size(zz)) - zz; % inv(K + S^-1)*S^-1\n Ksy = Ks*nutilde;\n [RB RAR] = mean_predf(gp,x,xt,K_nf',Ks,Ksy,'EP',Stildesqroot.^2);\n \n Eft = Eft_zm + RB; % The mean\n end\n \n % Compute variance\n if nargout > 1\n if issparse(L)\n V = ldlsolve(L, Stildesqroot*K_nf');\n Varft = kstarstar - sum(K_nf.*(Stildesqroot*V)',2);\n else\n V = (L\\Stildesqroot)*K_nf';\n Varft = kstarstar - sum(V.^2)';\n end\n if isfield(gp,'meanf')\n Varft = Varft + RAR;\n end\n end\n else\n % We might end up here if the likelihood is not log concave\n % For example Student-t likelihood.\n \n %{\n zz=tautilde.*(L'*(L*nutilde));\n Eft=K_nf*(nutilde-zz);\n \n if nargout > 1\n S = diag(tautilde);\n V = K_nf*S*L';\n Varft = kstarstar - sum((K_nf*S).*K_nf,2) + sum(V.^2,2);\n end\n %}\n \n % An alternative implementation for avoiding negative variances\n [Eft,V]=pred_var(tautilde,K,K_nf,nutilde);\n Varft=kstarstar-V;\n \n end\n if isfield(gp.lik, 'int_likparam') && gp.lik.int_likparam && gp.lik.inputparam\n tautilde=tautildee(:,2);\n nutilde=nutildee(:,2);\n [K, C]=gp_trcov(gp,x, gp.comp_cf{2});\n kstarstar = gp_trvar(gp, xt, gp.comp_cf{2});\n K_nf=gp_cov(gp,xt,x,gp.comp_cf{2});\n \n [Eft(:,2),V]=pred_var(tautilde,K,K_nf,nutilde);\n Varft(:,2)=kstarstar-V; \n end\n if isfield(gp.lik, 'int_magnitude') && gp.lik.int_magnitude && gp.lik.inputmagnitude\n tautilde=tautildee(:,end);\n nutilde=nutildee(:,end);\n [K, C]=gp_trcov(gp,x, gp.comp_cf{end});\n kstarstar = gp_trvar(gp, xt, gp.comp_cf{end});\n K_nf=gp_cov(gp,xt,x,gp.comp_cf{end});\n \n [Eft(:,end+1),V]=pred_var(tautilde,K,K_nf,nutilde);\n Varft(:,end+1)=kstarstar-V; \n end\n \n else % isfield(gp.lik, 'int_likparam')\n \n [e, edata, eprior, p] = gpep_e(gp_pak(gp), gp, x, y, 'z', z);\n if isnan(e)\n Eft=NaN; Varft=NaN; lpyt=NaN; Eyt=NaN; Varyt=NaN;\n return\n end\n [tautilde, nutilde, L] = deal(p.tautilde, p.nutilde, p.L);\n \n [K, C]=gp_trcov(gp,x);\n kstarstar = gp_trvar(gp, xt, predcf);\n ntest=size(xt,1);\n K_nf=gp_cov(gp,xt,x,predcf);\n [n,nin] = size(x);\n \n if all(tautilde > 0) ... \n && ~(isequal(gp.latent_opt.optim_method, 'robust-EP') )\n % This is the usual case where likelihood is log concave\n % for example, Poisson and probit\n sqrttautilde = sqrt(tautilde);\n nstt=length(sqrttautilde);\n Stildesqroot = sparse(1:nstt, 1:nstt, sqrttautilde, nstt, nstt);\n \n if ~isfield(gp,'meanf')\n if issparse(L) % If compact support covariance functions a re used\n % the covariance matrix will be sparse\n zz=Stildesqroot*ldlsolve(L,Stildesqroot*(C*nutilde));\n else\n zz=Stildesqroot*(L'\\(L\\(Stildesqroot*(C*nutilde))));\n end\n \n Eft=K_nf*(nutilde-zz); % The mean, zero mean GP\n else\n zz = Stildesqroot*(L'\\(L\\(Stildesqroot*(C))));\n \n Eft_zm=K_nf*(nutilde-zz*nutilde); % The mean, zero mean GP\n Ks = eye(size(zz)) - zz; % inv(K + S^-1)*S^-1\n Ksy = Ks*nutilde;\n [RB RAR] = mean_predf(gp,x,xt,K_nf',Ks,Ksy,'EP',Stildesqroot.^2);\n \n Eft = Eft_zm + RB; % The mean\n end\n \n % Compute variance\n if nargout > 1\n if issparse(L)\n V = ldlsolve(L, Stildesqroot*K_nf');\n Varft = kstarstar - sum(K_nf.*(Stildesqroot*V)',2);\n else\n V = (L\\Stildesqroot)*K_nf';\n Varft = kstarstar - sum(V.^2)';\n end\n if isfield(gp,'meanf')\n Varft = Varft + RAR;\n end\n end\n else\n % We might end up here if the likelihood is not log concave\n % For example Student-t likelihood.\n \n %{\n zz=tautilde.*(L'*(L*nutilde));\n Eft=K_nf*(nutilde-zz);\n \n if nargout > 1\n S = diag(tautilde);\n V = K_nf*S*L';\n Varft = kstarstar - sum((K_nf*S).*K_nf,2) + sum(V.^2,2);\n end\n %}\n \n % An alternative implementation for avoiding negative variances\n [Eft,V]=pred_var(tautilde,K,K_nf,nutilde);\n Varft=kstarstar-V; \n \n end\n \n end % isfield(gp.lik, 'int_likparam')\n % ============================================================\n % FIC\n % ============================================================\n case 'FIC' % Predictions with FIC sparse approximation for GP\n %[e, edata, eprior, tautilde, nutilde, L, La, b] = gpep_e(gp_pak(gp), gp, x, y, 'z', z);\n [e, edata, eprior, p] = gpep_e(gp_pak(gp), gp, x, y, 'z', z);\n if isnan(e)\n Eft=NaN; Varft=NaN; lpyt=NaN; Eyt=NaN; Varyt=NaN;\n return\n end\n [tautilde, nutilde, L, La, b] = deal(p.tautilde, p.nutilde, p.L, p.La2, p.b);\n \n % Here tstind = 1 if the prediction is made for the training set\n if nargin > 6\n if ~isempty(tstind) && length(tstind) ~= size(x,1)\n error('tstind (if provided) has to be of same length as x.')\n end\n else\n tstind = [];\n end\n \n u = gp.X_u;\n m = size(u,1);\n \n K_fu = gp_cov(gp,x,u,predcf); % f x u\n K_nu=gp_cov(gp,xt,u,predcf);\n K_uu = gp_trcov(gp,u,predcf); % u x u, noiseless covariance K_uu\n K_uu = (K_uu+K_uu')./2; % ensure the symmetry of K_uu\n \n kstarstar=gp_trvar(gp,xt,predcf);\n \n if all(tautilde > 0) && ~isequal(gp.latent_opt.optim_method, 'robust-EP')\n \n % From this on evaluate the prediction\n % See Snelson and Ghahramani (2007) for details\n % p=iLaKfu*(A\\(iLaKfu'*mutilde));\n p = b';\n \n ntest=size(xt,1);\n \n Eft = K_nu*(K_uu\\(K_fu'*p));\n \n % if the prediction is made for training set, evaluate Lav also for prediction points\n if ~isempty(tstind)\n [Kv_ff, Cv_ff] = gp_trvar(gp, xt(tstind,:), predcf);\n Luu = chol(K_uu)';\n B=Luu\\(K_fu');\n Qv_ff=sum(B.^2)';\n Lav = Kv_ff-Qv_ff;\n Eft(tstind) = Eft(tstind) + Lav.*p;\n end\n \n % Compute variance\n if nargout > 1\n %Varft(i1,1)=kstarstar(i1) - (sum(Knf(i1,:).^2./La') - sum((Knf(i1,:)*L).^2));\n Luu = chol(K_uu)';\n B=Luu\\(K_fu');\n B2=Luu\\(K_nu');\n Varft = kstarstar - sum(B2'.*(B*(repmat(La,1,m).\\B')*B2)',2) + sum((K_nu*(K_uu\\(K_fu'*L))).^2, 2);\n \n % if the prediction is made for training set, evaluate Lav also for prediction points\n if ~isempty(tstind)\n Varft(tstind) = Varft(tstind) - 2.*sum( B2(:,tstind)'.*(repmat((La.\\Lav),1,m).*B'),2) ...\n + 2.*sum( B2(:,tstind)'*(B*L).*(repmat(Lav,1,m).*L), 2) ...\n - Lav./La.*Lav + sum((repmat(Lav,1,m).*L).^2,2);\n end\n end\n \n else\n % Robust-EP\n [Eft,V]=pred_var2(tautilde,nutilde,L,K_uu,K_fu,b,K_nu);\n Varft=kstarstar-V;\n \n end\n \n \n % ============================================================\n % PIC\n % ============================================================\n case {'PIC' 'PIC_BLOCK'} % Predictions with PIC sparse approximation for GP\n % Calculate some help matrices\n u = gp.X_u;\n ind = gp.tr_index;\n %[e, edata, eprior, tautilde, nutilde, L, La, b] = gpep_e(gp_pak(gp), gp, x, y, 'z', z);\n [e, edata, eprior, p] = gpep_e(gp_pak(gp), gp, x, y, 'z', z);\n if isnan(e)\n Eft=NaN; Varft=NaN; lpyt=NaN; Eyt=NaN; Varyt=NaN;\n return\n end\n [L, La, b] = deal(p.L, p.La2, p.b);\n \n K_fu = gp_cov(gp, x, u, predcf); % f x u\n K_nu = gp_cov(gp, xt, u, predcf); % n x u\n K_uu = gp_trcov(gp, u, predcf); % u x u, noiseles covariance K_uu\n \n % From this on evaluate the prediction\n % See Snelson and Ghahramani (2007) for details\n % p=iLaKfu*(A\\(iLaKfu'*mutilde));\n p = b';\n \n iKuuKuf = K_uu\\K_fu';\n \n w_bu=zeros(length(xt),length(u));\n w_n=zeros(length(xt),1);\n for i=1:length(ind)\n w_bu(tstind{i},:) = repmat((iKuuKuf(:,ind{i})*p(ind{i},:))', length(tstind{i}),1);\n K_nf = gp_cov(gp, xt(tstind{i},:), x(ind{i},:), predcf); % n x u\n w_n(tstind{i},:) = K_nf*p(ind{i},:);\n end\n \n Eft = K_nu*(iKuuKuf*p) - sum(K_nu.*w_bu,2) + w_n;\n \n % Compute variance\n if nargout > 1\n kstarstar = gp_trvar(gp, xt, predcf);\n KnfL = K_nu*(iKuuKuf*L);\n Varft = zeros(length(xt),1);\n for i=1:length(ind)\n v_n = gp_cov(gp, xt(tstind{i},:), x(ind{i},:), predcf); % n x u\n v_bu = K_nu(tstind{i},:)*iKuuKuf(:,ind{i});\n KnfLa = K_nu*(iKuuKuf(:,ind{i})/chol(La{i}));\n KnfLa(tstind{i},:) = KnfLa(tstind{i},:) - (v_bu + v_n)/chol(La{i});\n Varft = Varft + sum((KnfLa).^2,2);\n KnfL(tstind{i},:) = KnfL(tstind{i},:) - v_bu*L(ind{i},:) + v_n*L(ind{i},:);\n end\n Varft = kstarstar - (Varft - sum((KnfL).^2,2));\n \n end\n % ============================================================\n % CS+FIC\n % ============================================================\n case 'CS+FIC' % Predictions with CS+FIC sparse approximation for GP\n % Here tstind = 1 if the prediction is made for the training set\n if nargin > 6\n if ~isempty(tstind) && length(tstind) ~= size(x,1)\n error('tstind (if provided) has to be of same length as x.')\n end\n else\n tstind = [];\n end\n \n u = gp.X_u;\n m = length(u);\n n = size(x,1);\n n2 = size(xt,1);\n \n %[e, edata, eprior, tautilde, nutilde, L, La, b] = gpep_e(gp_pak(gp), gp, x, y, 'z', z);\n [e, edata, eprior, p] = gpep_e(gp_pak(gp), gp, x, y, 'z', z);\n if isnan(e)\n Eft=NaN; Varft=NaN; lpyt=NaN; Eyt=NaN; Varyt=NaN;\n return\n end\n [L, La, b] = deal(p.L, p.La2, p.b);\n \n % Indexes to all non-compact support and compact support covariances.\n cf1 = [];\n cf2 = [];\n % Indexes to non-CS and CS covariances, which are used for predictions\n predcf1 = [];\n predcf2 = [];\n \n ncf = length(gp.cf);\n % Loop through all covariance functions\n for i = 1:ncf\n % Non-CS covariances\n if ~isfield(gp.cf{i},'cs')\n cf1 = [cf1 i];\n % If used for prediction\n if ~isempty(find(predcf==i))\n predcf1 = [predcf1 i];\n end\n % CS-covariances\n else\n cf2 = [cf2 i];\n % If used for prediction\n if ~isempty(find(predcf==i))\n predcf2 = [predcf2 i];\n end\n end\n end\n if isempty(predcf1) && isempty(predcf2)\n predcf1 = cf1;\n predcf2 = cf2;\n end\n \n % Determine the types of the covariance functions used\n % in making the prediction.\n if ~isempty(predcf1) && isempty(predcf2) % Only non-CS covariances\n ptype = 1;\n predcf2 = cf2;\n elseif isempty(predcf1) && ~isempty(predcf2) % Only CS covariances\n ptype = 2;\n predcf1 = cf1;\n else % Both non-CS and CS covariances\n ptype = 3;\n end\n \n K_fu = gp_cov(gp,x,u,predcf1); % f x u\n K_uu = gp_trcov(gp,u,predcf1); % u x u, noiseles covariance K_uu\n K_uu = (K_uu+K_uu')./2; % ensure the symmetry of K_uu\n K_nu=gp_cov(gp,xt,u,predcf1);\n \n Kcs_nf = gp_cov(gp, xt, x, predcf2);\n \n p = b';\n ntest=size(xt,1);\n \n % Calculate the predictive mean according to the type of\n % covariance functions used for making the prediction\n if ptype == 1\n Eft = K_nu*(K_uu\\(K_fu'*p));\n elseif ptype == 2\n Eft = Kcs_nf*p;\n else\n Eft = K_nu*(K_uu\\(K_fu'*p)) + Kcs_nf*p;\n end\n \n % evaluate also Lav if the prediction is made for training set\n if ~isempty(tstind)\n [Kv_ff, Cv_ff] = gp_trvar(gp, xt(tstind,:), predcf1);\n Luu = chol(K_uu)';\n B=Luu\\(K_fu');\n Qv_ff=sum(B.^2)';\n Lav = Kv_ff-Qv_ff;\n end\n \n % Add also Lav if the prediction is made for training set\n % and non-CS covariance function is used for prediction\n if ~isempty(tstind) && (ptype == 1 || ptype == 3)\n Eft(tstind) = Eft(tstind) + Lav.*p;\n end\n \n % Evaluate the variance\n if nargout > 1\n Knn_v = gp_trvar(gp,xt,predcf);\n Luu = chol(K_uu)';\n B=Luu\\(K_fu');\n B2=Luu\\(K_nu');\n p = amd(La);\n iLaKfu = La\\K_fu;\n % Calculate the predictive variance according to the type\n % covariance functions used for making the prediction\n if ptype == 1 || ptype == 3\n % FIC part of the covariance\n Varft = Knn_v - sum(B2'.*(B*(La\\B')*B2)',2) + sum((K_nu*(K_uu\\(K_fu'*L))).^2, 2);\n % Add Lav2 if the prediction is made for the training set\n if ~isempty(tstind)\n % Non-CS covariance\n if ptype == 1\n Kcs_nf = sparse(tstind,1:n,Lav,n2,n);\n % Non-CS and CS covariances\n else\n Kcs_nf = Kcs_nf + sparse(tstind,1:n,Lav,n2,n);\n end\n % Add Lav2 inside Kcs_nf\n Varft = Varft - sum((Kcs_nf(:,p)/chol(La(p,p))).^2,2) + sum((Kcs_nf*L).^2, 2) ...\n - 2.*sum((Kcs_nf*iLaKfu).*(K_uu\\K_nu')',2) + 2.*sum((Kcs_nf*L).*(L'*K_fu*(K_uu\\K_nu'))' ,2);\n % In case of both non-CS and CS prediction covariances add\n % only Kcs_nf if the prediction is not done for the training set\n elseif ptype == 3\n Varft = Varft - sum((Kcs_nf(:,p)/chol(La(p,p))).^2,2) + sum((Kcs_nf*L).^2, 2) ...\n - 2.*sum((Kcs_nf*iLaKfu).*(K_uu\\K_nu')',2) + 2.*sum((Kcs_nf*L).*(L'*K_fu*(K_uu\\K_nu'))' ,2);\n end\n % Prediction with only CS covariance\n elseif ptype == 2\n Varft = Knn_v - sum((Kcs_nf(:,p)/chol(La(p,p))).^2,2) + sum((Kcs_nf*L).^2, 2) ;\n end\n end\n % ============================================================\n % DTC/(VAR)\n % ============================================================\n case {'DTC' 'VAR' 'SOR'} % Predictions with DTC or variational sparse approximation for GP\n %[e, edata, eprior, tautilde, nutilde, L, La, b] = gpep_e(gp_pak(gp), gp, x, y, 'z', z);\n [e, edata, eprior, p] = gpep_e(gp_pak(gp), gp, x, y, 'z', z);\n if isnan(e)\n Eft=NaN; Varft=NaN; lpyt=NaN; Eyt=NaN; Varyt=NaN;\n return\n end\n [L, La, b] = deal(p.L, p.La2, p.b);\n \n % Here tstind = 1 if the prediction is made for the training set\n if nargin > 6\n if ~isempty(tstind) && length(tstind) ~= size(x,1)\n error('tstind (if provided) has to be of same length as x.')\n end\n else\n tstind = [];\n end\n \n u = gp.X_u;\n m = size(u,1);\n \n K_fu = gp_cov(gp,x,u,predcf); % f x u\n K_nu=gp_cov(gp,xt,u,predcf);\n K_uu = gp_trcov(gp,u,predcf); % u x u, noiseles covariance K_uu\n K_uu = (K_uu+K_uu')./2; % ensure the symmetry of K_uu\n \n kstarstar=gp_trvar(gp,xt,predcf);\n \n % From this on evaluate the prediction\n p = b';\n \n ntest=size(xt,1);\n \n Eft = K_nu*(K_uu\\(K_fu'*p));\n \n % if the prediction is made for training set, evaluate Lav also for prediction points\n if ~isempty(tstind)\n [Kv_ff, Cv_ff] = gp_trvar(gp, xt(tstind,:), predcf);\n Luu = chol(K_uu)';\n B=Luu\\(K_fu');\n Qv_ff=sum(B.^2)';\n Lav = Kv_ff-Cv_ff;\n Eft(tstind) = Eft(tstind);% + Lav.*p;\n end\n \n if nargout > 1\n % Compute variances of predictions\n %Varft(i1,1)=kstarstar(i1) - (sum(Knf(i1,:).^2./La') - sum((Knf(i1,:)*L).^2));\n Luu = chol(K_uu)';\n B=Luu\\(K_fu');\n B2=Luu\\(K_nu');\n \n Varft = sum(B2'.*(B*(repmat(La,1,m).\\B')*B2)',2) + sum((K_nu*(K_uu\\(K_fu'*L))).^2, 2);\n switch gp.type\n case {'VAR' 'DTC'}\n Varft = kstarstar - Varft;\n case 'SOR'\n Varft = sum(B2.^2,1)' - Varft;\n end\n end\n end\n end\n if ~isequal(fcorr, 'off')\n % Do marginal corrections for samples\n [pc_predm, fvecm] = gp_predcm(gp, x, y, xt, 'z', z, 'ind', 1:size(xt,1), 'fcorr', fcorr);\n for i=1:size(xt,1)\n % Remove NaNs and zeros\n pc_pred=pc_predm(:,i);\n dii=isnan(pc_pred)|pc_pred==0;\n pc_pred(dii)=[];\n fvec=fvecm(:,i);\n fvec(dii)=[];\n % Compute mean correction\n Eft(i) = trapz(fvec.*(pc_pred./sum(pc_pred)));\n end\n end\n \n % ============================================================\n % Evaluate also the predictive mean and variance of new observation(s)\n % ============================================================ \n if ~isequal(fcorr, 'off')\n if nargout == 3\n if isempty(yt)\n lpyt=[];\n else\n lpyt = gp.lik.fh.predy(gp.lik, fvecm', pc_predm', yt, zt);\n end\n elseif nargout > 3\n [lpyt, Eyt, Varyt] = gp.lik.fh.predy(gp.lik, fvecm', pc_predm', yt, zt);\n end\n else\n if nargout == 3\n if isempty(yt)\n lpyt=[];\n else\n lpyt = gp.lik.fh.predy(gp.lik, Eft, Varft, yt, zt);\n end\n elseif nargout > 3\n [lpyt, Eyt, Varyt] = gp.lik.fh.predy(gp.lik, Eft, Varft, yt, zt);\n end\n end\nend\n\nfunction [m,S]=pred_var(tau_q,K,A,b)\n\n% helper function for determining\n%\n% m = A * inv( K+ inv(diag(tau_q)) ) * inv(diag(tau_q)) *b\n% S = diag( A * inv( K+ inv(diag(tau_q)) ) * A)\n%\n% when the site variances tau_q may be negative\n%\n\n ii1=find(tau_q>0); n1=length(ii1); W1=sqrt(tau_q(ii1));\n ii2=find(tau_q<0); n2=length(ii2); W2=sqrt(abs(tau_q(ii2)));\n\n m=A*b;\n b=K*b;\n S=zeros(size(A,1),1);\n u=0;\n U=0;\n L1=[];\n if ~isempty(ii1)\n % Cholesky decomposition for the positive sites\n L1=(W1*W1').*K(ii1,ii1);\n L1(1:n1+1:end)=L1(1:n1+1:end)+1;\n L1=chol(L1);\n \n U = bsxfun(@times,A(:,ii1),W1')/L1;\n u = L1'\\(W1.*b(ii1));\n \n m = m-U*u;\n S = S+sum(U.^2,2);\n end\n\n if ~isempty(ii2)\n % Cholesky decomposition for the negative sites\n V=bsxfun(@times,K(ii2,ii1),W1')/L1;\n if isempty(V)\n V=0;\n end\n L2=(W2*W2').*(V*V'-K(ii2,ii2));\n L2(1:n2+1:end)=L2(1:n2+1:end)+1;\n \n [L2,pd]=chol(L2);\n if pd==0\n U = bsxfun(@minus, bsxfun(@times,A(:,ii2),W2')/L2,U*(bsxfun(@times,V,W2)'/L2));\n u = L2'\\(W2.*b(ii2)) -L2'\\(bsxfun(@times,V,W2)*u);\n \n m = m+U*u;\n S = S-sum(U.^2,2);\n else\n fprintf('Posterior covariance is negative definite.\\n')\n end\n end\n\nend\n\nfunction [m_q,S_q]=pred_var2(tautilde,nutilde,L,K_uu,K_fu,D,K_nu)\n\n% function for determining the parameters of the q-distribution\n% when site variances tau_q may be negative\n%\n% q(f) = N(f|0,K)*exp( -0.5*f'*diag(tau_q)*f + nu_q'*f )/Z_q = N(f|m_q,S_q)\n%\n% S_q = inv(inv(K)+diag(tau_q)) where K is sparse approximation for prior\n% covariance\n% m_q = S_q*nu_q;\n%\n% det(eye(n)+K*diag(tau_q))) = det(L1)^2 * det(L2)^2\n% where L1 and L2 are upper triangular\n%\n% see Expectation consistent approximate inference (Opper & Winther, 2005)\n\n n=length(nutilde);\n\n U = K_fu;\n S = 1+tautilde.*D;\n B = tautilde./S;\n BUiL = bsxfun(@times, B, U)/L';\n % iKS = diag(B) - BUiL*BUiL';\n\n Ktnu = D.*nutilde + U*(K_uu\\(U'*nutilde));\n m_q = nutilde - B.*Ktnu + BUiL*(BUiL'*Ktnu);\n kstar = K_nu*(K_uu\\K_fu');\n m_q = kstar*m_q;\n\n S_q = sum(bsxfun(@times,B',kstar.^2),2) - sum((kstar*BUiL).^2,2);\n % S_q = kstar*iKS*kstar';\n\n\nend\n", "meta": {"author": "gpstuff-dev", "repo": "gpstuff", "sha": "114937ec0a201306489a66cbba38283e722fb998", "save_path": "github-repos/MATLAB/gpstuff-dev-gpstuff", "path": "github-repos/MATLAB/gpstuff-dev-gpstuff/gpstuff-114937ec0a201306489a66cbba38283e722fb998/gp/gpep_pred.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.66192288918838, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.34388305442149597}} {"text": "classdef prtRvMvn < prtRv & prtRvMemebershipModel\n % prtRvMvn Multivariate normal random variable\n %\n % RV = prtRvMvn creates a prtRvMvn object with empty mean and\n % covariance matrices. The mean and covariance matrices must be set\n % either directly, or by calling the MLE method.\n %\n % RV = prtRvMvn('covarianceStructure', VALUE) enforces a covariance\n % structure, which may be either 'full', 'spherical', or 'diagonal'.\n % Setting this property to 'spherical' or 'diagonal' will enforce\n % this structure onto the existing covariance matrix, or one\n % estimated by calling the MLE method.\n %\n % RV = prtRvMvn(PROPERTY1, VALUE1,...) creates a prtRvMv object RV\n % with properties as specified by PROPERTY/VALUE pairs.\n %\n % A prtRvMvn object inherits all properties from the prtRv class. In\n % addition, it has the following properties:\n %\n % covarianceStructure - A string specifying the structure of the\n % covariance matrix to estimate or enforce. \n % Valid values are 'full','spherical', or \n % 'diagonal'\n % mu - The mean of the distribution, which is\n % a 1 x nDimensions vector.\n % sigma - The covariance matrix of the distribution,\n % which is a nDimensions x nDimensions \n % matrix.\n % \n % A prtRvMvn object inherits all methods from the prtRv class. The MLE\n % method can be used to estimate the distribution parameters from\n % data.\n %\n % Example:\n %\n % dataSet = prtDataGenUnimodal; % Load a dataset consisting of 2\n % % classes\n % % Extract one of the classes from the dataSet\n % dataSetOneClass = prtDataSetClass(dataSet.getObservationsByClass(1));\n %\n % RV = prtRvMvn; % Create a prtRvMvn object\n % RV = RV.mle(dataSetOneClass.getX); % Compute the maximum\n % % likelihood estimate from the\n % % data\n % RV.plotPdf % Plot the pdf\n %\n % RVspec = prtRvMvn; % Create another prtRvMvn\n % % object\n % RVspec.mu = [1 2]; % Specify the mean\n % RVspec.sigma = [2 -1; -1 2] % Specify the covariance\n % figure;\n % RVspec.plotPdf % Plot the pdf\n % sample = RVspec.draw(1) % Draw 1 random sample from the\n % % Distribution\n %\n % See also: prtRv, prtRvGmm, prtRvMultinomial, prtRvUniform,\n % prtRvUniformImproper, prtRvVq, prtRvDiscrete\n\n\n\n\n\n\n\n properties (SetAccess = 'private')\n name = 'Multi-Variate Normal';\n nameAbbreviation = 'RVMVN';\n end\n \n properties (SetAccess = 'protected')\n isSupervised = false;\n isCrossValidateValid = true;\n end\n \n properties (Dependent)\n covarianceStructure % The covariance structure\n mu % The mean vector\n sigma % The covariance matrix\n end\n properties (SetAccess = 'private', GetAccess = 'private', Hidden = true)\n muDepHelper\n sigmaDepHelper\n covarianceStructureDepHelper = 'full';\n end\n \n properties (Hidden = true)\n covarianceBias = [];\n end\n \n properties (Hidden = true, Dependent = true)\n nDimensions\n end\n \n properties (SetAccess = 'private', Hidden = true)\n trueCovariance\n badCovariance = false;\n end\n \n methods\n function R = prtRvMvn(varargin)\n R = constructorInputParse(R,varargin{:});\n end\n \n function R = mle(R,X)\n % MLE Compute the maximum likelihood estimate \n %\n % RV = RV.mle(X) computes the maximum likelihood estimate based\n % the data X. X should be nObservations x nDimensions. \n\n X = R.dataInputParse(X); % Basic error checking etc\n \n R.mu = mean(X,1);\n if size(X,1) == 1 \n % A single observation\n % This is bad..\n % You can't call cov for this case \n % Since we always want to output sum( (x_i - u)'*(x_i - u))\n % We will output a matrix of zeros of the correct size.\n % Error checking for a propert covariance will happen later\n % after the bias has been applied.\n R.sigma = zeros(size(X,2));\n else\n R.sigma = cov(X);\n end\n \n end\n \n function vals = pdf(R,X)\n % PDF Output the pdf of the random variable evaluated at the points specified\n %\n % pdf = RV.pdf(X) returns the pdf of the prtRv\n % object evaluated at X. X must be an N x nDims matrix, where\n % N is the number of locations to evaluate the pdf, and nDims\n % is the same as the number of dimensions, nDimensions, of the\n % prtRv object RV.\n \n [isValid, reasonStr] = R.isValid;\n assert(isValid,'PDF cannot yet be evaluated. This RV is not yet valid %s.',reasonStr);\n \n assert(~R.badCovariance,'Covariance matrix is not positive definite. Consider modifying \"covarianceStructure\".');\n X = R.dataInputParse(X); % Basic error checking etc\n \n assert(size(X,2) == R.nDimensions,'Data, RV dimensionality missmatch. Input data, X, has dimensionality %d and this RV has dimensionality %d.', size(X,2), R.nDimensions)\n assert(isnumeric(X) && ndims(X)==2,'X must be a 2D numeric array.');\n \n vals = exp(prtRvUtilMvnLogPdf(X,R.mu,R.sigma));\n end\n \n function vals = logPdf(R,X)\n % LOGPDF Output the log pdf of the random variable evaluated at the points specified\n %\n % logpdf = RV.logpdf(X) returns the logarithm of value of the\n % pdf of the prtRv object evaluated at X. X must be an N x\n % nDims matrix, where N is the number of locations to evaluate\n % the pdf, and nDims is the same as the number of dimensions,\n % nDimensions, of the prtRv object RV.\n \n X = R.dataInputParse(X); % Basic error checking etc\n try\n vals = prtRvUtilMvnLogPdf(X,R.mu,R.sigma);\n catch ME\n [isValid, reasonStr] = R.isValid;\n assert(isValid,'LOGPDF cannot yet be evaluated. This RV is not yet valid %s.',reasonStr);\n assert(size(X,2) == R.nDimensions,'Data, RV dimensionality missmatch. Input data, X, has dimensionality %d and this RV has dimensionality %d.', size(X,2), R.nDimensions)\n throw(ME);\n end\n end\n \n function varargout = plotCdf(R,varargin)\n % PLOTCDF Plots the CDF of the prtRv\n assert(R.nDimensions == 1,'prtRvMvn.plotCdf can only be used for 1D RV objects.');\n \n varargout = cell(nargout,1); \n \n [varargout{:}] = plotCdf@prtRv(R,varargin{:});\n \n end\n \n function vals = cdf(R,X)\n % CDF Output the cdf of the random variable evaluated at the points specified\n %\n % cdf = RV.cdf(X) returns the value of the cdf of the prtRv\n % object evaluated at X. X must be an N x nDims matrix, where\n % N is the number of locations to evaluate the pdf, and nDims\n % is the same as the number of dimensions, nDimensions, of the\n % prtRv object RV.\n \n [isValid, reasonStr] = R.isValid;\n assert(isValid,'CDF cannot yet be evaluated. This RV is not yet valid %s.',reasonStr);\n \n assert(~R.badCovariance,'Covariance matrix is not positive definite. Consider modifying \"covarianceStructure\"');\n X = R.dataInputParse(X); % Basic error checking etc\n \n assert(size(X,2) == R.nDimensions,'Data, RV dimensionality missmatch. Input data, X, has dimensionality %d and this RV has dimensionality %d.', size(X,2), R.nDimensions)\n vals = prtRvUtilMvnCdf(X,R.mu,R.sigma);\n end\n \n function vals = draw(R,N)\n % DRAW Draw random samples from the distribution described by the prtRv object\n %\n % VAL = RV.draw(N) generates N random samples drawn from the\n % distribution described by the prtRv object RV. VAL will be a\n % N x nDimensions vector, where nDimensions is the number of\n % dimensions of RV.\n \n assert(numel(N)==1 && N==floor(N) && N > 0,'N must be a positive integer scalar.')\n [isValid, reasonStr] = R.isValid;\n assert(isValid,'DRAW cannot yet be evaluated. This RV is not yet valid %s.',reasonStr);\n \n assert(~R.badCovariance,'Covariance matrix is not positive definite. Consider modifying \"covarianceStructure\"');\n vals = prtRvUtilMvnDraw(R.mu,R.sigma,N);\n end\n end\n \n methods (Hidden=true)\n function [val, reasonStr] = isValid(R)\n \n if numel(R) > 1\n val = false(size(R));\n for iR = 1:numel(R)\n [val(iR), reasonStr] = isValid(R(iR));\n end\n return\n end\n \n val = ~isempty(R.sigma) && ~isempty(R.mu);\n \n if val\n reasonStr = '';\n else\n badCov = isempty(R.sigma);\n badMean = isempty(R.mu);\n \n if badCov && ~badMean\n reasonStr = 'because sigma has not been set';\n elseif ~badCov && badMean\n reasonStr = 'because mu has not been set';\n elseif badCov && badMean\n reasonStr = 'because mu and sigma have not been set';\n else\n reasonStr = 'because of an unknown reason';\n end\n end\n end\n \n function val = plotLimits(R)\n [isValid, reasonStr] = R.isValid;\n if isValid\n minX = min(R.mu, [], 1)' - 2*sqrt(diag(R.sigma));\n maxX = max(R.mu, [], 1)' + 2*sqrt(diag(R.sigma));\n \n val = zeros(1,2*R.nDimensions);\n val(1:2:R.nDimensions*2-1) = minX;\n val(2:2:R.nDimensions*2) = maxX;\n else\n error('prtRvMvn:plotLimits','Plotting limits can not be determined for this RV. It is not yet valid %s',reasonStr)\n end\n end\n \n function R = weightedMle(R,X,weights)\n assert(numel(weights)==size(X,1),'The number of weights must mach the number of observations.');\n \n weights = weights(:);\n \n Nbar = sum(weights);\n R.mu = 1/Nbar*sum(bsxfun(@times,X,weights),1);\n X = bsxfun(@times,bsxfun(@minus,X,R.mu),sqrt(weights));\n R.sigma = 1/Nbar*(X'*X);\n end\n end\n \n % Get methods\n methods\n function val = get.nDimensions(R)\n val = getNumDimensions(R);\n end\n \n function val = get.mu(R)\n val = R.muDepHelper;\n end\n function val = get.sigma(R)\n val = R.sigmaDepHelper;\n end\n function val = get.covarianceStructure(R)\n val = R.covarianceStructureDepHelper;\n end\n end\n methods (Access = 'protected')\n function val = getNumDimensions(R)\n if ~isempty(R.mu)\n val = length(R.mu);\n elseif ~isempty(R.sigma)\n val = size(R.sigma,2);\n else\n val = [];\n end\n end\n end\n % Set Methods\n methods\n function R = set.covarianceStructure(R,covarianceStructure)\n % Find and fix known abbreviations\n \n assert(ischar(covarianceStructure),'covarianceStructure must be a string that is either, full, diagonal, or spherical');\n \n covarianceStructure = lower(covarianceStructure);\n \n if strcmpi(covarianceStructure,'diag')\n covarianceStructure = 'diagonal';\n end\n \n % Limit the options for the covariance structure\n if ~(strcmpi(covarianceStructure,'full') || ...\n strcmpi(covarianceStructure,'diagonal') || ...\n strcmpi(covarianceStructure,'spherical'))\n error('%s is not a valid covariance structure. Possible types are, full, diagonal, and spherical',covarianceStructure);\n end\n R.covarianceStructureDepHelper = covarianceStructure;\n \n % Redo the covariance to reflect the updated covarianceStructure\n if ~isempty(R.sigma)\n R.sigma = R.trueCovariance; % This will call set.sigma()\n end\n end\n \n function R = set.mu(R,meanVal)\n if ~isempty(R.sigma) && size(meanVal,2) ~= size(R.sigma,2)\n error('prtRvMvn:dimensions','Dimensions mismatch between supplied mu and prtRvMvn dimensionality');\n end\n R.muDepHelper = meanVal;\n end\n \n function R = set.sigma(R,sigma)\n if size(sigma,1) ~= size(sigma,2)\n error('Covariance matrix must be square.')\n end\n \n if ~isempty(R.mu) && size(sigma,1) ~= R.nDimensions\n error('prtRvMvn:dimensions','Dimensions mismatch between sigma and prtRvMvn dimensionality')\n end\n\n % Save this input as a true hidden sigma\n R.trueCovariance = sigma;\n \n % Enforce the covariance structure\n switch lower(R.covarianceStructure)\n case 'full'\n R.sigmaDepHelper = sigma;\n case 'diagonal'\n R.sigmaDepHelper = eye(size(sigma)).*sigma;\n case 'spherical'\n R.sigmaDepHelper = eye(size(sigma))*mean(diag(sigma));\n end\n \n if ~isempty(R.covarianceBias)\n R.sigmaDepHelper = R.sigmaDepHelper + R.covarianceBias.*eye(size(sigma));\n end\n \n [dontNeed, cholErr] = chol(R.sigmaDepHelper); %#ok\n if cholErr ~=0\n R.badCovariance = true;\n warning('prt:prtRvMvn','Covariance matrix is not positive definite. This may cause errors. Consider modifying \"covarianceStructure\".');\n end\n end\n end\nend\n\n", "meta": {"author": "covartech", "repo": "PRT", "sha": "4305e612af048e7dbf3d9392efc7436db125b1fc", "save_path": "github-repos/MATLAB/covartech-PRT", "path": "github-repos/MATLAB/covartech-PRT/PRT-4305e612af048e7dbf3d9392efc7436db125b1fc/rv/prtRvMvn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6619228625116081, "lm_q2_score": 0.5195213219520929, "lm_q1q2_score": 0.3438830405623441}} {"text": "function [MDP] = spm_MDP_check(MDP)\n% MDP structure checking\n% FORMAT [MDP] = spm_MDP_check(MDP)\n%\n% MDP.V(T - 1,P,F) - P allowable policies of T moves over F factors\n% or\n% MDP.U(1,P,F) - P allowable actions at each move\n% MDP.T - number of outcomes\n%\n% MDP.A{G}(O,N1,...,NF) - likelihood of O outcomes given hidden states\n% MDP.B{F}(NF,NF,MF) - transitions among hidden under MF control states\n% MDP.C{G}(O,T) - prior preferences over O outcomes in modality G\n% MDP.D{F}(NF,1) - prior probabilities over initial states\n%\n% MDP.a{G} - concentration parameters for A\n% MDP.b{F} - concentration parameters for B\n% MDP.d{F} - concentration parameters for D\n%\n% optional:\n% MDP.s(F,T) - vector of true states - for each hidden factor\n% MDP.o(G,T) - vector of outcome - for each outcome modality\n% MDP.u(F,T - 1) - vector of action - for each hidden factor\n% MDP.w(1,T) - vector of precisions\n%\n% if C or D are not specified, they will be set to default values (of no\n% preferences and uniform priors over initial steps). If there are no\n% policies, it will be assumed that I = 1 and all policies (for each\n% marginal hidden state) are allowed.\n%__________________________________________________________________________\n% Copyright (C) 2005 Wellcome Trust Centre for Neuroimaging\n\n% Karl Friston\n% $Id: spm_MDP_check.m 7766 2020-01-05 21:37:39Z karl $\n\n\n% deal with a sequence of trials\n%==========================================================================\n\n% if there are multiple structures check each separately\n%--------------------------------------------------------------------------\nif numel(MDP) > 1\n for m = 1:size(MDP,1)\n for i = 1:size(MDP,2)\n mdp(m,i) = spm_MDP_check(MDP(m,i));\n end\n end\n MDP = mdp;\n return\nend\n\n% fill in (posterior or process) likelihood and priors\n%--------------------------------------------------------------------------\nif ~isfield(MDP,'A'), MDP.A = MDP.a; end\nif ~isfield(MDP,'B'), MDP.B = MDP.b; end\n\n% check format of likelihood and priors\n%--------------------------------------------------------------------------\nif ~iscell(MDP.A), MDP.A = {full(MDP.A)}; end\nif ~iscell(MDP.B), MDP.B = {full(MDP.B)}; end\n\nif isfield(MDP,'a'), if ~iscell(MDP.a), MDP.a = {full(MDP.a)}; end; end\nif isfield(MDP,'b'), if ~iscell(MDP.b), MDP.b = {full(MDP.b)}; end; end\n\n\n% check dimensions and orders\n%==========================================================================\n\n% numbers of transitions, policies and states\n%--------------------------------------------------------------------------\nNf = numel(MDP.B); % number of hidden state factors\nNg = numel(MDP.A); % number of outcome factors\nfor f = 1:Nf\n Nu(f) = size(MDP.B{f},3); % number of hidden controls\n Ns(f) = size(MDP.B{f},1); % number of hidden states\n MDP.B{f} = double(MDP.B{f});\nend\nfor g = 1:Ng\n No(g) = size(MDP.A{g},1); % number of outcomes\n MDP.A{g} = double(MDP.A{g});\nend\n\n% check policy specification (create default moving policy U, if necessary)\n% V = V(Nt,Np,Nf)\n% U = U(Np,Nf)\n%--------------------------------------------------------------------------\nif isfield(MDP,'U')\n if size(MDP.U,1) == 1 && size(MDP.U,3) == Nf\n MDP.U = shiftdim(MDP.U,1);\n end\nend\ntry\n V(1,:,:) = MDP.U; % allowable actions (1,Np)\ncatch\n try\n V = MDP.V; % allowable policies (T - 1,Np)\n catch\n \n % allowable (moving) policies using all allowable actions\n %------------------------------------------------------------------\n for f = 1:Nf\n u = 1;\n for i = 1:Nf\n if i == f\n u = kron(1:Nu(i),u);\n else\n u = kron(ones(1,Nu(i)),u);\n end\n end\n MDP.U(:,f) = u;\n end\n V(1,:,:) = MDP.U;\n end\nend\nMDP.V = V;\n\n% check policy specification\n%--------------------------------------------------------------------------\nif Nf ~= size(V,3) && size(V,3) > 1\n error('please ensure V(:,:,1:Nf) is consistent with MDP.B{1:Nf}')\nend\n\n% check preferences\n%--------------------------------------------------------------------------\nif ~isfield(MDP,'C')\n for g = 1:Ng\n MDP.C{g} = zeros(No(g),1);\n end\nend\nfor g = 1:Ng\n if iscell(MDP.C)\n if isvector(MDP.C{g})\n MDP.C{g} = spm_vec(MDP.C{g});\n end\n if No(g) ~= size(MDP.C{g},1)\n error(['please ensure A{' num2str(g) '} and C{' num2str(g) '} are consistent'])\n end\n end\nend\n\n% check iinitial states\n%--------------------------------------------------------------------------\nif ~isfield(MDP,'D')\n for f = 1:Nf\n MDP.D{f} = ones(Ns(f),1);\n end\nend\nif Nf ~= numel(MDP.D)\n error('please ensure V(:,:,1:Nf) is consistent with MDP.D{1:Nf}')\nend\n\n\n% check iinitial states and internal consistency\n%--------------------------------------------------------------------------\nif Nf ~= numel(MDP.D)\n error('please ensure V(:,:,1:Nf) is consistent with MDP.D{1:Nf}')\nend\nfor f = 1:Nf\n if Ns(f) ~= size(MDP.D{f},1)\n error(['please ensure B{' num2str(f) '} and D{' num2str(f) '} are consistent'])\n end\n if size(V,3) > 1\n if Nu(f) < max(spm_vec(V(:,:,f)))\n error(['please check V(:,:,' num2str(f) ') or U(:,:,' num2str(f) ')'])\n end\n end\n for g = 1:Ng\n Na = size(MDP.A{g});\n if ~all(Na(2:end) == Ns)\n error(['please ensure A{' num2str(g) '} and D{' num2str(f) '} are consistent'])\n end\n end\nend\n\n% check probability matrices are properly specified\n%--------------------------------------------------------------------------\nfor f = 1:Nf\n if ~all(spm_vec(any(MDP.B{f},1)))\n error(['please check B{' num2str(f) '} for missing entries'])\n end\nend\nfor g = 1:Ng\n if ~all(spm_vec(any(MDP.A{g},1)))\n error(['please check A{' num2str(g) '} for missing entries'])\n end\nend\n\n% check initial states\n%--------------------------------------------------------------------------\nif isfield(MDP,'s')\n if size(MDP.s,1) > Nf\n error('please specify an initial state MDP.s for %i factors',Nf)\n end\n f = max(MDP.s,[],2)';\n if any(f > Ns(1:numel(f)))\n error('please ensure initial states MDP.s are consistent with MDP.B')\n end\nend\n\n% check outcomes if specified\n%--------------------------------------------------------------------------\nif isfield(MDP,'o')\n if numel(MDP.o)\n if size(MDP.o,1) ~= Ng\n error('please specify an outcomes MDP.o for %i modalities',Ng)\n end\n if any(max(MDP.o,[],2) > No(:))\n error('please ensure outcomes MDP.o are consistent with MDP.A')\n end\n end\nend\n\n% check (primary link array if necessary)\n%--------------------------------------------------------------------------\nif isfield(MDP,'link')\n \n % cardinality of subordinate level\n %----------------------------------------------------------------------\n nf = numel(MDP.MDP(1).B); % number of hidden factors\n for f = 1:nf\n ns(f) = size(MDP.MDP(1).B{f},1); % number of hidden states\n end\n \n % check the size of link\n %----------------------------------------------------------------------\n if ~all(size(MDP.link) == [nf,Ng]);\n error('please check the size of link {%i,%i}',nf,Ng)\n end\n \n % convert matrix to cell array if necessary\n %----------------------------------------------------------------------\n if isnumeric(MDP.link)\n link = cell(nf,Ng);\n for f = 1:size(MDP.link,1)\n for g = 1:size(MDP.link,2)\n if MDP.link(f,g)\n link{f,g} = spm_speye(ns(f),No(g),0);\n end\n end\n end\n MDP.link = link;\n end\n \n % check sizes of cell array\n %----------------------------------------------------------------------\n for f = 1:size(MDP.link,1)\n for g = 1:size(MDP.link,2)\n if ~isempty(MDP.link{f,g})\n if ~all(size(MDP.link{f,g}) == [ns(f),No(g)]);\n error('please check link{%i,%i}',f,g)\n end\n end\n end\n end\n \nend\n\n% Empirical prior preferences\n%--------------------------------------------------------------------------\nif isfield(MDP,'linkC')\n if isnumeric(MDP.linkC)\n linkC = cell(numel(MDP.MDP.C),Ng);\n for f = 1:size(MDP.linkC,1)\n for g = 1:size(MDP.linkC,2)\n if MDP.linkC(f,g)\n linkC{f,g} = spm_speye(size(MDP.MDP.C{f},1),No(g),0);\n end\n end\n end\n MDP.linkC = linkC;\n end\nend\n\n% Empirical priors over policies\n%--------------------------------------------------------------------------\nif isfield(MDP,'linkE')\n if isnumeric(MDP.linkE)\n linkE = cell(1,Ng);\n for g = 1:size(MDP.linkE,2)\n if MDP.linkE(g)\n linkE{g} = spm_speye(size(MDP.MDP.E,1),No(g),0);\n end\n end\n MDP.linkE = linkE;\n end\nend\n\n% check factors and outcome modalities have proper labels\n%--------------------------------------------------------------------------\nfor i = 1:Nf\n \n % name of factors\n %----------------------------------------------------------------------\n try\n MDP.label.factor(i);\n catch\n try\n MDP.label.factor{i} = MDP.Bname{i};\n catch\n MDP.label.factor{i} = sprintf('factor %i',i);\n end\n end\n \n % name of levels of each factor\n %----------------------------------------------------------------------\n for j = 1:Ns(i)\n try\n MDP.label.name{i}(j);\n catch\n try\n MDP.label.name{i}{j} = MDP.Sname{i}{j};\n catch\n MDP.label.name{i}{j} = sprintf('state %i(%i)',j,i);\n end\n end\n end\n \n % name of actions under each factor\n %----------------------------------------------------------------------\n for j = 1:Nu(i)\n try\n MDP.label.action{i}(j);\n catch\n MDP.label.action{i}{j} = sprintf('act %i(%i)',j,i);\n end\n end\nend\n\n% name of outcomes under each modality\n%--------------------------------------------------------------------------\nfor i = 1:Ng\n try\n MDP.label.modality(i);\n catch\n try\n MDP.label.modality{i} = MDP.Bname{i};\n catch\n MDP.label.modality{i} = sprintf('modality %i',i);\n end\n end\n for j = 1:No(i)\n try\n MDP.label.outcome{i}(j);\n catch\n try\n MDP.label.outcome{i}{j} = MDP.Oname{i}{j};\n catch\n MDP.label.outcome{i}{j} = sprintf('outcome %i(%i)',j,i);\n end\n end\n end\nend\n\n% check names are specified properly\n%--------------------------------------------------------------------------\nif isfield(MDP,'Aname')\n if numel(MDP.Aname) ~= Ng\n error('please specify an MDP.Aname for each modality')\n end\nelse\n MDP.Aname = MDP.label.modality;\nend\nif isfield(MDP,'Bname')\n if numel(MDP.Bname) ~= Nf\n error('please specify an MDP.Bname for each factor')\n end\nelse\n MDP.Bname = MDP.label.factor;\nend\n\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/toolbox/DEM/spm_MDP_check.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.44552953503957277, "lm_q1q2_score": 0.34387907471556045}} {"text": "% op_B0Correction.m\n% Jamie Near, McGill University 2021.\n%E dits from Brenden Kadota, 2021.\n%\n% USAGE:\n% [out, phaseMap, freqMap]=op_B0Correction(in, (optional) phaseMap);\n%\n% DESCRIPTION:\n% Corrects for slight B0 shifts by aligning all voxels to the voxel with\n% the highest water peak. (Possibly not correct output as highest peak may\n% no have the correct ppm shifts)\n%\n% INPUTS:\n% in = MRSI struct\n% phaseMap = phaseMap matrix used to apply corrections\n%\n% OUTPUTS:\n% B0Map = 2D array of shift intensity at each specific voxel\n% phaseMap = 2D array of phase shift intensity at each specific voxel\n% freqMap = 2D array of frequency shift intensity at each specific voxel\n\nfunction [MRSIStruct, phaseMap, freqMap] = op_CSIB0Correction(MRSIStruct, phaseMap, ...\n freqMap, plottingArguments)\n arguments\n MRSIStruct (1, 1) struct\n phaseMap double = []\n freqMap double = []\n plottingArguments.isPlot = false;\n end\n %only correct if coils have be combined\n if(getFlags(MRSIStruct, 'addedrcvrs') == 0)\n error(\"MRSIStruct Error. Add coils first in MRSIStruct\");\n end\n if(getFlags(MRSIStruct, 'spatialft') == 0)\n error(\"Please fourier transform along the spatial dimension\");\n end\n if(getFlags(MRSIStruct, 'spectralft') == 0)\n error(\"Please fourier transform along the spectral dimension\");\n end\n\n %find the coordinate of the highest intensity\n [x, y, a] = findMaxCoord(MRSIStruct);\n\n %create twix object from coordinate with highest intensity\n referenceMRS = op_CSItoMRS(MRSIStruct, x, y, \"averageIndex\", a);\n referenceMRS = setFlags(referenceMRS, 'averaged', true);\n referenceMRS.flags.isISIS = 0;\n\n\n if(~isempty(phaseMap) && ~isempty(freqMap))\n [MRSIStruct, prevPermute, prevSize] = reshapeDimensions(MRSIStruct, {'t', 'y', 'x'});\n MRSIStruct = applyFreqMap(MRSIStruct, freqMap);\n MRSIStruct = applyPhaseMap(MRSIStruct, phaseMap);\n MRSIStruct = reshapeBack(MRSIStruct, prevPermute, prevSize);\n\n else\n\n [MRSIStruct, prevPermute, prevSize] = reshapeDimensions(MRSIStruct, {'t', 'y', 'x'});\n\n phaseMap = zeros(getSizeFromDimensions(MRSIStruct, {'y', 'x', 'extras'}));\n freqMap = zeros(getSizeFromDimensions(MRSIStruct, {'y', 'x', 'extras'}));\n\n data = getData(MRSIStruct);\n for e = 1:getSizeFromDimensions(MRSIStruct, {'extras'})\n for y = 1:getSizeFromDimensions(MRSIStruct, {'y'})\n for x = 1:getSizeFromDimensions(MRSIStruct, {'x'})\n %get twix object at x and y coordinate\n alignMRS = op_CSItoMRS(MRSIStruct, x, y, 'Extra', e);\n alignMRS = setFlags(alignMRS, 'averaged', true);\n alignMRS.flags.isISIS = 0;\n %aligns twix object to the maximum intensity twix object\n [alignMRS, phase, freq] = op_alignScans(alignMRS, referenceMRS, referenceMRS.t(end));\n\n timeDimension = getDimension(alignMRS, 't');\n %adds the aligned twix to the specs of MRSI object.\n data(:, y, x, e) = flip(alignMRS.specs, timeDimension);\n %add phase and frequency to maps\n phaseMap(y, x, e) = phase;\n freqMap(y, x, e) = freq;\n end\n end\n end\n MRSIStruct = setData(MRSIStruct, data);\n MRSIStruct = reshapeBack(MRSIStruct, prevPermute, prevSize);\n\n %plot maps\n if(plottingArguments.isPlot)\n plotFreqAndPhaseMap(phaseMap, MRSIStruct, freqMap);\n end\n MRSIStruct = setFlags(MRSIStruct, 'phasecorrected', 1);\n MRSIStruct = setFlags(MRSIStruct, 'freqcorrected', 1);\n end\nend\n\n\n%finds the (x,y) coordinate with the highest intensity spectrum.\nfunction [x,y,a] = findMaxCoord(in)\n [~, i] = max(getData(in),[], 'all', 'linear');\n out = cell(size(in.sz));\n [out{:}] = ind2sub(in.sz, i);\n x = out{in.dims.x};\n y = out{in.dims.y};\n if(in.dims.averages)\n a = out{in.dims.averages};\n else\n a = 1;\n end\n\n\nend\n\nfunction plotFreqAndPhaseMap(phaseMap, MRSIStruct, freqMap)\n for i = 1:size(phaseMap,3)\n figure;\n subplot(2,1,1);\n imagesc(MRSIStruct.coordinates.x, MRSIStruct.coordinates.y, phaseMap(:,:,i)')\n title(\"phaseMap\")\n subplot(2,1,2);\n imagesc(MRSIStruct.coordinates.x, MRSIStruct.coordinates.y, freqMap(:,:,i)')\n title(\"freqMap\")\n end\nend\n\nfunction MRSIStruct = applyFreqMap(MRSIStruct, freqMap)\n %applying the freqMap map if added as an argument\n for e = 1:getSizeFromDimensions(MRSIStruct, {'extras'})\n for x = 1:getSizeFromDimensions(MRSIStruct, {'x'})\n for y = 1:getSizeFromDimensions(MRSIStruct, {'y'})\n %create twix object from the coordinates\n alignMRS = op_CSItoMRS(MRSIStruct, x, y, 'extraIndex', e);\n %align twix object with op_freqshift to the equivalent\n %freqmap coordinate.\n alignMRS = op_freqshift(alignMRS, freqMap(x, y));\n %add the specs to MRSI object\n MRSIStruct.data(:, x, y, e) = alignMRS.specs;\n end\n end\n end\nend\n\nfunction MRSIStruct = applyPhaseMap(MRSIStruct, phaseMap)\n %applying the freqMap map if added as an argument\n for e = 1:getSizeFromDimensions(MRSIStruct, {'extras'})\n for x = 1:getSizeFromDimensions(MRSIStruct, {'x'})\n for y = 1:getSizeFromDimensions(MRSIStruct, {'y'})\n %create twix object from the coordinates\n alignMRS = op_CSItoMRS(MRSIStruct, x, y, 'extraIndex', e);\n %align twix object with op_freqshift to the equivalent\n %freqmap coordinate.\n alignMRS = op_addphase(alignMRS, phaseMap(x, y));\n %add the specs to MRSI object\n MRSIStruct.data(:, x, y, e) = alignMRS.specs;\n end\n end\n end\nend\n", "meta": {"author": "CIC-methods", "repo": "FID-A", "sha": "c24da581e376f6eed66979dcc662ec26903a2eef", "save_path": "github-repos/MATLAB/CIC-methods-FID-A", "path": "github-repos/MATLAB/CIC-methods-FID-A/FID-A-c24da581e376f6eed66979dcc662ec26903a2eef/processingTools/MRSI/op_CSIB0Correction.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.3436154138656433}} {"text": "classdef math_model_opf_acci < mp.math_model_opf_acc\n%MP.MATH_MODEL_OPF_ACCI MATPOWER mathematical model for AC optimal power flow (OPF) problem.\n% ?\n%\n% MP.MATH_MODEL_OPF_ACCI ... power flow ...\n%\n% Properties\n% ? - ?\n%\n% Methods\n% ?\n\n% MATPOWER\n% Copyright (c) 2021-2022, Power Systems Engineering Research Center (PSERC)\n% by Ray Zimmerman, PSERC Cornell\n%\n% This file is part of MATPOWER.\n% Covered by the 3-clause BSD License (see LICENSE file for details).\n% See https://matpower.org for more info.\n\n% properties\n% end\n\n methods\n function tag = form_tag(obj)\n tag = 'acci';\n end\n\n function name = form_name(obj)\n name = 'AC-cartesian-current';\n end\n\n function add_node_balance_constraints(obj, nm, dm, mpopt)\n %% power balance constraints\n nn = nm.node.N; %% number of nodes\n fcn_mis = @(x)obj.nodal_current_balance_fcn(x, nm);\n hess_mis = @(x, lam)obj.nodal_current_balance_hess(x, lam, nm);\n obj.add_nln_constraint({'rImis', 'iImis'}, [nn;nn], 1, fcn_mis, hess_mis);\n end\n\n function [lam_p, lam_q] = node_power_balance_prices(obj, nm)\n %% shadow prices on node power balance\n nne = obj.get_idx('nle');\n\n %% convert current balance shadow prices to equivalent lam_p and lam_q\n %% P + jQ = (Vr + jVi) * (M - jN)\n %% M = (Vr P + Vi Q) / (Vr^2 + Vi^2)\n %% N = (Vi P - Vr Q) / (Vr^2 + Vi^2)\n %% lam_p = df/dP = df/dM * dM/dP + df/dN + dN/dP\n %% lam_q = df/dQ = df/dM * dM/dQ + df/dN + dN/dQ\n V = nm.soln.v;\n lambda = obj.soln.lambda;\n VV = V ./ (V .* conj(V)); %% V / vm^2\n VVr = real(VV);\n VVi = imag(VV);\n lamM = lambda.eqnonlin(nne.i1.rImis:nne.iN.rImis);\n lamN = lambda.eqnonlin(nne.i1.iImis:nne.iN.iImis);\n lam_p = (VVr.*lamM + VVi.*lamN);\n lam_q = (VVi.*lamM - VVr.*lamN);\n end\n end %% methods\nend %% classdef\n", "meta": {"author": "MATPOWER", "repo": "matpower", "sha": "7da926d978824bf675a71e0a5cb91f8967f97007", "save_path": "github-repos/MATLAB/MATPOWER-matpower", "path": "github-repos/MATLAB/MATPOWER-matpower/matpower-7da926d978824bf675a71e0a5cb91f8967f97007/lib/+mp/math_model_opf_acci.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.343098936222237}} {"text": "function [dat, ref] = ft_preproc_rereference(dat, refchan, method, handlenan)\n\n% FT_PREPROC_REREFERENCE computes the average reference over all EEG channels\n% or rereferences the data to the selected channels\n%\n% Use as\n% [dat] = ft_preproc_rereference(dat, refchan, method, handlenan)\n% where\n% dat data matrix (Nchans X Ntime)\n% refchan vector with indices of the new reference channels, or 'all'\n% method string, can be 'avg' or 'median'\n% handlenan boolean, can be true or false\n%\n% If the new reference channel is not specified, the data will be\n% rereferenced to the average of all channels.\n%\n% See also PREPROC\n\n% Copyright (C) 1998-2017, Robert Oostenveld\n%\n% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org\n% for the documentation and details.\n%\n% FieldTrip is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% FieldTrip is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with FieldTrip. If not, see .\n%\n% $Id$\n\n% determine the size of the data\n[Nchans, Nsamples] = size(dat);\n\n% determine the new reference channels\nif nargin<2 || isempty(refchan) || (ischar(refchan) && strcmp(refchan, 'all'))\n refchan = 1:Nchans;\nend\n\nif nargin<3 || isempty(method)\n method = 'avg';\nend\n\nif nargin<4 || isempty(handlenan)\n handlenan = false;\nend\n\nhasnan = any(any(isnan(dat(refchan,:))));\n\nif hasnan && handlenan\n % preprocessing works differently if channels contain NaN\n switch method\n case 'avg'\n ref = nanmean(dat(refchan,:), 1);\n case 'median'\n ref = nanmedian(dat(refchan,:), 1);\n otherwise\n ft_error('unsupported method')\n end % switch\nelse\n % preprocessing fails on channels that contain NaN\n if any(isnan(dat(:)))\n ft_warning('FieldTrip:dataContainsNaN', 'data contains NaN values');\n end\n % compute the average value over the reference channels\n switch method\n case 'avg'\n ref = mean(dat(refchan,:), 1);\n case 'median'\n ref = median(dat(refchan,:), 1);\n otherwise\n ft_error('unsupported method')\n end % switch\nend\n\n% subtract the new reference from the data\nfor chan=1:Nchans\n dat(chan,:) = dat(chan,:) - ref;\nend\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/external/fieldtrip/preproc/ft_preproc_rereference.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7025300449389326, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.3430337556401173}} {"text": "## Copyright (C) 2013 CarnĂŤ Draug \n##\n## This program is free software; you can redistribute it and/or modify it under\n## the terms of the GNU General Public License as published by the Free Software\n## Foundation; either version 3 of the License, or (at your option) any later\n## version.\n##\n## This program is distributed in the hope that it will be useful, but WITHOUT\n## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more\n## details.\n##\n## You should have received a copy of the GNU General Public License along with\n## this program; if not, see .\n\n## -*- texinfo -*-\n## @deftypefn {Function File} {@var{cmap} =} ycbcr2rgb (@var{YCbCrmap})\n## @deftypefnx {Function File} {@var{RGB} =} ycbcr2rgb (@var{YCbCr})\n## @deftypefnx {Function File} {@dots{} =} ycbcr2rgb (@dots{}, [@var{Kb} @var{Kr}])\n## @deftypefnx {Function File} {@dots{} =} ycbcr2rgb (@dots{}, @var{standard})\n## Convert YCbCr color space to RGB.\n##\n## The convertion changes the image @var{YCbCr} or colormap @var{YCbCrmap},\n## from the YCbCr (luminance, chrominance blue, and chrominance red)\n## color space to RGB values. @var{YCbCr} must be of class double, single,\n## uint8, or uint16.\n##\n## The formula used for the conversion is dependent on two constants, @var{Kb}\n## and @var{Kr} which can be specified individually, or according to existing\n## standards:\n##\n## @table @asis\n## @item \"601\" (default)\n## According to the ITU-R BT.601 (formerly CCIR 601) standard. Its values\n## of @var{Kb} and @var{Kr} are 0.114 and 0.299 respectively.\n## @item \"709\" (default)\n## According to the ITU-R BT.709 standard. Its values of @var{Kb} and\n## @var{Kr} are 0.0722 and 0.2116 respectively.\n## @end table\n##\n## @seealso{hsv2rgb, ntsc2rgb, rgb2hsv, rgb2ntsc, rgb2ycbcr}\n## @end deftypefn\n\nfunction rgb = ycbcr2rgb (ycbcr, standard = \"601\")\n if (nargin < 1 || nargin > 2)\n print_usage ();\n endif\n rgb = ycbcrfunc (\"ycbcr2rgb\", ycbcr, standard);\nendfunction\n\n%!assert (ycbcr2rgb (rgb2ycbcr (jet (10))), jet (10), 0.00001);\n\n## Copyright (C) 2013 CarnĂŤ Draug \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## Private function for ycbcr2rgb and rgb2ycbcr functions which are\n## very similar\n\nfunction out = ycbcrfunc (func, in, standard)\n\n img = false; # was input an image?\n if (iscolormap (in))\n ## do nothing, it's a colormap\n elseif (isrgb (in))\n img = true;\n ## we shape it as a colormap (2D matrix) so we can use matrix multiplcation\n nRows = rows (in);\n nCols = columns (in);\n in = reshape (in, [nRows*nCols 3]);\n else\n error (\"%s: input must be a colormap (Nx3) or RGB image (NxMx3)\", func);\n endif\n\n if (ischar (standard))\n if (strcmpi (standard, \"601\")) # for ITU-R BT.601\n Kb = 0.114;\n Kr = 0.299;\n elseif (strcmpi (standard, \"709\")) # for ITU-R BT.709\n Kb = 0.0722;\n Kr = 0.2126;\n else\n error (\"%s: unknown standard `%s'\", func, standard);\n endif\n elseif (isnumeric (standard) && numel (standard) == 2)\n Kb = standard(1);\n Kr = standard(2);\n else\n error (\"%s: must specify a standard (string), or Kb and Kr values\", func);\n endif\n\n ## the color matrix for the conversion. Derived from:\n ## Y = Kr*R + (1-Kr-Kb)*G + kb*B\n ## Cb = (1/2) * ((B-Y)/(1-Kb))\n ## Cr = (1/2) * ((R-Y)/(1-Kr))\n ## It expects RGB values in the range [0 1], and returns Y in the\n ## range [0 1], and Cb and Cr in the range [-0.5 0.5]\n cmat = [ Kr (1-Kr-Kb) Kb\n -(Kr/(2-2*Kb)) -(1-Kr-Kb)/(2-2*Kb) 0.5\n 0.5 -(1-Kr-Kb)/(2-2*Kr) -(Kb/(2-2*Kr)) ];\n\n cls = class (in);\n in = im2double (in);\n\n ## note that these blocks are the inverse of one another. Changes\n ## in one will most likely require a change on the other\n if (strcmp (func, \"rgb2ycbcr\"))\n ## convert to YCbCr colorspace\n out = (cmat * in')'; # transpose at the end to get back colormap shape\n ## rescale Cb and Cr to range [0 1]\n out(:, [2 3]) += 0.5;\n ## footroom and headroom will take from the range 16/255 each for Cb and Cr,\n ## and 16/255 and 20/255 for Y. So we have to compress the values of the\n ## space, and then shift forward\n out(:,1) = (out(:,1) * 219/255) + 16/255;\n out(:,[2 3]) = (out(:,[2 3]) * 223/255) + 16/255;\n\n elseif (strcmp (func, \"ycbcr2rgb\"))\n ## just the inverse of the rgb2ycbcr conversion\n in(:,[2 3]) = (in(:,[2 3]) - 16/255) / (223/255);\n in(:,1) = (in(:,1) - 16/255) / (219/255);\n in(:,[2 3]) -= 0.5;\n out = (inv (cmat) * in')';\n else\n error (\"internal error for YCbCr conversion. Unknown function %s\", func);\n endif\n\n switch (cls)\n case {\"single\", \"double\"}\n ## do nothing. All is good\n case \"uint8\"\n out = im2uint8 (out);\n case \"uint16\"\n out = im2uint16 (out);\n otherwise\n error (\"%s: unsupported image class %s\", func, cls);\n endswitch\n\n if (img)\n ## put the image back together\n out = reshape (out, [nRows nCols 3]);\n endif\n\nendfunction\n", "meta": {"author": "fumin", "repo": "pencil", "sha": "31c5fd8cf4112e17592db5be1acf39aa8670e074", "save_path": "github-repos/MATLAB/fumin-pencil", "path": "github-repos/MATLAB/fumin-pencil/pencil-31c5fd8cf4112e17592db5be1acf39aa8670e074/ycbcr2rgb.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.640635868562172, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.34280324658946265}} {"text": "function [b, iCv, iC] = gp_looprep(gp, x, y)\n%GP_LOOPREP Calculates help terms needed in Gaussian GP LOO\n%\n% Description\n% [b, iCv] = gp_looprep(gp, x, y, varargin) takes GP structure,\n% training input and output and returns following terms\n% b = C\\y\n% iCv = diag(inv(C))\n% [b, iCv, iC] = gp_looprep(gp, x, y, varargin) returns additionally\n% iC = inv(C)\n% In case of CS, FIC, PIC and CS+FIC, these terms are computed\n% using appropriate efficient sparse matrix and inverse lemma\n% computations.\n% \n \n% Copyright (c) 2012 Aki Vehtari\n\n% This software is distributed under the GNU General Public\n% License (version 3 or later); please refer to the file\n% License.txt, included with the software, for details.\n \n \n switch gp.type\n case 'FULL' \n % FULL GP (and compact support GP)\n [K, C] = gp_trcov(gp, x);\n \n if issparse(C)\n if nargout==3\n iC = full(spinv(C)); % sparse inverse\n iCv = full(diag(iC)); % the diagonal of sparse inverse\n else\n iCv = full(diag(spinv(C))); % the diagonal of sparse inverse\n end\n [LD, notpositivedefinite] = ldlchol(C);\n if notpositivedefinite\n b = NaN;\n iCv = NaN;\n iC = NaN;\n return\n end\n b = ldlsolve(LD,y);\n else\n if nargout==3\n iC = inv(C); % full inverse\n iCv = diag(inv(C)); % the diagonal of full inverse\n else\n iCv = diag(inv(C)); % the diagonal of full inverse\n end\n b = C\\y;\n end\n \n case 'FIC' \n % FIC\n % Use inverse lemma for FIC low rank covariance matrix approximation\n % Code adapated from gp_pred\n \n u = gp.X_u;\n m = size(u,1);\n % Turn the inducing vector on right direction\n if size(u,2) ~= size(x,2)\n u=u';\n end\n [Kv_ff, Cv_ff] = gp_trvar(gp, x); % 1 x f vector\n K_fu = gp_cov(gp, x, u); % f x u\n K_uu = gp_trcov(gp, u); % u x u, noiseles covariance K_uu\n [Luu, notpositivedefinite] = chol(K_uu,'lower');\n if notpositivedefinite\n b = NaN;\n iCv = NaN;\n iC = NaN;\n return\n end\n B=Luu\\(K_fu');\n Qv_ff=sum(B.^2)';\n Lav = Cv_ff-Qv_ff; % 1 x f, Vector of diagonal elements\n \n % iLaKfu = diag(inv(Lav))*K_fu = inv(La)*K_fu\n iLaKfu = zeros(size(K_fu)); % f x u,\n n=size(x,1);\n for i=1:n\n iLaKfu(i,:) = K_fu(i,:)./Lav(i); % f x u\n end\n A = K_uu+K_fu'*iLaKfu;\n A = (A+A')./2;\n L = iLaKfu/chol(A);\n \n if nargout==3\n iC = diag(1./Lav) - L*L'; % Cv = inv(C);\n iCv = diag(iC); % iCv = diag(inv(C));\n else\n iCv = 1./Lav - sum(L.^2,2); % iCv = diag(inv(C));\n end\n b = y./Lav - L*(L'*y); % b = C\\y;\n \n case {'PIC' 'PIC_BLOCK'}\n % PIC\n % Use inverse lemma for PIC low rank covariance matrix approximation\n % Code adapated from gp_pred\n \n u = gp.X_u;\n ind = gp.tr_index;\n if size(u,2) ~= size(x,2)\n % Turn the inducing vector on right direction\n u=u';\n end\n\n % Calculate some help matrices\n [Kv_ff, Cv_ff] = gp_trvar(gp, x); % 1 x f vector\n K_fu = gp_cov(gp, x, u); % f x u\n K_uu = gp_trcov(gp, u); % u x u, noiseles covariance K_uu\n Luu = chol(K_uu)';\n\n % Evaluate the Lambda (La) for specific model\n % Q_ff = K_fu*inv(K_uu)*K_fu'\n % Here we need only the diag(Q_ff), which is evaluated below\n B=Luu\\K_fu';\n iLaKfu = zeros(size(K_fu)); % f x u\n for i=1:length(ind)\n Qbl_ff = B(:,ind{i})'*B(:,ind{i});\n [Kbl_ff, Cbl_ff] = gp_trcov(gp, x(ind{i},:));\n La{i} = Cbl_ff - Qbl_ff;\n iLaKfu(ind{i},:) = La{i}\\K_fu(ind{i},:); \n end\n A = K_uu+K_fu'*iLaKfu;\n A = (A+A')./2; % Ensure symmetry\n L = iLaKfu/chol(A);\n\n % From this on evaluate the prediction\n % See Snelson and Ghahramani (2007) for details\n n=size(y,1);\n iCv=zeros(n,1);\n if nargout==3\n iC=zeros(n,n);\n end\n for i=1:length(ind)\n if nargout==3\n iC(ind{i},ind{i}) = inv(La{i});\n else\n iCv(ind{i},:) = diag(inv(La{i}));\n end\n b(ind{i},:) = La{i}\\y(ind{i},:);\n end\n if nargout==3\n iC = iC - L*L'; % iC = inv(C);\n iCv = diag(iC); % iCv = diag(inv(C));\n else\n iCv = iCv - sum(L.^2,2); % iCv = diag(inv(C));\n end\n b = b - L*(L'*y); % b = C\\y;\n\n case 'CS+FIC'\n % CS+FIC\n % Use inverse lemma for CS+FIC\n % Code adapated from gp_pred\n \n u = gp.X_u;\n if size(u,2) ~= size(x,2)\n % Turn the inducing vector on right direction\n u=u';\n end\n \n n = size(x,1);\n m = size(u,1);\n ncf = length(gp.cf);\n \n % Indexes to all non-compact support and compact support covariances.\n cf1 = [];\n cf2 = [];\n\n % Loop through all covariance functions\n for i1 = 1:ncf \n if ~isfield(gp.cf{i1},'cs') \n % Non-CS covariances\n cf1 = [cf1 i1];\n else\n % CS-covariances\n cf2 = [cf2 i1]; \n end\n end\n \n % First evaluate needed covariance matrices\n % v defines that parameter is a vector\n [Kv_ff, Cv_ff] = gp_trvar(gp, x, cf1); % f x 1 vector \n K_fu = gp_cov(gp, x, u, cf1); % f x u\n K_uu = gp_trcov(gp, u, cf1); % u x u, noiseles covariance K_uu\n K_uu = (K_uu+K_uu')./2; % ensure the symmetry of K_uu\n\n Luu = chol(K_uu)';\n % Evaluate the Lambda (La)\n % Q_ff = K_fu*inv(K_uu)*K_fu'\n B=Luu\\(K_fu'); % u x f\n Qv_ff=sum(B.^2)';\n Lav = Cv_ff-Qv_ff; % f x 1, Vector of diagonal elements\n\n K_cs = gp_trcov(gp,x,cf2);\n La = sparse(1:n,1:n,Lav,n,n) + K_cs;\n\n iLaKfu = La\\K_fu;\n A = K_uu+K_fu'*iLaKfu;\n A = (A+A')./2; % Ensure symmetry\n L = iLaKfu/chol(A);\n \n if nargout==3\n iC = inv(La) - L*L'; % iCv = diag(inv(C));\n iCv = diag(iC) ; % iCv = diag(inv(C));\n else\n iCv = diag(inv(La)) - sum(L.^2,2); % iCv = diag(inv(C));\n end\n b = La\\y - L*(L'*y); % b = C\\y;\n \n case 'SSGP' % SSGP\n error('GP_LOOPRED is not yet implemented for SSGP and Gaussian likelihood')\n \n otherwise\n error('Unknown type of Gaussian process')\n end\n\nend\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/dmlt/external/gpstuff/gp/private/gp_looprep.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7185943925708562, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.3424674648677329}} {"text": "function varargout = pdeSolve(pdeFun, tIn, u0, bc, varargin)\n%PDESOLVE Solve PDEs using Chebfun.\n%\n% PDESOLVE() solves solves an initial-boundary value problem via a method of\n% lines approach. See @CHEBFUN/PDE15S() for documentation.\n%\n% See also PDE15S, PDE23T, PDESET.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers. \n% See http://www.chebfun.org/ for Chebfun information.\n\nglobal DIFFORDER SYSSIZE\nDIFFORDER = 0;\nSYSSIZE = 0;\n\n% Default options:\ntol = 1e-6; % 'eps' in Chebfun terminology\n% The default behaviour with no outputs is to plot. If the method is called with\n% outputs, by default, we don't plot.\ndoPlot = ( nargout == 0 );\ndoHold = false; % Hold plot?\nplotOpts = {'-'}; % Plotting style\nadjustBCs = true; % Adjust inconsistent BCs\nthrowBCwarning = true; % Throw a warning for inconsistent BCs\ntimeChunks = 51; % Default number of time slices if not specified\n\n% Parse the variable inputs:\nif ( numel(varargin) == 2 )\n opt = varargin{1};\n opt.N = varargin{2};\nelseif ( numel(varargin) == 1 )\n if ( isstruct(varargin{1}) )\n opt = varargin{1};\n else\n opt = pdeset;\n opt.N = varargin{1};\n end\nelse\n opt = pdeset;\nend\noptN = opt.N;\nif ( isempty(optN) )\n optN = NaN;\nend\n\n% Get the domain:\nDOMAIN = domain(u0, 'ends');\n\nif ( isfield(opt, 'AdjustBCs') && ~isempty(opt.AdjustBCs) && ~opt.AdjustBCs )\n throwBCwarning = false;\n adjustBCs = false;\nend\n\n% PDE solver options:\nif ( ~isempty(opt.Eps) )\n tol = opt.Eps;\nend\nif ( ~isempty(opt.Plot) )\n doPlot = strcmpi(opt.Plot, 'on');\nend\nif ( ~isempty(opt.HoldPlot) )\n doHold = strcmpi(opt.HoldPlot, 'on') || strcmp(opt.HoldPlot, '1');\nend\nif ( ~isempty(opt.PlotStyle) )\n plotOpts = opt.PlotStyle;\nend\nif ( ~isempty(opt.ODESolver) )\n ODESOLVER = opt.ODESolver;\nelse\n ODESOLVER = @ode15s;\nend\n\n% Set time chunks:\nif ( length(tIn) == 2 )\n tt = linspace(tIn(1), tIn(2), timeChunks);\nelse\n tt = tIn;\nend\n\nuserMassSet = false;\nISPERIODIC = false;\nDONE = false;\nCOUNTER = 1;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% %%%%%%%%%%%%%%%%%%%%%%%%%% PARSE INPUTS TO PDEFUN %%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% Determine the size of the system, i.e., number of dependent variables.\nSYSSIZE = min(size(u0));\n[pdeFun, varNamesParsed] = parseFun(pdeFun);\nif ( isfield(opt, 'difforder') )\n DIFFORDER = opt.difforder;\nelse\n getDIFFORDER(pdeFun, DOMAIN);\nend\n\nif ( (max(DIFFORDER) < 2) && isequal(ODESOLVER, @ode15s) )\n warning('CHEBFUN:PdeSolver', ...\n 'PDE23T() is recommended for non-diffusive problems.');\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% EVENT SETUP %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nif ( ~isnan(optN) )\n opt.OutputFcn = @nonAdaptiveEvent;\nelse\n opt.OutputFcn = @adaptiveEvent;\nend\n\n function status = nonAdaptiveEvent(t, U, flag)\n % This event is called at the end of each chunk in non-adaptive mode.\n status = false;\n if ( ~isempty(flag) )\n return\n end\n \n % Sometimes we get given more than one time slice.\n for kk = 1:numel(t)\n \n if ( ~any(abs(tSpan - t(kk)) < 1e-6) )\n % This is not a designated time slice!\n continue\n end\n \n % Reshape solution:\n Uk = reshape(U(:,kk), n, SYSSIZE);\n uCurrent = chebfun(Uk, DOMAIN, 'tech', techHandle);\n tCurrent = t(kk);\n % Store for output:\n COUNTER = COUNTER + 1;\n uOut{COUNTER} = uCurrent;\n\n % Plot current solution:\n if ( doPlot )\n plotFun(uCurrent, t(kk));\n end\n end\n \n if ( guiFlag )\n status = guiEvent(status);\n end\n\n end\n\n function status = adaptiveEvent(t, U, flag)\n % This event is called at the end of each chunk in adaptive mode.\n\n status = false;\n if ( ~isempty(flag) )\n return\n end\n\n % Sometimes we get given more than one time slice.\n for kk = 1:numel(t)\n % Reshape solution:\n Uk = reshape(U(:,kk), currentLength, SYSSIZE);\n\n % Happiness check:\n c = (1+sin(1:SYSSIZE)).'; % Arbitrarily linear combination.\n Uk2 = (Uk*c/sum(c));\n uk2 = tech.make(Uk2, pref);\n [ishappy, cutoff] = happinessCheck(uk2, Uk2, [], [], pref); %#ok\n\n if ( ishappy ) \n\n if ( ~any(abs(tSpan - t(kk)) < 1e-6) )\n % This is not a designated time slice!\n continue\n end\n\n % Store these values:\n tCurrent = t(kk);\n uCurrent = chebfun(Uk, DOMAIN, 'tech', techHandle);\n uCurrent = simplify(uCurrent);\n \n COUNTER = COUNTER + 1;\n uOut{COUNTER} = uCurrent;\n tOut(COUNTER) = tCurrent;\n\n % Plot current solution (if plotting is on)\n if ( doPlot )\n plotFun(uCurrent, tCurrent);\n end\n % TODO: Re-insert this?\n% % If we have 2.5 times as many coefficients as we need then \n% % shorten the representation and cause the integrator to stop. \n% if ( cutoff < 0.4*n && n > 17)\n% currentLength = round(1.25*cutoff)';\n% %currentLength = floor( currentLength / 1.5 );\n% currentLength = currentLength + 1 - rem(currentLength,2);\n% currentLength = max(currentLength, 17);\n% status = true;\n% return\n% end\n \n else \n\n % Increase length and bail out:\n currentLength = 2*currentLength-1;\n status = true;\n break\n \n end \n \n if ( guiFlag )\n status = guiEvent(status);\n end\n \n end\n\n end\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% %%%%%%%%%%%%%%%%%%%%%%%%%%%% PLOTTING SETUP %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% Determine which figure to plot to (for CHEBGUI) and set default display values\n% for variables.\nYLim = opt.YLim;\ngridOn = 0;\nguiFlag = false;\nif ( isfield(opt, 'handles') )\n if ( opt.handles.gui )\n guiFlag = true;\n axesSol = opt.handles.fig_sol;\n axesNorm = opt.handles.fig_norm;\n gridOn = opt.handles.guifile.options.grid;\n solveButton = opt.handles.button_solve;\n clearButton = opt.handles.button_clear;\n panelSol = opt.handles.panel_figSol;\n end\n varNames = opt.handles.varnames;\n xLabel = opt.handles.indVarName{1};\n tlabel = opt.handles.indVarName{2};\n fontsize = opt.handles.fontsizePanels;\n set(axesSol, 'fontsize', fontsize);\nelse\n % Obtain the correct variable names from the parsing of the operator\n if ( length(varNamesParsed) == numColumns(u0) )\n % Space and time variables did not get passed explicitly to operator\n tlabel = 't';\n xLabel = 'x';\n else\n tlabel = varNamesParsed{1};\n xLabel = varNamesParsed{2};\n end\n varNames = varNamesParsed(end-numColumns(u0)+1:end);\n if ( doPlot ) % Set up ploting in non-gui mode\n axesSol = gca;\n cla(axesSol)\n xlabel(axesSol, xLabel);\n % Bring attention to the figure\n shg\n end\nend\n\n% Set plot options\nif ( doPlot )\n \n % Use linear scale. Always.\n if ( ~ishold )\n set(gca, 'XScale', 'Linear', 'YScale', 'Linear');\n end\n \n set(axesSol, 'NextPlot', 'replacechildren');\n \n % Fix x limits\n set(axesSol, 'xLim', u0.domain);\n \n % Fix y limits if they were specified\n if ( ~isempty(YLim) )\n set(axesSol, 'ylim', YLim);\n end\n \n % Initialize lines for plotting\n hLines = plot(axesSol, DOMAIN, NaN(length(DOMAIN), numColumns(u0)), ...\n plotOpts{:});\n \n % Grid on?\n if ( gridOn )\n grid(axesSol, 'on')\n else\n grid(axesSol, 'off')\n end\n \n % Hold on?\n if ( doHold )\n hold(axesSol, 'on')\n else\n hold(axesSol, 'off')\n end\n \n % For plotting, it's useful to know whether we're running in old or new\n % Matlab graphics mode\n if ( ~verLessThan('matlab', '8.4') )\n newMatlabVersion = true;\n else\n newMatlabVersion = false;\n end\nend\n\n\n function status = guiEvent(status)\n %GUIEVENT Deal with GUI events ('stop', 'pause', etc). \n % OUTPUTS:\n % status = true exits the current time chunk.\n % DONE = true exits PDE solver. (Note DONE is a GLOBAL variable).\n\n % Interrupt computation if stop or pause button is pressed in the GUI.\n if ( strcmp(get(solveButton, 'String'), 'Solve') )\n % Stop.\n tt = tt( tt <= tCurrent );\n uOut(COUNTER+1:end) = [];\n status = true;\n DONE = true;\n elseif ( strcmp(get(clearButton, 'String'), 'Continue') )\n % Wait, pause.\n \n % Plot a waterfall plot to the bottom figure window:\n axes(axesNorm)\n uuTmp = prepare4output(uOut(1:COUNTER));\n if ( SYSSIZE == 1 )\n waterfall(uuTmp, tt(tt<=tCurrent), 'linewidth', 2);\n else\n cols = get(0, 'DefaultAxesColorOrder');\n waterfall(uuTmp, tt(tt<=tCurrent), 'linewidth', 2, ...\n 'EdgeColors', cols);\n end\n xlabel(xLabel), ylabel(tlabel), zlabel(varNames)\n if ( gridOn )\n grid on\n end\n view([322.5 30])\n box off\n axes(axesSol)\n % Hang around until 'CONTINUE' or 'STOP' is presed.\n waitfor(clearButton, 'String');\n % Call again to see if 'STOP' was pressed.\n status = guiEvent(status);\n \n set(axesNorm, 'fontsize', fontsize);\n end\n end\n\n function plotFun(U, t)\n %PLOTFUN Plot current solution U at a time t.\n\n % Obtain plotting data for the solution\n Udata = plotData(U);\n UdataX = Udata.xLine;\n UdataY = Udata.yLine;\n \n % Update the YData of the lines plotted\n if ( ~doHold )\n for hCounter = 1:length(hLines)\n set(hLines(hCounter), 'XData', UdataX);\n set(hLines(hCounter), 'YData', UdataY(:, hCounter)');\n end\n else\n % Reset color cycle prior to point plot if running R2014b.\n if ( newMatlabVersion )\n set(axesSol, 'ColorOrderIndex', 1);\n end\n hLines = plot(axesSol, UdataX, UdataY, plotOpts{:});\n end\n \n % Update the title, either of the GUI panel or the figure\n if ( guiFlag )\n set(panelSol, 'Title', sprintf('%s = %.3f', tlabel, t))\n elseif ( nargin > 1 )\n title(sprintf('%s = %.3f', tlabel, t))\n end\n \n % Update the plot\n drawnow\n\n end\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% %%%%%%%%%%%%%%%%%%%%%%%%% PARSE BOUNDARY CONDITIONS %%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nif ( ischar(bc) && (strcmpi(bc, 'neumann') || strcmpi(bc, 'dirichlet')) )\n bc = struct( 'left', bc, 'right', bc);\nelseif ( iscell(bc) && numel(bc) == 2 )\n bc = struct( 'left', bc{1}, 'right', bc{2});\nend\nif ( isstruct(bc) && ~isfield(bc, 'middle') )\n bc.middle.op = [];\nend\n\n% Initialise some global variables.\nnumLinBCs = 0; % linear BCS (total)\nnumLBCs = 0; % nonlinear LBCs\nnumMBCs = 0; % nonlinear other constraints\nnumRBCs = 0; % nonlinear RBCs\nBCRHS = {}; % RHS values for BCs\n\n % Differentiation matrices at left and right endpoints:\n function D = neumannLeft(n)\n x = -cos(pi*(1:n-2)/(n-1));\n D = [0, 2./(1+x), .5]; \n D(1:2:end) = -D(1:2:end);\n D(1) = -sum(D);\n end\n function D = neumannRight(n)\n x = -cos(pi*(1:n-2)/(n-1));\n D = [-.5, 2./(x-1), 0]; \n D(end:-2:1) = -D(end:-2:1);\n D(end) = -sum(D);\n end\n\nif ( ischar(bc) && any(strcmpi(bc, {'periodic', 'trig'})) )\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%% PERIODIC BCS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n \n ISPERIODIC = true;\n \n % One can still use a Chebyshev basis and enforce periodic conditions by\n % enforcing suitable constraints on the derivative. However, using a\n % periodic basis (for now, trigtech) is much more efficient.\n% r = cell(sum(DIFFORDER), 1);\n% count = 1;\n% for j = 1:SYSSIZE\n% for k = 0:DIFFORDER(j)-1\n% c = (diff(DOMAIN)/2)^k;\n% A = @(n) [1 zeros(1, n-2) -1]*chebcolloc2.diffmat(n, k)*c;\n% r{count} = @(n) [zeros(1, (j-1)*n) A(n) zeros(1,(SYSSIZE-j)*n)];\n% count = count + 1;\n% end\n% end\n% bc = struct( 'left', [], 'right', []);\n% bc.left.op = r(1:2:end);\n% bc.right.op = r(2:2:end);\n% BCRHS = num2cell(zeros(1, numel(r)));\n \nelse\n %%%%%%%%%%%%%%%%%%%%%%%%%%% NONPERIODIC BCS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n if ( isfield(bc, 'left') && ~isfield(bc, 'right') )\n bc.right = [];\n elseif ( isfield(bc, 'right') && ~isfield(bc, 'left') )\n bc.left = [];\n elseif ( ~isfield(bc, 'left') && ~isfield(bc, 'right') )\n bc = struct('left', [], 'right', [], 'middle', bc);\n end\n \n % Deal with struct and numeric input:\n bc.left = dealWithStructInput(bc.left);\n bc.right = dealWithStructInput(bc.right);\n \n % Temporary chebdouble for evaluating BC function handles:\n uTmp = chebdouble(ones(1, SYSSIZE), DOMAIN);\n \n %% LEFT BCS\n if ( isempty(bc.left) )\n bc.left = struct('op', []);\n \n elseif ( ischar(bc.left) || (iscell(bc.left) && ischar(bc.left{1})) )\n %%%%%%%%%%%%%%%%%%% DIRICHLET AND NEUMANN BCS (LEFT) %%%%%%%%%%%%%%%%%\n if ( iscell(bc.left) )\n v = bc.left{2};\n bc.left = bc.left{1};\n else\n v = 0;\n end\n if ( ~isnumeric(v) )\n error('CHEBFUN:CHEBFUN:pde15s:nonNumericVal1', ...\n 'For BCs of the form {char, val} val must be numeric.')\n end\n BCRHS = num2cell(repmat(v, SYSSIZE, 1));\n numLinBCs = numel(v)*SYSSIZE;\n \n if ( strcmpi(bc.left, 'dirichlet') )\n A = @(n) [1, zeros(1, n-1)];\n elseif ( strcmpi(bc.left, 'neumann') )\n A = @(n) neumannLeft(n)*(diff(DOMAIN)/2);\n else\n error('CHEBFUN:CHEBFUN:pde15s:bcSyntax1', 'Unknown BC syntax');\n end\n bc.left = struct('op', []);\n bc.left.op = cell(SYSSIZE, 1);\n for k = 1:SYSSIZE\n bc.left.op{k} = ...\n @(n) [zeros(1,(k-1)*n), A(n), zeros(1, (SYSSIZE-k)*n)];\n end\n \n elseif ( numel(bc.left) == 1 && isa(bc.left, 'function_handle') )\n %%%%%%%%%%%%%%%%%%%%%%% GENERAL BCS (LEFT) %%%%%%%%%%%%%%%%%%%%%%%%%%\n opLBC = parseFun(bc.left, 'lbc');\n numLBCs = max(size(opLBC(0, DOMAIN(1), uTmp)));\n bc.left = struct('op', []);\n \n else\n error('CHEBFUN:CHEBFUN:pde15s:bcSyntax2', 'Unknown BC syntax');\n \n end\n \n %% MIDDLE BCS / OTHER CONSTRAINTS\n if ( isfield(bc, 'middle') && isa(bc.middle, 'function_handle') )\n %%%%%%%%%%%%%%%%%%%%% GENERAL BCS (MIDDLE) %%%%%%%%%%%%%%%%%%%%%%%%%%\n opMBC = parseFun(bc.middle, 'bc');\n numMBCs = max(size(opMBC(0, mean(DOMAIN), uTmp)));\n bc.middle = [];\n \n end\n \n %% RIGHT BCS\n if ( isempty(bc.right) )\n bc.right = struct('op', []);\n \n elseif ( ischar(bc.right) || (iscell(bc.right) && ischar(bc.right{1})) )\n %%%%%%%%%%%%%%%%%%% DIRICHLET AND NEUMANN BCS (RIGHT) %%%%%%%%%%%%%%%%%\n if ( iscell(bc.right) )\n v = bc.right{2};\n bc.right = bc.right{1};\n else\n v = 0;\n end\n if ( ~isnumeric(v) )\n error('CHEBFUN:CHEBFUN:pde15s:nonNumericVal1', ...\n 'For BCs of the form {char, val} val must be numeric.')\n end\n BCRHS = [BCRHS, num2cell(repmat(v, SYSSIZE, 1))];\n numLinBCs = numLinBCs + numel(v)*SYSSIZE;\n \n if ( strcmpi(bc.right, 'dirichlet') )\n A = @(n) [zeros(1, n-1), 1];\n elseif ( strcmpi(bc.right, 'neumann') )\n A = @(n) neumannRight(n)*(diff(DOMAIN)/2);\n else\n error('CHEBFUN:CHEBFUN:pde15s:bcSyntax3', 'Unknown BC syntax');\n end\n bc.right = struct('op', []);\n bc.right.op = cell(SYSSIZE, 1);\n for k = 1:SYSSIZE\n bc.right.op{k} = ...\n @(n) [zeros(1,(k-1)*n), A(n), zeros(1,(SYSSIZE-k)*n)];\n end\n \n elseif ( numel(bc.right) == 1 && isa(bc.right, 'function_handle') )\n %%%%%%%%%%%%%%%%%%%%%% GENERAL BCS (RIGHT) %%%%%%%%%%%%%%%%%%%%%%%%%%\n opRBC = parseFun(bc.right, 'rbc');\n numRBCs = max(size(opRBC(0, DOMAIN(end), uTmp)));\n bc.right = struct('op', []);\n \n else\n error('CHEBFUN:CHEBFUN:pde15s:bcSyntax4', 'Unknown BC syntax');\n \n end\n \nend\n\n% Total number of BCs:\nnumBCs = numLinBCs + numLBCs + numMBCs + numRBCs;\n\nif ( isstruct(bc) && ~isfield(bc, 'middle') )\n bc.middle.op = [];\nend\n\n%% %%%%%%%%%%%%%%%%%%%%%%% SUPPORT FOR COUPLED BVP-PDES! %%%%%%%%%%%%%%%%%%%%%%%\n% Experimental feature for coupled ode/pde systems: (An entry equal to 1 denotes\n% that the corresponding variable appears with a time derivative. 0 otherwise.)\nif ( isfield(opt, 'PDEflag') && ~isempty(opt.PDEflag) )\n pdeFlag = opt.PDEflag;\nelse\n pdeFlag = true;\nend\nif ( numel(pdeFlag) == 1 )\n pdeFlag = repmat(pdeFlag, 1, SYSSIZE);\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% PERIODIC %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nif ( ~ISPERIODIC )\n techHandle = @chebtech2;\n points = @chebpts;\n mydouble = @chebdouble;\nelse\n techHandle = @trigtech;\n points = @trigpts;\n mydouble = @trigdouble; \n u0 = chebfun(u0, 'trig', 'eps', tol);\n u0 = simplify(u0, tol);\nend\ntech = techHandle();\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% %%%%%%%%%%%%%%%%%%% SETUP TOLERANCES AND INITIAL CONDITION %%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% ODE tolerances:\naTol = odeget(opt, 'AbsTol', tol);\nrTol = odeget(opt, 'RelTol', tol);\nif ( isnan(optN) )\n aTol = min(aTol, tol);\n rTol = min(rTol, tol);\nend\nopt.AbsTol = aTol;\nopt.RelTol = rTol;\n\n% Check for (and try to remove) piecewise initial conditions:\nu0Trans = u0(1).isTransposed;\nif ( u0Trans )\n u0 = transpose(u0);\nend\nfor k = 1:numel(u0)\n if ( numel(u0(k).funs) > 1 )\n u0(k) = merge(u0(k), 'all', 1025, tol);\n if ( u0(k).nfuns > 1 )\n error('CHEBFUN:CHEBFUN:pde15s:piecewise', ...\n 'Piecewise initial conditions are not supported.');\n end\n end\nend\n\n% Simplify initial condition to tolerance or fixed size in optN:\nif ( isnan(optN) )\n u0 = simplify(u0);\nelse\n for k = 1:numel(u0)\n u0(k).funs{1}.onefun = prolong(u0(k).funs{1}.onefun, optN);\n end\nend\n\n% Initial condition:\nuCurrent = u0;\n% Storage:\nuOut = cell(1, numel(tt));\nuOut{1} = uCurrent;\ntOut(1) = tt(1);\n\n% Initialise variables for ONESTEP():\nM = []; P = []; n = []; B = 0;\n\n% Set the preferences:\npref = tech.techPref();\npref.chebfuneps = tol;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% %%%%%%%%%%%%%%%%%%%%%%%%%%%% TIME CHUNKS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% Plot initial condition:\ncurrentLength = length(u0);\nif ( doPlot )\n plotFun(u0, tt(1));\n leg = legend(axesSol, varNames);\n set(leg, 'HandleVisibility', 'off')\n drawnow\nend\nDONE = false;\n\nif ( ~isnan(optN) )\n % Non-adaptive in space:\n currentLength = optN;\n tSpan = tt;\n solvePDE(tSpan); % Do all chunks at once!\n \nelse\n % Adaptive in space\n \n % Min-length is 9\n currentLength = max(currentLength, 9);\n tCurrent = tt(1);\n tSpan = tt;\n while ( tCurrent < tt(end) && ~DONE )\n tSpan(tSpan < tCurrent) = [];\n solvePDE(tSpan);\n end\n\nend\n\nif ( doPlot && ~doHold )\n hold off\nend\n\n% Ensure tOut is a column vector\ntOut = tOut(:);\n\nuOut = prepare4output(uOut);\n\n function uOut = prepare4output(uIn)\n % If we only had one dependent variable, return an array valued CHEBFUN\n % instead of a QUASIMATRIX.\n if ( SYSSIZE == 1 )\n uOut = horzcat(uIn{:});\n else\n blocks = cell(SYSSIZE, numel(uIn));\n for kk = 1:SYSSIZE\n blocks(kk,:) = cellfun(@(u) extractColumns(u, kk), uIn, ...\n 'UniformOutput', false);\n end\n uOut = chebmatrix(blocks); % CHEBMATRIX\n end\n end\n\nswitch nargout\n case 0\n case 1\n if ( length(tIn) == 2 ) % Only T_start and T_end were given.\n uOut = uOut(:,[1,end]); % Strip intermediate steps.\n end\n varargout{1} = uOut;\n case 2\n varargout{1} = tOut;\n varargout{2} = uOut;\n case 1 + size(uOut, 1)\n varargout{1} = tOut;\n for varCounter = 1:size(uOut, 1)\n varargout{varCounter + 1} = chebfun(uOut(varCounter,:)); %#ok\n end\n otherwise\n error('CHEBFUN:CHEBFUN:pdeSolve:nargout', ...\n 'Incorrect number of output arguments.');\nend\n\nclear global\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ONESTEP %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n function solvePDE(tSpan)\n % Constructs the result of one time chunk at fixed discretization.\n\n % Evaluate the chebfun at discrete points:\n x = points(currentLength, DOMAIN);\n U0 = feval(uCurrent, x);\n\n if ( ISPERIODIC )\n \n % The discretisation length\n n = currentLength;\n \n elseif ( isempty(n) || (n ~= currentLength) )\n % This depends only on the size of n. If this is the same, reuse!\n \n % The new discretisation length\n n = currentLength;\n \n % Linear constraints:\n if ( numLinBCs > 0 )\n bcop = [bc.left.op ; bc.middle.op ; bc.right.op];\n B = cell2mat(cellfun(@(f) feval(f, n), bcop, 'UniformOutput', false));\n end\n \n % Zero matrix for algebraic (boundary) terms:\n Z = zeros(numBCs, SYSSIZE*n);\n % Initialise evaluated BC rhs vector:\n q = zeros(numBCs, 1);\n \n % Project / mass matrix.\n P = cell(1, SYSSIZE);\n M = cell(1, SYSSIZE);\n \n for kk = 1:SYSSIZE\n% xk = chebpts(n-DIFFORDER(kk), DOMAIN, 1);\n xk = chebpts(n-DIFFORDER(kk)+2, DOMAIN, 2); xk([1,end]) = [];\n P{kk} = barymat(xk, x);\n M{kk} = pdeFlag(kk)*P{kk};\n end\n P = [ Z ; blkdiag(P{:}) ];\n M = [ Z ; blkdiag(M{:}) ];\n \n % Multiply by user-defined mass matrix\n if ( userMassSet )\n M = feval(userMass, n)*M;\n end\n \n % ODE options: (mass matrix)\n opt = odeset(opt, 'Mass', M, 'MassSingular', 'yes', ...\n 'MStateDependence', 'none');\n \n end\n \n if ( ~ISPERIODIC )\n % We have to ensure the starting condition satisfies the boundary\n % conditions, or else we will get a singularity in time. We do this\n % by tweaking the BC values to match the reality. Changing the IC\n % itself is much trickier. Find out what the BC deviance from\n % nominal really is:\n BCVALOFFSET = 0; % recover nominal value in next call\n F = odeFun(tSpan(1), U0(:)); % also assigns values to \"q\"\n\n % If this is for the initial chunk, check whether the initial\n % condition nearly satisfies the BCs. We're quite lax about this,\n % because discretization at low N can cause derivatives to look\n % fairly bad.\n BCrows = 1:numBCs;\n if ( throwBCwarning && (length(uOut) > 1) && ...\n (norm(F(BCrows)) > 0.05*norm(F)) )\n warning('CHEBFUN:CHEBFUN:pde15s:BadIC',...\n 'Initial state may not satisfy the boundary conditions.')\n throwBCwarning = false;\n end\n if ( adjustBCs )\n BCVALOFFSET = F(BCrows) - q;\n end\n end\n \n % Solve ODE over time chunk with the selected solver:\n try\n [~, ~] = ODESOLVER(@odeFun, tSpan, U0, opt);\n catch ME\n if ( strcmp(ME.identifier, 'MATLAB:odearguments:SizeIC') )\n error('CHEBFUN:CHEBFUN:pde15s:dims', ...\n 'Dimension mismatch. Check boundary conditions.');\n else\n rethrow(ME)\n end\n end \n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n %% %%%%%%%%%%%%%%%%%%%%%%%%%%% ODEFUN %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n function F = odeFun(t, U)\n % This is what the ODESOLVER() calls.\n \n % Reshape to n by SYSSIZE:\n U = reshape(U, n, SYSSIZE);\n \n % Evaluate the PDEFUN:\n myU = mydouble(U, DOMAIN);\n F = double(pdeFun(t, x, myU));\n F = F(:);\n \n if ( ISPERIODIC )\n return\n end\n \n % Enforce boundary constraints:\n \n % Project:\n F = P*F; \n \n % Replacements for the BC algebraic conditions:\n if ( numLinBCs > 0 )\n % Get the right-hand sides: (may be time-dependent)\n for l = 1:numLinBCs\n if ( isa(BCRHS{l}, 'function_handle') )\n q(l,1) = feval(BCRHS{l}, t);\n else\n q(l,1) = BCRHS{l};\n end\n end\n indx = 1:numLinBCs;\n F(indx) = B*U(:) - q(indx); \n else\n indx = 0;\n end\n \n % Replacements for the nonlinear BC conditions:\n if ( numLBCs > 0 )\n indx = indx(end) + (1:numLBCs);\n fTmp = double(opLBC(t, x, myU));\n F(indx) = fTmp(1, :);\n end\n if ( numMBCs > 0 )\n % TODO: This won't work if there are also left nonlin BCs\n indx = indx(end) + (1:numMBCs);\n F(indx) = double(opMBC(t, x, myU));\n end \n if ( numRBCs > 0 )\n indx = indx(end) + (1:numRBCs);\n fTmp = double(opRBC(t, x, myU));\n F(indx) = fTmp(end,:);\n end\n \n % Adjust BC rows by the needed offset from original time:\n indx = 1:numBCs;\n F(indx) = F(indx) - BCVALOFFSET;\n \n end\n end\n\nend\n\n%% %%%%%%%%%%%%%%%%%%%%%%%%%% MISC %%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [outFun, varNamesParsed] = parseFun(inFun, bcFlag)\n% Rewrites the input function handle to call the right DIFF, SUM, methods, etc,\n% and convert the input @(t, x, u, v, w, ...) to @(t, x, U).\n%\n% For PARSEFUN(INFUN), if the INFUN has only one independent variable as an\n% input, we assume this is x. PARSEFUN(INFUN, 'lbc') or PARSEFUN(INFUN, 'rbc')\n% will assume the variable is t. PARSEFUN(INFUN, 'bc') will assume space, but\n% throw a warning.\n\nglobal SYSSIZE\n\n% Ensure backwards compatibility by processing the input function.\n[inFun, varNamesParsed] = backCompat(inFun);\n\n% V4: We don't accept only time or space as input args (i.e., both or nothing).\n% V5: Actually, we now accept @(u, x) diff(u, 2) + sin(x).*u (for CHEBOPs).\nNind = nargin(inFun) - SYSSIZE;\nif ( Nind == 0 )\n outFun = @(t, x, u) conv2cell(inFun, u);\nelseif ( Nind == 1 )\n if ( nargin > 1 )\n if ( strcmp(bcFlag, 'bc') )\n warning('CHEBFUN:CHEBFUN:pde15s:bcInput', ...\n ['Please input both time and space independent variable to ' ...\n '.BC function handle inputs.\\nAssuming given variable is ' ...\n 'time.']);\n outFun = @(t, x, u) conv2cell(inFun, u, x);\n else\n outFun = @(t, x, u) conv2cell(inFun, u, t);\n end\n else\n outFun = @(t, x, u) conv2cell(inFun, u, x);\n end\nelseif ( Nind == 2 )\n outFun = @(t, x, u) conv2cell(inFun, u, t, x);\nelse\n error('CHEBFUN:CHEBFUN:pde15s:inputs_ind', ...\n ['Incorrect number of independent variables in input function. ' ...\n '(Must be 0, 1, or 2).']);\nend\n\nend\n\nfunction newFun = conv2cell(oldFun, u, varargin)\n% This function allows the use of different variables in the anonymous function,\n% rather than using the clunky quasi-matrix notation.\n%\n% Inputs: \n% oldFun in the original function handle\n% u will be the solution we evaluate at\n% varargin possibly contains the time and space variables\n% Output\n% newFun the modified function handle\n\nglobal SYSSIZE\n% Note. This is faster than mat2cell!\ntmpCell = cell(1, SYSSIZE);\nfor qk = 1:SYSSIZE\n tmpCell{qk} = extractColumns(u, qk);\nend\nnewFun = oldFun(varargin{:}, tmpCell{:});\nend\n\nfunction getDIFFORDER(pdeFun, DOMAIN)\n% Extract the DIFFORDER by evaluating the operator at some NaN values.\nglobal DIFFORDER SYSSIZE\n% Find the order of each of the variables:\ntmp = chebdouble(zeros(SYSSIZE), DOMAIN);\nv = pdeFun(0, 0, tmp);\nDIFFORDER = get(v, 'diffOrder');\nDIFFORDER = max(DIFFORDER, 0);\nend\n\nfunction out = dealWithStructInput(in)\n% Parse the inputs for BCs.\n% Throw a warning or an error for a struct. Convert numeric value to 'dirichet'.\nif ( isstruct(in) )\n if ( numel(in) == 1)\n warning('CHEBFUN:CHEBFUN:pde15s:bcstruct', ...\n 'PDE15S no longer supports struct inputs for bc.left and bc.right.')\n if ( isfield(in, 'val') )\n out = {in.op, in.val};\n else\n out = in.op;\n end\n else\n error('CHEBFUN:CHEBFUN:pde15s:bcstruct', ...\n 'PDE15S no longer supports struct inputs for bc.left and bc.right.')\n end\nelseif ( isempty(in) )\n out = [];\nelseif ( isnumeric(in) )\n out = {'dirichlet', in};\nelse\n out = in;\nend\nend\n\nfunction [outFun, varNamesOut] = backCompat(inFun)\n% In V4 PDE15S required the user to pass in dummy function handles for the\n% differential operators. For example, u'' + u' + sum(u) would have needed\n% pdefun = @(u, t, x, diff, sum) diff(u, 2) + diff(u) + sum(u).\n% V5 deals with this in a different way (by using the CHEBDOUBLE class), but we\n% would still like to support the old syntax (at least for now).\n%\n% To do this, we parse the input function for the strings 'diff', 'Diff', and\n% 'D'. If we find any of these, we assume the old syntax is being used, and\n% redefine the function handle appropriately. Of course, this is not fool-proof,\n% but it should work most of the time.\n\nglobal SYSSIZE\n\n% Determine the variable names:\nstr = func2str(inFun);\nparLoc = strfind(str, ')');\nvarList = str(3:parLoc(1)-1);\ncommaLoc = strfind(varList, ',');\nvarNames = cell(1, numel(commaLoc)+1);\nfor k = 1:numel(commaLoc)\n varNames{k} = varList(1:commaLoc(k)-1);\n varList(1:commaLoc(k)) = [];\n commaLoc = commaLoc - commaLoc(k); \nend\nvarNames{numel(commaLoc)+1} = varList;\n\n% Look for 'diff', 'Diff', or 'D':\ndiffLoc = cellfun(@(v) any(strcmp(v, {'diff', 'Diff', 'D'})), varNames);\nidx = find(diffLoc);\nif ( isempty(idx) )\n % None present - new syntax!\n outFun = inFun;\n varNamesOut = varNames;\n return\nend\n\nwarning('CHEBFUN:CHEBFUN:pde15s:oldSyntax', ...\n ['The syntax\\n ' str '\\nis deprecated and may not be supported in ', ...\n 'future releases.\\n Please see the PDE15S documentation for details.'] )\n\n% Switch the order for V5 syntax:\nvarNamesNewOrder = varNames([(1+SYSSIZE):(idx-1), 1:SYSSIZE]);\n\n% Get the new list of variables:\nvarList1 = varNamesNewOrder{1};\nvarList2 = varNames{1};\nfor k = 2:idx-1\n varList1 = [varList1, ',', varNamesNewOrder{k}]; %#ok\n varList2 = [varList2, ',', varNames{k}]; %#ok\nend\n\n% Compile the new function string:\nfunList = {'@diff', '@sum', '@cumsum', '@fred'};\nnewStr = ['@(', varList1, ')' 'inFun(' varList2];\nfor k = 0:(nargin(inFun) - idx)\n newStr = [newStr, ',', funList{k+1}]; %#ok\nend\nnewStr = [newStr, ')'];\n\n% Make the new function handle:\noutFun = eval(newStr);\n\n% Return the obtained variable names\nvarNamesOut = varNamesNewOrder;\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/pdeSolve.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5851011542032313, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.34234336064995335}} {"text": "function [iF, IF_f] = invertFrame(F)\n\n% INVERTFRAME Invert frame.\n% INVERTFRAME(F) gives the frame iF, inverse of F, so that its\n% composition is the origin frame:\n% O = COMPOSEFRAMES(F,iF) ==> O.x = [0 0 0 1 0 0 0]'\n%\n% [iF, IF_f] = INVERTFRAME(F) returns tha Jacobian of the inversion.\n\nif nargout == 1\n \n q = q2qc(F.q);\n t = -Rtp(F.q,F.t);\n iF.x = [t;q];\n iF = updateFrame(iF);\n \nelse\n \n [q, Q_q] = q2qc(F.q);\n [nt, nT_q, nT_t] = Rtp(F.q,F.t); % this should be -Rtp(). n** means negative.\n \n iF.x = [-nt;q];\n iF = updateFrame(iF);\n\n% IF_f = zeros(7);\n IF_f(1:3,1:3) = -nT_t;\n IF_f(1:3,4:7) = -nT_q;\n IF_f(4:7,4:7) = Q_q;\n \nend\n\n\n\n% ========== End of function - Start GPL license ==========\n\n\n% # START GPL LICENSE\n\n%---------------------------------------------------------------------\n%\n% This file is part of SLAMTB, a SLAM toolbox for Matlab.\n%\n% SLAMTB is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% SLAMTB is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with SLAMTB. If not, see .\n%\n%---------------------------------------------------------------------\n\n% SLAMTB is Copyright:\n% Copyright (c) 2008-2010, Joan Sola @ LAAS-CNRS,\n% Copyright (c) 2010-2013, Joan Sola,\n% Copyright (c) 2014-2015, Joan Sola @ IRI-UPC-CSIC,\n% SLAMTB is Copyright 2009 \n% by Joan Sola, Teresa Vidal-Calleja, David Marquez and Jean Marie Codol\n% @ LAAS-CNRS.\n% See on top of this file for its particular copyright.\n\n% # END GPL LICENSE\n\n", "meta": {"author": "joansola", "repo": "slamtb", "sha": "b4767f6bf38bceed205abb85f1aed12422c9a972", "save_path": "github-repos/MATLAB/joansola-slamtb", "path": "github-repos/MATLAB/joansola-slamtb/slamtb-b4767f6bf38bceed205abb85f1aed12422c9a972/FrameTransforms/invertFrame.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6584175139669997, "lm_q2_score": 0.5195213219520929, "lm_q1q2_score": 0.34206193725254624}} {"text": "function [Sbus, dSbus_dVm] = makeSbus(baseMVA, bus, gen, mpopt, Vm, Sg)\n%MAKESBUS Builds the vector of complex bus power injections.\n% SBUS = MAKESBUS(BASEMVA, BUS, GEN)\n% SBUS = MAKESBUS(BASEMVA, BUS, GEN, MPOPT, VM)\n% SBUS = MAKESBUS(BASEMVA, BUS, GEN, MPOPT, VM, SG)\n% returns the vector of complex bus power injections, that is, generation\n% minus load. Power is expressed in per unit. If the MPOPT and VM arguments\n% are present it evaluates any ZIP loads based on the provided voltage\n% magnitude vector. If VM is empty, it assumes nominal voltage. If SG is\n% provided, it is a complex ng x 1 vector of generator power injections in\n% p.u., and overrides the PG and QG columns in GEN, using GEN only for\n% connectivity information.\n%\n% [SBUS, DSBUS_DVM] = MAKESBUS(BASEMVA, BUS, GEN, MPOPT, VM)\n% With two output arguments, it computes the partial derivative of the\n% bus injections with respect to voltage magnitude, leaving the first\n% return value SBUS empty. If VM is empty, it assumes no voltage dependence\n% and returns a sparse zero matrix.\n%\n% See also MAKEYBUS.\n\n% MATPOWER\n% Copyright (c) 1996-2016, Power Systems Engineering Research Center (PSERC)\n% by Ray Zimmerman, PSERC Cornell\n%\n% This file is part of MATPOWER.\n% Covered by the 3-clause BSD License (see LICENSE file for details).\n% See https://matpower.org for more info.\n\n%% define named indices into bus, gen 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[GEN_BUS, PG, QG, QMAX, QMIN, VG, MBASE, GEN_STATUS, PMAX, PMIN, ...\n MU_PMAX, MU_PMIN, MU_QMAX, MU_QMIN, PC1, PC2, QC1MIN, QC1MAX, ...\n QC2MIN, QC2MAX, RAMP_AGC, RAMP_10, RAMP_30, RAMP_Q, APF] = idx_gen;\n\n%% default inputs\nif nargin < 5\n Vm = [];\n if nargin < 4\n mpopt = [];\n end\nend\nnb = size(bus, 1);\n\n%% get load parameters\nSd = makeSdzip(baseMVA, bus, mpopt);\n\nif nargout == 2\n Sbus = [];\n if isempty(Vm)\n dSbus_dVm = sparse(nb, nb);\n else\n dSbus_dVm = -(spdiags(Sd.i + 2 * Vm .* Sd.z, 0, nb, nb));\n end\nelse\n %% compute per-bus generation in p.u.\n on = find(gen(:, GEN_STATUS) > 0); %% which generators are on?\n gbus = gen(on, GEN_BUS); %% what buses are they at?\n ngon = size(on, 1);\n Cg = sparse(gbus, (1:ngon)', 1, nb, ngon); %% connection matrix\n %% element i, j is 1 if\n %% gen on(j) at bus i is ON\n if nargin > 5 && ~isempty(Sg)\n Sbusg = Cg * Sg(on);\n else\n Sbusg = Cg * (gen(on, PG) + 1j * gen(on, QG)) / baseMVA;\n end\n\n %% compute per-bus loads in p.u.\n if isempty(Vm)\n Vm = ones(nb, 1);\n end\n Sbusd = Sd.p + Sd.i .* Vm + Sd.z .* Vm.^2;\n\n %% form net complex bus power injection vector\n %% (power injected by generators + power injected by loads)\n Sbus = Sbusg - Sbusd;\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/makeSbus.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.3420619302881985}} {"text": "classdef VehicleArticulatedLinear < VehicleDynamicsLateral.VehicleArticulated\n % VehicleArticulatedLinear Linear articulated vehicle model.\n %\n % It inherits properties from VehicleArticulated.\n\n methods\n % Constructor\n function self = VehicleArticulatedLinear()\n self.mF0 = 5200;\n self.mR0 = 2400;\n self.mF = 6000;\n self.mR = 10000;\n self.mM = 17000;\n self.IT = 46000;\n self.IS = 450000;\n self.lT = 3.5;\n self.lS = 7.7;\n self.c = -0.3;\n self.nF = 2;\n self.nR = 4;\n self.nM = 8;\n self.wT = 2.6;\n self.wS = 2.4;\n self.muy = 0.3;\n self.deltaf = 0;\n self.Fxf = 0;\n self.Fxr = 0;\n self.Fxm = 0;\n end\n\n function dx = Model(self,t,states,tspan)\n % Vehicle parameters\n mT = self.mT;\n mS = self.mS;\n % IT = self.IT;\n % IS = self.IS;\n a = self.a;\n b = self.b;\n c = self.c;\n d = self.d;\n e = self.e;\n nF = self.nF;\n nR = self.nR;\n nM = self.nM;\n g = 9.81;\n\n\n % Vertical forces\n FzF = self.mF * g;\n FzR = self.mR * g;\n FzM = self.mM * g;\n muy = self.muy;\n\n v0 = 20;\n\n % State\n X = states(1,1);\n Y = states(2,1);\n PSI = states(3,1);\n PHI = states(4,1);\n V = states(5,1);\n ALPHAT = states(6,1);\n dPSI = states(7,1);\n dPHI = states(8,1);\n\n if isa(self.deltaf,'function_handle')\n deltaf = self.deltaf([X;Y;PSI;PHI;V;ALPHAT;dPSI;dPHI],t);\n elseif length(self.deltaf)>1\n deltaf = interp1(tspan,self.deltaf,t);\n else\n deltaf = self.deltaf;\n end\n\n % Slip angles - linear\n ALPHAF = ALPHAT + a/v0*dPSI - deltaf;\n ALPHAR = ALPHAT - b/v0*dPSI;\n ALPHAM = ALPHAT + PHI - (dPSI*(b + c + d + e))/v0 + (dPHI*(d + e))/v0;\n\n % Longitudinal forces\n if isa(self.Fxf,'function_handle')\n FxF = self.Fxf([X;Y;PSI;PHI;V;ALPHAT;dPSI;dPHI],t);\n elseif length(self.Fxf)>1\n FxF = interp1(tspan,self.Fxf,t);\n else\n FxF = self.Fxf;\n end\n\n if isa(self.Fxr,'function_handle')\n FxR = self.Fxr([X;Y;PSI;PHI;V;ALPHAT;dPSI;dPHI],t);\n elseif length(self.Fxr)>1\n FxR = interp1(tspan,self.Fxr,t);\n else\n FxR = self.Fxr;\n end\n\n if isa(self.Fxm,'function_handle')\n FxM = self.Fxm([X;Y;PSI;PHI;V;ALPHAT;dPSI;dPHI],t);\n elseif length(self.Fxm)>1\n FxM = interp1(tspan,self.Fxm,t);\n else\n FxM = self.Fxm;\n end\n\n\n % Lateral forces - Characteristic curve\n FyF = nF*self.tire.Characteristic(ALPHAF,FzF/nF,muy);\n FyR = nR*self.tire.Characteristic(ALPHAR,FzR/nR,muy);\n FyM = nM*self.tire.Characteristic(ALPHAM,FzM/nM,muy);\n\n A = [ 0 0 0 0 1 0 0 0;...\n 0 0 v0 0 0 v0 0 0;...\n 0 0 0 0 0 0 1 0;...\n 0 0 0 0 0 0 0 1;...\n 0 0 0 0 0 0 0 0;...\n 0 0 0 0 0 0 (-v0*(mS + mT)) 0;...\n 0 0 0 0 0 0 (mS*(d*v0 + v0*(b + c))) 0;...\n 0 0 0 0 0 0 (-d*mS*v0) 0];\n\n B = [ 0 0 0 0 0 0 0;...\n 0 0 0 0 0 0 0;...\n 0 0 0 0 0 0 0;...\n 0 0 0 0 0 0 0;...\n 0 1 1 1 0 0 0;...\n 0 0 0 0 1 1 1;...\n 0 0 0 0 a -b (- b - c - d - e);...\n 0 0 0 0 0 0 (d + e)];\n\n vetEst = [X ; Y ; PSI ; PHI ; V ; ALPHAT ; dPSI ; dPHI];\n vetEnt = [deltaf ; FxF ; FxR ; FxM ; FyF ; FyR ; FyM];\n\n % Integrator output\n dx = A*vetEst + B*vetEnt;\n end\n\n function [value,isterminal,direction] = velocity(~,~,states)\n % If the velocity is less than 0.1m/s the integrator stops.\n % The MassMatrix is singular when the velocity is 0 m/s.\n value = states(5,1) - 0.1;\n isterminal = 1;\n direction = -1;\n end\n\n function E = MassMatrix(self,~,~)\n % Vehicle parameters\n mT = self.mT;\n mS = self.mS;\n IT = self.IT;\n IS = self.IS;\n % a = self.a;\n b = self.b;\n c = self.c;\n d = self.d;\n % e = self.e;\n % deltaf = self.deltaf;\n % nF = self.nF;\n % nR = self.nR;\n % nM = self.nM;\n\n % g = 9.81;\n\n v0 = 20;\n\n % Mass matrix\n E = [ 1 0 0 0 0 0 0 0;...\n 0 1 0 0 0 0 0 0;...\n 0 0 1 0 0 0 0 0;...\n 0 0 0 1 0 0 0 0;...\n 0 0 0 0 (mS + mT) 0 0 0;...\n 0 0 0 0 0 (v0*(mS + mT)) (-mS*(b + c + d)) (d*mS);...\n 0 0 0 0 0 ( -mS*v0*(b + c + d)) (IS + IT + mS*(b + c + d)^2) (- IS - mS*(d^2 + (b + c)*d));...\n 0 0 0 0 0 (d*mS*v0) (- IS - mS*(d^2 + (b + c)*d)) (mS*d^2 + IS)];\n\n end\n end\nend\n\n%% See Also\n%\n% <../../index.html Home>\n%\n", "meta": {"author": "andresmendes", "repo": "Vehicle-Dynamics-Lateral", "sha": "a1e9a07da58ef887164bf0046991f0db2ca3b647", "save_path": "github-repos/MATLAB/andresmendes-Vehicle-Dynamics-Lateral", "path": "github-repos/MATLAB/andresmendes-Vehicle-Dynamics-Lateral/Vehicle-Dynamics-Lateral-a1e9a07da58ef887164bf0046991f0db2ca3b647/+VehicleDynamicsLateral/@VehicleArticulatedLinear/VehicleArticulatedLinear.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7057850402140659, "lm_q2_score": 0.4843800842769844, "lm_q1q2_score": 0.34186821726032407}} {"text": "classdef math_model_opf_dc < mp.math_model_opf\n%MP.MATH_MODEL_OPF_DC MATPOWER mathematical model for DC optimal power flow (OPF) problem.\n% ?\n%\n% MP.MATH_MODEL_OPF_DC ... power flow ...\n%\n% Properties\n% ? - ?\n%\n% Methods\n% ?\n\n% MATPOWER\n% Copyright (c) 2021-2022, Power Systems Engineering Research Center (PSERC)\n% by Ray Zimmerman, PSERC Cornell\n%\n% This file is part of MATPOWER.\n% Covered by the 3-clause BSD License (see LICENSE file for details).\n% See https://matpower.org for more info.\n\n% properties\n% end\n\n methods\n %% constructor\n function obj = math_model_opf_dc()\n obj@mp.math_model_opf();\n obj.element_classes = { @mp.mme_bus_opf_dc, @mp.mme_gen_opf_dc, ...\n @mp.mme_load_pf_dc, @mp.mme_branch_opf_dc, @mp.mme_shunt_pf_dc };\n end\n\n function tag = form_tag(obj)\n tag = 'dc';\n end\n\n function name = form_name(obj)\n name = 'DC';\n end\n\n function [vx, z, x] = convert_x_m2n(obj, mmx, nm)\n nm_vars = obj.update_nm_vars(mmx, nm);\n\n %% convert (real) math model x to network model x\n vx = nm_vars.va;\n z = nm_vars.z;\n if nargout < 2\n vx = [vx; z];\n elseif nargout > 2\n x = [vx; z];\n end\n end\n\n function obj = add_node_balance_constraints(obj, nm, dm, mpopt)\n [B, K, p] = nm.get_params();\n\n %% power balance constraints\n C = nm.C;\n Amis = C * [B*C' K*nm.D'];\n bmis = -C * p;\n obj.add_lin_constraint('Pmis', Amis, bmis, bmis, ...\n [nm.va.order; nm.z.order]);\n end\n\n function opt = solve_opts(obj, nm, dm, mpopt)\n opt = mpopt2qpopt(mpopt, obj.problem_type());\n\n switch opt.alg\n case {'MIPS', 'IPOPT'}\n if mpopt.opf.start < 2 %% initialize interior point\n opt.x0 = obj.interior_x0(obj, nm, dm);\n end\n case 'OSQP'\n opt.x0 = []; %% disable provided starting point\n end\n end\n end %% methods\nend %% classdef\n", "meta": {"author": "MATPOWER", "repo": "matpower", "sha": "7da926d978824bf675a71e0a5cb91f8967f97007", "save_path": "github-repos/MATLAB/MATPOWER-matpower", "path": "github-repos/MATLAB/MATPOWER-matpower/matpower-7da926d978824bf675a71e0a5cb91f8967f97007/lib/+mp/math_model_opf_dc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.603931819468636, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.34183660381395375}} {"text": "function varargout = McCabeThieleGUI(varargin)\n% MCCABETHIELEGUI M-file for McCabeThieleGUI.fig\n% MCCABETHIELEGUI, by itself, creates a new MCCABETHIELEGUI or raises the existing\n% singleton*.\n%\n% H = MCCABETHIELEGUI returns the handle to a new MCCABETHIELEGUI or the handle to\n% the existing singleton*.\n%\n% MCCABETHIELEGUI('CALLBACK',hObject,eventData,handles,...) calls the local\n% function named CALLBACK in MCCABETHIELEGUI.M with the given input arguments.\n%\n% MCCABETHIELEGUI('Property','Value',...) creates a new MCCABETHIELEGUI or raises the\n% existing singleton*. Starting from the left, property value pairs are\n% applied to the GUI before McCabeThieleGUI_OpeningFunction gets called. An\n% unrecognized property name or invalid value makes property application\n% stop. All inputs are passed to McCabeThieleGUI_OpeningFcn via varargin.\n%\n% *See GUI Options on GUIDE's Tools menu. Choose \"GUI allows only one\n% instance to run (singleton)\".\n%\n% See also: GUIDE, GUIDATA, GUIHANDLES\n\n% Last Modified by GUIDE v2.5 06-Jul-2010 12:55:42\n\n% Begin initialization code - DO NOT EDIT\ngui_Singleton = 1;\ngui_State = struct('gui_Name', mfilename, ...\n 'gui_Singleton', gui_Singleton, ...\n 'gui_OpeningFcn', @McCabeThieleGUI_OpeningFcn, ...\n 'gui_OutputFcn', @McCabeThieleGUI_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 McCabeThieleGUI is made visible.\nfunction McCabeThieleGUI_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 McCabeThieleGUI (see VARARGIN)\n\nset(handles.mixturepanel_buttongroup,'SelectionChangeFcn',@mixturepanel_buttongroup_SelectionChangeFcn);\n\n% Choose default command line output for McCabeThieleGUI\nhandles.output = hObject;\n\n% Update handles structure\nguidata(hObject, handles);\n\n% UIWAIT makes McCabeThieleGUI 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 = McCabeThieleGUI_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%% Mixture Panel\n\nfunction mixturepanel_buttongroup_SelectionChangeFcn(hObject, eventdata)\n \n\nhandles = guidata(hObject); \n \nswitch get(eventdata.NewValue,'Tag') % Get Tag of selected object\n case 'methanolwater_radiobutton'\n %equilibrium data\n xMW = '[0 0.0200 0.0400 0.0600 0.0800 0.1000 0.1500 0.2000 0.3000 0.4000 0.5000 0.6000 0.7000 0.8000 0.9000 0.9500 1.0000]';\n yMW = '[0 0.1340 0.2300 0.3040 0.3650 0.4180 0.5170 0.5790 0.6650 0.7290 0.7790 0.8250 0.8700 0.9150 0.9580 0.9790 1.0000]';\n set(handles.userdefined_input,'Enable','Off')\n set(handles.userdefined_input2,'Enable','Off')\n set(handles.userdefined_input,'String',xMW)\n set(handles.userdefined_input2,'String',yMW)\n %hold off \n %methanol-water mixture\n %polynomial regression and plot of equilibrium data\n %p = polyfit(xMW,yMW,6);\n %x = 0:.1:100;\n %y = polyval(p,x);\n %plot(xMW,yMW)\n %hold on\n %axis([0 1 0 1])\n %plot(x,y)\n %plot(x,x)\n %xlabel('Liquid Mole Fraction of Methanol')\n %ylabel('Vapor Mole Fraction of Methanol')\n %title('McCabe-Thiele Diagram for Methanol-Water')\n \n case 'ethanolwater_radiobutton'\n %equilibrium data\n xEW = '[0 0.0190 0.0721 0.0966 0.1238 0.1661 0.2337 0.2608 0.3273 0.3965 0.5198 0.5732 0.6763 0.7472 0.8943 1.0000]';\n yEW = '[0 0.1700 0.3891 0.4375 0.4704 0.5089 0.5445 0.5580 0.5826 0.6122 0.6599 0.6841 0.7385 0.7815 0.8943 1.0000]';\n xeq = num2str(xEW);\n yeq = num2str(yEW);\n set(handles.userdefined_input,'Enable','Off')\n set(handles.userdefined_input2,'Enable','Off')\n set(handles.userdefined_input,'String',xeq)\n set(handles.userdefined_input2,'String',yeq)\n %hold off\n %ethanol-water mixture\n %polynomial regression and plot of equilibrium data\n %p = polyfit(xEW,yEW,8);\n %x = 0:.1:100;\n %y = polyval(p,x);\n %plot(x,y)\n %plot(xEW,yEW)\n %hold on\n %axis([0 1 0 1])\n %plot(x,x)\n %xlabel('Liquid Mole Fraction of Ethanol')\n %ylabel('Vapor Mole Fraction of Ethanol')\n %title('McCabe-Thiele Diagram for Ethanol-Water')\n \n case 'acetonethanol_radiobutton'\n %equilibrium data\n xAE = '[0 0.1000 0.1500 0.2000 0.2500 0.3000 0.3500 0.4000 0.5000 0.6000 0.7000 0.8000 0.9000 1.0000]';\n yAE = '[0 0.2620 0.3480 0.4170 0.4780 0.5240 0.5660 0.6050 0.6740 0.7390 0.8020 0.8650 0.9290 1.0000]'; \n set(handles.userdefined_input,'Enable','Off')\n set(handles.userdefined_input2,'Enable','Off')\n set(handles.userdefined_input,'String',xAE)\n set(handles.userdefined_input2,'String',yAE)\n %hold off\n %acetone-ethanol mixture\n %polynomial regression and plot of equilibrium data\n %p = polyfit(xAE,yAE,6);\n %x = 0:.1:100;\n %y = polyval(p,x);\n %plot(xAE,yAE)\n %hold on\n %plot(x,y)\n %plot(x,x)\n %axis([0 1 0 1])\n %xlabel('Liquid Mole Fraction of Acetone')\n %ylabel('Vapor Mole Fraction of Acetone')\n %title('McCabe-Thiele Diagram for Acetone-Ethanol') \n \n case 'userdefined_radiobutton'\n hold off\n %User Defined Input\n choice = menu('Input Equilibrium Data as a Row Vector or as a Relative Volatility (alpha)','Vector','Alpha');\n switch choice\n case 1\n set(handles.userdefined_input,'Enable','On')\n set(handles.userdefined_input2,'Enable','On')\n set(handles.userdefined_input,'String','[Liquid Mole Fractions]')\n set(handles.userdefined_input2,'String','[Vapor Mole Fractions]')\n warndlg('Enlose your vectors with brackets and single quotes', 'Warning');\n %disp('You must enter your own equilibrium data in vector form ')\n %MVC = input('Enter the name of the more volatile component ','s');\n %LVC = input('Enter the name of the less volatile component ','s');\n %xU = input('Enter liquid mole fraction data as a row vector (use brackets) \\n');\n %a = length(xU);\n %fprintf('You have entered %1.0f \"x\" data points, you must enter an equal number of y data points \\n',a)\n %yU = input('Enter vapor phase mole fraction data as a row vector (use brackets) \\n');\n %b = length(yU);\n %if a == b\n %plot(xU,yU,'o')\n %hold on\n %p = polyfit(xU,yU,6);\n %x = 0:.1:100;\n %y = polyval(p,x);\n %plot(x,y)\n %plot(x,x)\n %x_label = sprintf('Liquid Phase Mole Fraction of %s',MVC);\n %y_label = sprintf('Vapor Phase Mole Fraction of %s',MVC);\n %t_itle = sprintf('McCabe-Thiele Diagram for %s-%s',MVC,LVC);\n %xlabel(x_label)\n %ylabel(y_label)\n %title(t_itle) \n %else\n %disp('Equilibrium data does not match, vectors must be equal lengths')\n %end\n case 2 \n set(handles.userdefined_input,'Enable','On')\n set(handles.userdefined_input2,'String','[]')\n set(handles.userdefined_input,'String','') \n end\nend\n%updates the handles structure\nguidata(hObject, handles);\nfunction userdefined_input_Callback(hObject, eventdata, handles)\n% --- Executes during object creation, after setting all properties.\nfunction userdefined_input_CreateFcn(hObject, eventdata, handles)\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\nfunction userdefined_input2_Callback(hObject, eventdata, handles)\n% --- Executes during object creation, after setting all properties.\nfunction userdefined_input2_CreateFcn(hObject, eventdata, handles)\n\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n%% Column Pressure Checkbox\n\n%Column Pressure Input\nfunction pressureinput_Callback(hObject, eventdata, handles)\n% Hints: get(hObject,'String') returns contents of pressureinput as text\n% str2double(get(hObject,'String')) returns contents of pressureinput as a double\n\n% --- Executes during object creation, after setting all properties.\nfunction pressureinput_CreateFcn(hObject, eventdata, handles)\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\nfunction columnpressure_checkbox_Callback(hObject, eventdata, handles)\n\n\n\ncheckbox1_Status = get(handles.columnpressure_checkbox,'Value');\nif checkbox1_Status == 0\n set(handles.pressureinput,'String',' ')\nelse\n set(handles.pressureinput,'Enable','On')\n set(handles.pressureinput,'String','')\nend\n\n\n%% Feed\n%% Feed Flow Rate\n%Feed Flow Rate Input\nfunction feedflowinput_Callback(hObject, eventdata, handles)\n\n% --- Executes during object creation, after setting all properties.\nfunction feedflowinput_CreateFcn(hObject, eventdata, handles)\n\n if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\n end\n\n%Feed Flow Rate Checkbox\nfunction feedflowrate_checkbox_Callback(hObject, eventdata, handles)\n\ncheckbox2_Status = get(handles.feedflowrate_checkbox,'Value');\n\nif checkbox2_Status == 0\n set(handles.feedflowinput,'Enable','Off')\n set(handles.feedflowinput,'String',' ');\nelse \n set(handles.feedflowinput,'Enable','On')\n set(handles.feedflowinput,'String','')\nend\n\n\n%% Feed Composition of the Volatile Component Input\nfunction feedcompvolatile_Callback(hObject, eventdata, handles)\n\n% --- Executes during object creation, after setting all properties.\nfunction feedcompvolatile_CreateFcn(hObject, eventdata, handles)\n\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n%Feed Composition of the Less Volatile Component Input\nfunction feedcomplessvolatile_Callback(hObject, eventdata, handles)\n\n% --- Executes during object creation, after setting all properties.\nfunction feedcomplessvolatile_CreateFcn(hObject, eventdata, handles)\n\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n%Feed Composition Checkbox\nfunction feedcomposition_checkbox_Callback(hObject, eventdata, handles)\n\ncheckbox3_Status = get(handles.feedcomposition_checkbox,'Value');\n\nif checkbox3_Status == 0\n set(handles.feedcompvolatile,'Enable','Off')\n set(handles.feedcomplessvolatile,'Enable','Off')\n set(handles.feedcompvolatile,'String',' ')\n set(handles.feedcomplessvolatile,'String',' ')\nelse\n set(handles.feedcompvolatile,'Enable','On')\n set(handles.feedcomplessvolatile,'Enable','On')\n set(handles.feedcompvolatile,'String','')\n set(handles.feedcomplessvolatile,'String','')\nend\n\n%% Feed Enthalpy \n%Feed Enthalpy Input\nfunction feedenthalpyinput_Callback(hObject, eventdata, handles)\nfunction feedenthalpyinput_CreateFcn(hObject, eventdata, handles)\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n%Feed Enthalpy Checkbox\nfunction feedenthalpy_Callback(hObject, eventdata, handles)\n\ncheckbox4_Status = get(handles.feedenthalpy,'Value');\n\nif checkbox4_Status == 0\n set(handles.feedenthalpyinput,'Enable','Off')\n set(handles.feedenthalpyinput,'String',' ')\nelse\n set(handles.feedenthalpyinput,'Enable','On')\n set(handles.feedenthalpyinput,'String','')\nend\n\n\n\n%Reboiler Duty Input\nfunction reboilerdutyinput_Callback(hObject, eventdata, handles)\n\n% --- Executes during object creation, after setting all properties.\nfunction reboilerdutyinput_CreateFcn(hObject, eventdata, handles)\n\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n% Reboiler Duty Checkbox\nfunction reboilerdutycheckbox_Callback(hObject, eventdata, handles)\n\ncheckbox7_Status = get(handles.reboilerdutycheckbox,'Value');\nif checkbox7_Status == 0\n set(handles.reboilerdutyinput,'Enable','Off')\n set(handles.reboilerdutyinput,'String',' ')\nelse\n set(handles.reboilerdutyinput,'Enable','On')\n set(handles.reboilerdutyinput,'String','')\nend\n\n\n\n\n%% Distillate composition\n\n%Distillate Composition, Volatile Component Input\nfunction distcompvolatile_Callback(hObject, eventdata, handles)\n\n% --- Executes during object creation, after setting all properties.\nfunction distcompvolatile_CreateFcn(hObject, eventdata, handles)\n\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n%Distillate Composition of the less Volatile Component Input\nfunction distcomplessvolatile_Callback(hObject, eventdata, handles)\n\n% --- Executes during object creation, after setting all properties.\nfunction distcomplessvolatile_CreateFcn(hObject, eventdata, handles)\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n%Distillate composition checkbox\nfunction distillatecomposition_checkbox_Callback(hObject, eventdata, handles)\n\ncheckbox9_Status = get(handles.distillatecomposition_checkbox,'Value');\n\nif checkbox9_Status == 0\n set(handles.distcompvolatile,'Enable','Off')\n set(handles.distcomplessvolatile,'Enable','Off')\n set(handles.distcompvolatile,'String',' ')\n set(handles.distcomplessvolatile,'String',' ')\nelse\n set(handles.distcompvolatile,'Enable','On')\n set(handles.distcomplessvolatile,'Enable','On')\n set(handles.distcompvolatile,'String','')\n set(handles.distcomplessvolatile,'String','')\nend\n\n\n%% Reflux Ratio\n%Reflux Ratio Input\nfunction refluxratio_input_Callback(hObject, eventdata, handles)\n\n% --- Executes during object creation, after setting all properties.\nfunction refluxratio_input_CreateFcn(hObject, eventdata, handles)\n\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\nfunction minimumrefluxinput_Callback(hObject, eventdata, handles)\n\n% --- Executes during object creation, after setting all properties.\nfunction minimumrefluxinput_CreateFcn(hObject, eventdata, handles)\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n%Reflux Ratio Checkbox\nfunction refluxratio_checkbox_Callback(hObject, eventdata, handles)\n\ncheckbox11_Status = get(handles.refluxratio_checkbox,'Value');\n\nif checkbox11_Status == 0 \n set(handles.refluxratio_input,'Enable','Off')\n set(handles.refluxratio_input,'String',' ')\n set(handles.minimumrefluxinput,'Enable','Off')\n set(handles.minimumrefluxinput,'String',' ')\nelseif checkbox11_Status == 1\n choice = menu('Are you specifying minimum reflux or actual reflux','Actual','Minumum');\n switch choice\n case 1\n set(handles.refluxratio_input,'Enable','On')\n set(handles.refluxratio_input,'String','')\n set(handles.minimumrefluxinput,'Enable','Off')\n set(handles.minimumrefluxinput,'String',' ')\n case 2\n Rmin = str2double(get(handles.minimumrefluxinput,'String'));\n if isnan(Rmin) == 1\n set(handles.refluxratio_input,'Enable','On')\n set(handles.refluxratio_input,'String','')\n set(handles.minimumrefluxinput,'Enable','On')\n set(handles.minimumrefluxinput,'String','')\n elseif isnan(Rmin) == 0\n set(handles.refluxratio_input,'Enable','On')\n set(handles.refluxratio_input,'String','')\n set(handles.minimumrefluxinput,'Enable','Off')\n end\n end\n\nend\n\n%% Bottoms Composition\n%Bottoms Composition of the Less Volatile Component Input\nfunction botcomplessvolatile_Callback(hObject, eventdata, handles)\n\n% --- Executes during object creation, after setting all properties.\nfunction botcomplessvolatile_CreateFcn(hObject, eventdata, handles)\n\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n%Bottoms Composition of the Volatile Component Input\nfunction botcompvolatile_Callback(hObject, eventdata, handles)\n\n% --- Executes during object creation, after setting all properties.\nfunction botcompvolatile_CreateFcn(hObject, eventdata, handles)\n\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n%Bottoms Composition Checkbox\nfunction bottomscomposition_checkbox_Callback(hObject, eventdata, handles)\n\ncheckbox10_Status = get(handles.bottomscomposition_checkbox,'Value');\n\nif checkbox10_Status == 0 \n set(handles.botcomplessvolatile,'Enable','Off')\n set(handles.botcompvolatile,'Enable','Off')\n set(handles.botcomplessvolatile,'String',' ')\n set(handles.botcompvolatile,'String',' ')\nelseif checkbox10_Status == 1\n set(handles.botcomplessvolatile,'Enable','On')\n set(handles.botcompvolatile,'Enable','On')\n set(handles.botcompvolatile,'String','')\n set(handles.botcomplessvolatile,'String','')\nend\n\n%% Optimum Feed Plate \n%Optimum Feed Plate Checkbox\nfunction optimumfeedplate_Callback(hObject, eventdata, handles)\n\n%% Distillate Flow Rate\n%Distillate Flow Rate Input\nfunction distillateflowrateinput_Callback(hObject, eventdata, handles)\n\n% --- Executes during object creation, after setting all properties.\nfunction distillateflowrateinput_CreateFcn(hObject, eventdata, handles)\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n%Distillate Flow Rate Checkbox\nfunction distillateflowrate_checkbox_Callback(hObject, eventdata, handles)\ncheckbox14_Status = get(handles.distillateflowrate_checkbox,'Value');\n\nif checkbox14_Status == 0\n set(handles.distillateflowrateinput,'Enable','Off')\n set(handles.distillateflowrateinput,'String',' ')\nelse\n set(handles.distillateflowrateinput,'Enable','On')\n set(handles.distillateflowrateinput,'String','')\nend\n\n%% Fractional Recoveries\n\n%Fractional Recovery of the Volatile Component in the Distillate Input\nfunction fracrecoveryvolatile_Callback(hObject, eventdata, handles)\n\n% --- Executes during object creation, after setting all properties.\nfunction fracrecoveryvolatile_CreateFcn(hObject, eventdata, handles)\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n%Fractional Recovery of the Less Volatile Component in the Bottoms Input\nfunction fracrecoverylessvolatile_Callback(hObject, eventdata, handles)\n\n% --- Executes during object creation, after setting all properties.\nfunction fracrecoverylessvolatile_CreateFcn(hObject, eventdata, handles)\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n%Fractional Recoveries Checkbox\nfunction fractionalrecoveries_checkbox_Callback(hObject, eventdata, handles)\n\ncheckbox12_Status = get(handles.fractionalrecoveries_checkbox,'Value');\n\nif checkbox12_Status == 0 \n set(handles.fracrecoveryvolatile,'Enable','Off')\n set(handles.fracrecoverylessvolatile,'Enable','Off')\n set(handles.fracrecoveryvolatile,'String','0')\n set(handles.fracrecoverylessvolatile,'String','0')\nelse\n set(handles.fracrecoveryvolatile,'Enable','On')\n set(handles.fracrecoverylessvolatile,'Enable','On')\n set(handles.fracrecoveryvolatile,'String','')\n set(handles.fracrecoverylessvolatile,'String','')\nend\n\n%% Bottoms Flow Rate \nfunction bottomsflowrateinput_Callback(hObject, eventdata, handles)\n\n% --- Executes during object creation, after setting all properties.\nfunction bottomsflowrateinput_CreateFcn(hObject, eventdata, handles)\n\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n%Bottoms Flow Rate Checkbox\nfunction bottomsflowrate_checkbox_Callback(hObject, eventdata, handles)\ncheckbox15_Status = get(handles.bottomsflowrate_checkbox,'Value');\nif checkbox15_Status == 0\n set(handles.bottomsflowrateinput,'Enable','Off')\n set(handles.bottomsflowrateinput,'String',' ')\nelse\n set(handles.bottomsflowrateinput,'Enable','On')\n set(handles.bottomsflowrateinput,'String','')\nend\n\n\n%% Boilup Ratio Checkbox\n\n%Boilup Ratio Input\nfunction boilupratioinput_Callback(hObject, eventdata, handles)\n\nfunction boilupratioinput_CreateFcn(hObject, eventdata, handles)\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\nfunction boilupratio_checkbox_Callback(hObject, eventdata, handles)\n\ncheckbox15_Status = get(handles.boilupratio_checkbox,'Value');\n\nif checkbox15_Status == 0 \n set(handles.boilupratioinput,'Enable','Off')\n set(handles.boilupratioinput,'String',' ')\nelseif checkbox15_Status == 1\n set(handles.boilupratioinput,'Enable','On')\n set(handles.boilupratioinput,'String','')\nelseif checkbox15_Status == 0 && checkbox11_Status == 1 && checkbox6_Status == 1 && checkbox9_Status == 1\n set(handles.boilupratioinput,'Enable','Off')\n set(handles.boilupratioinput,'String',' ')\n xi = (-(Q-1)*(1-R/(R+1))*xd-zf)/((Q-1)*R/(R+1)-Q);\n yi = (zf+xd*Q/R)/(1+Q/R);\n xs = linspace(xb,xi);\n ys = linspace(xb,yi);\n plot(xs,ys)\n hold on\nend\n\n\n%% Feed Quality\n\n%Feed Quality Input\nfunction feedqualityinput_Callback(hObject, eventdata, handles)\n\n% --- Executes during object creation, after setting all properties.\nfunction feedqualityinput_CreateFcn(hObject, eventdata, handles)\n\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n%Feed Quality Checkbox\nfunction feedquality_checkbox_Callback(hObject, eventdata, handles)\n\ncheckbox6_Status = get(handles.feedquality_checkbox,'Value');\n\nif checkbox6_Status == 0 \n set(handles.feedqualityinput,'Enable','Off')\n set(handles.feedqualityinput,'String',' ')\nelse\n set(handles.feedqualityinput,'Enable','On')\n set(handles.feedqualityinput,'String','')\nend\n\n\n%Condenser Duty Input\nfunction condenserdutyinput_Callback(hObject, eventdata, handles)\nfunction condenserdutyinput_CreateFcn(hObject, eventdata, handles)\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n%Condenser Duty Checkbox\nfunction condenserdutycheckbox_Callback(hObject, eventdata, handles)\n\n% --- Executes during object creation, after setting all properties.\nfunction condenserdutycheckbox_CreateFcn(hObject, eventdata, handles)\n\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\ncheckbox5_Status = get(handles.condenserdutycheckbox,'Value');\nif checkbox5_Status == 0 \n set(handles.condenserdutyinput,'Enable','Off')\n set(handles.condenserdutyinput,'String',' ')\nelse\n set(handles.condenserdutyinput,'Enable','On')\n set(handles.condenserdutyinput,'String','')\nend\n\n\n%Reflux Enthalpy Input\nfunction refluxenthalpyinput_Callback(hObject, eventdata, handles)\n% --- Executes during object creation, after setting all properties.\nfunction refluxenthalpyinput_CreateFcn(hObject, eventdata, handles)\n\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n%Reflux Enthalpy Checkbox\nfunction refluxenthalpy_Callback(hObject, eventdata, handles)\n\ncheckbox8_Status = get(handles.refluxenthalpy,'Value');\nif checkbox8_Status == 0\n set(handles.refluxenthalpyinput,'Enable','Off')\n set(handles.refluxenthalpyinput,'String',' ')\nelse\n set(handles.refluxenthalpyinput,'Enable','On')\n set(handles.refluxenthalpyinput,'String','')\nend\n\n%Boilup Enthalpy Input\nfunction boilupenthalpyinput_Callback(hObject, eventdata, handles)\n\n% --- Executes during object creation, after setting all properties.\nfunction boilupenthalpyinput_CreateFcn(hObject, eventdata, handles)\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n%Boilup Enthalpy Checkbox\nfunction boilupenthalpycheckbox_Callback(hObject, eventdata, handles)\ncheckbox20_Status = get(handles.boilupenthalpycheckbox,'Value');\nif checkbox20_Status == 0\n set(handles.boilupenthalpyinput,'Enable','Off')\n set(handles.boilupenthalpyinput,'String',' ')\nelse\n set(handles.boilupenthalpyinput,'Enable','On')\n set(handles.boilupenthalpyinput,'String','')\nend\n\n%Distillate Enthalpy \nfunction distillateenthalpyinput_Callback(hObject, eventdata, handles)\n\n\n% --- Executes during object creation, after setting all properties.\nfunction distillateenthalpyinput_CreateFcn(hObject, eventdata, handles)\n\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n% --- Executes on button press in distillateenthalpycheckbox.\nfunction distillateenthalpycheckbox_Callback(hObject, eventdata, handles)\ncheckbox21_Status = get(handles.distillateenthalpycheckbox,'Value');\nif checkbox21_Status == 0\n set(handles.distillateenthalpyinput,'Enable','Off')\n set(handles.distillateenthalpyinput,'String',' ')\nelse\n set(handles.distillateenthalpyinput,'Enable','On')\n set(handles.distillateenthalpyinput,'String','')\nend\n\n%Bottoms enthalpy\nfunction bottomsenthalpyinput_Callback(hObject, eventdata, handles)\n\n% --- Executes during object creation, after setting all properties.\nfunction bottomsenthalpyinput_CreateFcn(hObject, eventdata, handles)\n\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n% --- Executes on button press in bottomsenthalpycheckbox.\nfunction bottomsenthalpycheckbox_Callback(hObject, eventdata, handles)\ncheckbox22_Status = get(handles.bottomsenthalpycheckbox,'Value');\nif checkbox22_Status == 0\n set(handles.bottomsenthalpyinput,'Enable','Off')\n set(handles.bottomsenthalpyinput,'String',' ')\nelse\n set(handles.bottomsenthalpyinput,'Enable','On')\n set(handles.bottomsenthalpyinput,'String','')\nend\n\n\n% --- Executes on button press in startbutton.\nfunction startbutton_Callback(hObject, eventdata, handles)\n\n% Get Values\n\nAlpha = str2double(get(handles.userdefined_input,'String'));\n\nP = str2double(get(handles.pressureinput,'String'));\nF = str2double(get(handles.feedflowinput,'String'));\nzf = str2double(get(handles.feedcompvolatile,'String'));\nzfnv = str2double(get(handles.feedcomplessvolatile,'String'));\nxd = str2double(get(handles.distcompvolatile,'String'));\nxdnv = str2double(get(handles.distcomplessvolatile,'String'));\nxb = str2double(get(handles.botcompvolatile,'String'));\nxbnv = str2double(get(handles.botcomplessvolatile,'String'));\nD = str2double(get(handles.distillateflowrateinput,'String'));\nfv = str2double(get(handles.fracrecoveryvolatile,'String'));\nfnv = str2double(get(handles.fracrecoverylessvolatile,'String'));\nB = str2double(get(handles.bottomsflowrateinput,'String'));\nS = str2double(get(handles.boilupratioinput,'String'));\nQ = str2double(get(handles.feedqualityinput,'String'));\nR = str2double(get(handles.refluxratio_input,'String'));\nRmin = str2double(get(handles.minimumrefluxinput,'String'));\nhf = str2double(get(handles.feedenthalpyinput,'String'));\nhD = str2double(get(handles.refluxenthalpyinput,'String'));\nhB = str2double(get(handles.boilupenthalpyinput,'String'));\nQc = str2double(get(handles.condenserdutyinput,'String'));\nQr = str2double(get(handles.reboilerdutyinput,'String'));\nHD = str2double(get(handles.distillateenthalpyinput,'String'));\nHB = str2double(get(handles.bottomsenthalpyinput,'String'));\n\n%xie = 1/2*(-Q+zf*Alpha+Q*Alpha-zf-Alpha+(2*Q*Alpha^2*zf+Q^2-2*Q*zf+2*zf*Alpha-2*zf^2*Alpha+zf^2*Alpha^2-2*zf*Alpha^2+zf^2+2*Q*Alpha-2*Q^2*Alpha+Alpha^2+Q^2*Alpha^2-2*Q*Alpha^2)^(1/2))/Q/(-1+Alpha);\n%yie = xie*Alpha/(1-xie+xie*Alpha);\nxi = (-(Q-1)*(1-R/(R+1))*xd-zf)/((Q-1)*R/(R+1)-Q);\nyi = (zf+xd*Q/R)/(1+Q/R);\n\n%Error Tests\n\n%Feed Quality & Feed Line\ncheckbox6_Status = get(handles.feedquality_checkbox,'Value');\nif checkbox6_Status == 0 \n errordlg('Feed quality must be specified')\n return\nelseif checkbox6_Status == 1 && isnan(Q) == 1\n errordlg('Feed quality must be specified')\n return\nelseif checkbox6_Status == 1 && isnan(Q) == 0\n ye = 0:.001:1;\n if Q > -inf && Q <1\n xf = 0:.001:1;\n elseif Q > 1\n xf = zf:.001:1;\n end \n if Q ~= 1\n yf = yfeed(xf,Q,zf);\n elseif Q == 1\n yf = 0:.001:1;\n xf = zf*ones(length(yf));\n end \nend\n\n%Equilibrium Data\nif any(isnan(Alpha)) == 1\n xeq = str2num(get(handles.userdefined_input,'String'));\n yeq = str2num(get(handles.userdefined_input2,'String'));\n %Error Test on Equilibrium Vector Length\n if length(yeq) ~= length(xeq) && isempty(yeq) == 1 && length(xeq) > 1\n errordlg('Equilibrium data does not match')\n return\n elseif length(yeq) == length(xeq) && length(xeq) < 10\n errordlg('Too few data points will give a poor equilibrium curve')\n else\n k = 1; %k is a constant, metric for stepping off equilibrium stages\n end\nelseif isnan(Alpha) == 0 && length(Alpha) == 1\n yeq = [];\n if Alpha <= 1\n errordlg('Relative volatility must be greater than 1')\n return\n elseif Alpha > 1\n k = 2;\n end\nend\nif k == 1\n xx = 0:.001:1;\n yy = spline(xeq,yeq,xx);\n if Q == 0\n xx = .001:.001:1.001;\n yy = spline(xeq,yeq,xx);\n diffe = abs(yy-zf);\n [a b] = min(diffe) ; \n xie = xx(b);\n yie = zf;\n elseif Q == 1\n yie = spline(xeq,yeq,zf);\n xie = zf;\n elseif Q~=0 && Q~=1 \n diffe = abs(yy-yf);\n [a b] = min(diffe);\n xie = xx(b);\n yie = yy(b);\n end\nelseif k == 2 \n xie = 1/2*(-Q+zf*Alpha+Q*Alpha-zf-Alpha+(2*Q*Alpha^2*zf+Q^2-2*Q*zf+2*zf*Alpha-2*zf^2*Alpha+zf^2*Alpha^2-2*zf*Alpha^2+zf^2+2*Q*Alpha-2*Q^2*Alpha+Alpha^2+Q^2*Alpha^2-2*Q*Alpha^2)^(1/2))/Q/(-1+Alpha);\n yie = xie*Alpha/(1-xie+xie*Alpha);\nend\n\n%Overall Mass Balance\ncheckbox2_Status = get(handles.feedflowrate_checkbox,'Value');\ncheckbox17_Status = get(handles.distillateflowrate_checkbox,'Value');\ncheckbox18_Status = get(handles.bottomsflowrate_checkbox,'Value');\nl = [checkbox2_Status checkbox17_Status checkbox18_Status]; %l is a status vector for mass flow streams\nif any([F D B]< 0) \n errordlg('Mass flow rates must be greater than zero')\n return\nelseif sum(l) == 3 && D + B ~= F\n errordlg('The mass balance is incorrect')\n return \nelseif sum(l) == 2\n if isnan(F) == 0 \n if isnan(B) == 0\n D = F - B;\n Ds = num2str(D);\n set(handles.distillateflowrateinput,'String',Ds)\n elseif isnan(D) == 0\n B = F - D;\n Bs = num2str(B);\n set(handles.bottomsflowrateinput,'String',Bs)\n end\n elseif isnan(F) == 1\n F = B + D;\n Fs = num2str(F);\n set(handles.feedflowinput,'String',Fs)\n end\nend\n\n%Feed Composition\ncheckbox3_Status = get(handles.feedcomposition_checkbox,'Value');\nif checkbox3_Status == 1\n if isnan(zf) == 1 && isnan(zfnv) == 1\n errordlg('Feed composition must be a real number')\n return\n elseif isnan(zf) == 0 && isnan(zfnv) == 1\n zfnv = 1 - zf;\n zfnv = num2str(zfnv);\n set(handles.feedcomplessvolatile,'String',zfnv)\n elseif isnan(zf) == 1 && isnan(zfnv) == 0\n zf = 1 - zfnv;\n zf = num2str(zf);\n set(handles.feedcompvolatile,'String',zf)\n elseif isnan(zf) == 0 && isnan(zfnv) == 0 \n if zf + zfnv ~= 1\n errordlg('Mole fractions must add up to 1')\n return \n elseif zf < 0 || zf > 1 || zfnv < 0 || zfnv > 1\n errordlg('Mole fractions must be between 0 and 1')\n return\n end\n end\nend\n\n%Distillate Composition\ncheckbox9_Status = get(handles.distillatecomposition_checkbox,'Value');\nif checkbox9_Status == 1 \n if isnan(xd) && isnan(xdnv)\n errordlg('Distillate composition must be a real number')\n return\n elseif isnan(xd) == 0 && isnan(xdnv) == 1\n xdnv = 1 - xd;\n xdnvs = num2str(xdnv);\n set(handles.distcomplessvolatile,'String',xdnvs)\n elseif isnan(xd) == 1 && isnan(xdnv) == 0\n xd = 1 - xdnv;\n xds = num2str(xd);\n set(handles.distcompvolatile,'String',xds)\n elseif isnan(xd) == 0 && isnan(xdnv) == 0 \n if xd + xdnv ~= 1\n errordlg('Mole fractions must add up to 1')\n return \n elseif xd < 0 || xd > 1 || xdnv < 0 || xdnv > 1\n errordlg('Mole fractions must be between 0 and 1')\n return\n end\n end \nend\n\n%Bottoms Composition\ncheckbox10_Status = get(handles.bottomscomposition_checkbox,'Value');\nif checkbox10_Status == 1 \n if isnan(xb) == 1 && isnan(xbnv) == 1\n errordlg('Bottoms composition must be a real number')\n return\n elseif isnan(xb) == 0 && isnan(xbnv) == 1\n xbnv = 1 - xb;\n xbnvs = num2str(xbnv);\n set(handles.botcomplessvolatile,'String',xbnvs)\n elseif isnan(xb) == 1 && isnan(xbnv) == 0\n xb = 1 - xbnv;\n xbs = num2str(xb);\n set(handles.botcompvolatile,'String',xbs)\n elseif isnan(xb) == 0 && isnan(xbnv) == 0 \n if xb + xbnv ~= 1\n errordlg('Mole fractions must add up to 1')\n return\n elseif xb < 0 || xb > 1 || xbnv < 0 || xbnv > 1\n errordlg('Mole fractions must be between 0 and 1')\n return\n end\n end\nend\n\n\n%Test to see if the mass balance has converged\n%lk is a status vector for feed stream compositions\nlk = [checkbox3_Status checkbox9_Status checkbox10_Status];\nif sum(lk) == 3\n if sum(l) == 1\n if isnan(F) == 0\n if isnan(D) == 1 && isnan(B) == 1\n D = F*(zf-xb)/(xd-xb);\n Ds = num2str(D);\n set(handles.distillateflowrateinput,'String',Ds)\n B = F - D;\n Bs = num2str(B);\n set(handles.bottomsflowrateinput,'String',Bs)\n fv = D*xd/F/zf;\n fvs = num2str(fv);\n set(handles.fracrecoveryvolatile,'String',fvs)\n fnv = B*(1-xb)/F/(1-zf);\n fnvs = num2str(fnv);\n set(handles.fracrecoverylessvolatile,'String',fnvs)\n end\n end\n elseif sum(l) == 2\n if isnan(F) == 0\n if isnan(D) == 0\n Dk = F*(zf-xb)/(xd-xb);\n Bk = F - Dk;\n if D ~= Dk\n Ds = num2str(Dk);\n set(handles.distillateflowrateinput,'String',Ds)\n Bk = F-Dk;\n Bs = num2str(Bk);\n set(handles.bottomsflowrateinput,'String',Bs)\n fv = D*xd/F/zf;\n fvs = num2str(fv);\n set(handles.fracrecoveryvolatile,'String',fvs)\n fnv = B*(1-xb)/F/(1-zf);\n fnvs = num2str(fnv);\n set(handles.fracrecoverylessvolatile,'String',fnvs)\n end\n if B ~= Bk\n Bs = num2str(Bk);\n set(handles.bottomsflowrateinput,'String',Bs)\n Dk = F-Bk;\n Ds = num2str(Dk);\n set(handles.distillateflowrateinput,'String',Ds)\n fv = D*xd/F/zf;\n fvs = num2str(fv);\n set(handles.fracrecoveryvolatile,'String',fvs)\n fnv = B*(1-xb)/F/(1-zf);\n fnvs = num2str(fnv);\n set(handles.fracrecoverylessvolatile,'String',fnvs)\n end\n end\n end\n end\nelseif sum(lk) == 1 && isnan(zf) == 0\ncheckbox12_Status = get(handles.fractionalrecoveries_checkbox,'Value');\n if sum(l) == 2 || sum(l) == 3\n %Fractional Recoveries\n if checkbox12_Status == 1\n if any(isnan([fv fnv])) == 1\n errordlg('Fractional recovery must be a real number')\n return\n elseif any([fv fnv]>=1) || any([fv fnv]<0)\n errordlg('Fractional recovery must be between 0 and 1')\n return\n elseif any([fv fnv]==1)\n errordlg('100 percent recovery is physically impossible, try a different value')\n return\n else\n xd = fv/D*F*zf; \n xds = num2str(xd);\n set(handles.distcompvolatile,'String',xds)\n xb = 1-fnv/(F-D)*F*(1-zf);\n xbs = num2str(xb);\n set(handles.botcompvolatile,'String',xbs)\n end\n end\n elseif checkbox12_Status == 0\n errordlg('The system is underspecified')\n return\n end\nend\n\n%Fractional Recoveries\ncheckbox12_Status = get(handles.fractionalrecoveries_checkbox,'Value');\nif checkbox12_Status == 0\n if all(isnan([F D B zf xd xb])) == 0\n fv = D*xd/F/zf;\n fvs = num2str(fv);\n set(handles.fracrecoveryvolatile,'String',fvs)\n fnv = B*(1-xb)/F/(1-zf);\n fnvs = num2str(fnv);\n set(handles.fracrecoverylessvolatile,'String',fnvs)\n end\nend\n\n\n\n%Feed Enthalpy\ncheckbox4_Status = get(handles.feedenthalpy,'Value');\nif checkbox4_Status == 1 && isnan(hf) == 1\n errordlg('Feed enthalpy must be a real number')\n return\nend\n\n%Condenser Duty\ncheckbox5_Status = get(handles.condenserdutycheckbox,'Value');\nif checkbox5_Status == 1 && isnan(Qc) == 1\n errordlg('Condenser duty must be a real number')\n return\nend\n\n\n\n%Reboiler Duty\ncheckbox7_Status = get(handles.reboilerdutycheckbox,'Value');\nif checkbox7_Status == 1 && isnan(Qr) == 1\n errordlg('Reboiler duty must be a real number')\n return\nend\n\n%Reflux Enthalpy\ncheckbox8_Status = get(handles.refluxenthalpy,'Value');\nif checkbox8_Status == 1 && isnan(hD) == 1\n errordlg('Reflux enthalpy must be a real number')\n return\nend\n\n%Reflux Ratio\ncheckbox11_Status = get(handles.refluxratio_checkbox,'Value');\nif checkbox11_Status == 1 \n if isnan(R) == 1 && isnan(Rmin) == 1\n errordlg('Reflux ratio must be a real number')\n return\n elseif R < 0\n errordlg('Reflux ratio must be greater than 0')\n return\n elseif Rmin < 0\n errordlg('Minumum reflux must be greater than 0')\n return\n elseif isnan(Rmin) == 0 && isnan(R) == 1\n errordlg('You must specify an operating factor')\n return\n end\nelseif checkbox11_Status == 0\n if isnan(xd) == 1 && isnan(Q) == 1\n errordlg('You must specify feed quality and distillate composition')\n return\n elseif isnan(xd) == 0 && isnan(Q) == 1\n errordlg('You must specify feed quality')\n return\n elseif isnan(xd) == 1 && isnan(Q) == 0\n errordlg('You must specify distillate composition')\n return\n elseif isnan(Rmin) == 1 && isnan(Q) == 0 && isnan(xd) == 0 \n if isnan(Alpha) == 0\n if isnan(R) == 1\n Emin = (xd-yie)/(xd-xie);\n Rmin = Emin/(1-Emin);\n Rmins = num2str(Rmin);\n set(handles.minimumrefluxinput,'String',Rmins)\n errordlg('Minimum reflux has been calculated and returned but you must specify an operating factor')\n return\n elseif isnan(R) == 0\n Emin = (xd-yie)/(xd-xie);\n Rmin = Emin/(1-Emin);\n Rmins = num2str(Rmin);\n R = R*Rmin;\n Rs = num2str(R);\n set(handles.minimumrefluxinput,'String',Rmins)\n set(handles.refluxratio_input,'String',Rs)\n elseif isnan(Rmin) == 0 && isnan(R) == 1\n errordlg('You must specify an operating factor')\n return\n end\n elseif isnan(Alpha) == 1 && k ==1\n if isnan(R) == 1\n Emin = (xd-yie)/(xd-xie);\n Rmin = Emin/(1-Emin);\n Rmins = num2str(Rmin);\n set(handles.minimumrefluxinput,'String',Rmins)\n errordlg('Minimum reflux has been calculated and returned but you must specify an operating factor')\n return\n elseif isnan(R) == 0\n Emin = (xd-yie)/(xd-xie);\n Rmin = Emin/(1-Emin);\n Rmins = num2str(Rmin);\n R = R*Rmin;\n Rs = num2str(R);\n set(handles.minimumrefluxinput,'String',Rmins)\n set(handles.refluxratio_input,'String',Rs)\n elseif isnan(Rmin) == 0 && isnan(R) == 1\n errordlg('You must specify an operating factor')\n return\n end\n end\n end\nend\n\n%Optimum Feed Plate\ncheckbox12_Status = get(handles.optimumfeedplate,'Value');\nif checkbox12_Status == 0\n errordlg('This version does not support non-optimum feed plate')\n return\nend\n\n%Boilup Ratio\nif S < 0\n errordlg('Boilup ratio must be greater than 0')\n return\nend\n\n%Boilup Enthalpy\ncheckbox20_Status = get(handles.boilupenthalpycheckbox,'Value');\nif checkbox20_Status == 1 && isnan(hB) == 1\n errordlg('Boilup enthalpy must be a real number')\n return\nend\n\n%Pressure\nif P < 0\n errordlg('Pressure must be greater than 0')\nend \n\n%Energy Balance\n%checkbox4_Status = get(handles.feedenthalpy,'Value');\n%checkbox5_Status = get(handles.condenserdutycheckbox,'Value');\n%checkbox7_Status = get(handles.reboilerdutycheckbox,'Value');\n%checkbox8_Status = get(handles.refluxenthalpy,'Value');\n%checkbox20_Status = get(handles.boilupenthalpycheckbox,'Value');\n%checkbox21_Status = get(handles.distillateenthalpycheckbox,'Value');\n%checkbox22_Status = get(handles.bottomsenthalpycheckbox,'Value');\n%jkl = [checkbox4_Status checkbox5_Status checkbox7_Status checkbox8_Status checkbox20_Status checkbox21_Status checkbox22_Status]; %Status vector\n%Condenser Energy Balance\nif isnan(Qc) == 0 \n if isnan(hD) == 1\n hD = Qc/D/(R+1)*3600;\n hDs = num2str(hD);\n set(handles.refluxenthalpyinput,'String',hDs)\n end\nelseif isnan(hD) == 0\n if isnan(Qc) == 1\n Qc = hB*D*(R+1)/3600;\n Qcs = num2str(Qc);\n set(handles.condenserdutyinput,'String',Qcs)\n end\nend\n%Reboiler Energy Balance\nif isnan(Qr) == 0 \n if isnan(hB) == 1\n hB = Qr/B/S*3600;\n hBs = num2str(hB);\n set(handles.boilupenthalpyinput,'String',hBs)\n end\nelseif isnan(hB) == 0\n if isnan(Qr) == 1\n Qr = B*S*hB/3600;\n Qrs = num2str(Qr);\n set(handles.reboilerdutyinput,'String',Qrs)\n end\nend\n%jklm = [isnan(F) isnan(hf) isnan(Qc) isnan(Qr) isnan(B) isnan(HB) isnan(D) isnan(HD)];\n%if sum(jklm) == 0 \n% if F*hf + Qc + Qr - B*HB - D*HD >= 100 \n% errordlg('The energy balance is not correct')\n% return\n% end\n%end\n\n%Equilibrium Curves\nif k ==1 %Vector\n xx = 0:.001:1;\n yy = spline(xeq,yeq,xx);\n hold off\n plot(xx,yy)\n axis([0 1 0 1])\n hold on\n plot(xx,xx)\nelseif k == 2 %Alpha\n ye = 0:.001:1;\n xe = equilib(ye,Alpha);\n hold off\n plot(xe,ye)\n axis([0 1 0 1])\n hold on\n plot(ye,ye) \nend\n\n%Plotting the Operating Lines\nytopop = ytop(ye,R,xd);\nybotop = ybot(ye,S,xb);\nplot(xf,yf);\nplot(ye,ytopop)\nplot(ye,ybotop)\nplot(ye,ye)\nplot(xb,xb,'o')\ntext(xb+.025,xb-.025,'x_B')\nplot(xd,xd,'o')\ntext(xd+.025,xd-.025,'x_D')\nplot(zf,zf,'o')\n\n% Computing the intersection of feed line and operating lines\nplot(xi,yi,'o')\ntext(xi-.1,yi+.025,'Feed Line')\ntext(xb-.025,xb+.05,'Stripping Line')\ntext(xd-.25,xd-.05,'Enriching Line')\nxlabel('Liquid Phase Mole Fraction, x')\nylabel('Vapor Phase Mole Fraction, y')\ntitle('McCabe-Thiele Diagram for Binary Column Distillation')\nif k == 2\n yi2 = interp1 (xe,ye,xi);\n if yi > yi2\n errordlg ('The distillation is not possible. Try a different operating condition.')\n return\n end\nelseif k == 1\n yi2 = interp1(xx,yy,xi);\n if yi > yi2\n errordlg('The distillation is not possible. Try a different operating condition.')\n return\n end\nend\n\n% Rectifying section\nif k == 2 %user defined systems\n i = 1;\n xp(1) = xd;\n yp(1) = xd;\n y = xd;\n while xp (i) > xi\n xp(i+1)= equilib(y,Alpha);\n yp(i+1)= R/(R+1)*xp (i+1)+xd/(R+1);\n y = yp (i+1);\n a = linspace(xp(i),xp(i+1));\n b = yp(i)*ones(length(a));\n plot(a,b)\n text ((xp(i+1)-.025),(yp(i)+.025),num2str (i))\n if xp (i+1) > xi\n c = linspace(yp(i),yp(i+1));\n d = xp(i+1)*ones(length(c));\n plot(d,c)\n end\n i = i+1;\n end\n % Stripping section\n xs = linspace(xb,xi);\n ys = linspace(xb,yi);\n plot(xs,ys)\n ss = (yi-xb)/(xi-xb);\n S = 1/(ss-1); \n S = num2str(S);\n set(handles.boilupratioinput,'String',S)\n yp(i) = ss*(xp(i)-xb)+xb;\n y = yp(i);\n a = linspace(yp(i-1),yp(i));\n b = xp(i)*ones(length(a));\n plot(b,a)\n while xp (i) > xb\n xp(i+1) = equilib(y,Alpha);\n yp(i+1) = ss*(xp(i+1)-xb)+xb;\n y = yp(i+1);\n a = linspace(xp(i),xp(i+1));\n b = yp(i)*ones(length(a));\n plot(a,b)\n text ((xp(i+1)-.025),(yp(i)+.025),num2str (i))\n if xp (i+1) > xb\n a = linspace(yp(i),yp(i+1));\n b = xp(i+1)*ones(length(a));\n plot(b,a)\n end\n i = i+1;\n end\n \nelseif k ==1 %predefined equilibrium systems\n i = 1;\n xp(1) = xd;\n yp(1) = xd;\n y = xd;\n while xp(i) > xi\n xp(i+1)= predefeq(xeq,yeq,y);\n yp(i+1)= R/(R+1)*xp(i+1)+xd/(R+1);\n y = yp(i+1);\n a = linspace(xp(i),xp(i+1));\n b = yp(i)*ones(length(a));\n plot(a,b)\n text ((xp(i+1)-.025),(yp(i)+.025),num2str (i))\n if xp (i+1) > xi\n c = linspace(yp(i),yp(i+1));\n d = xp(i+1)*ones(length(c));\n plot(d,c)\n end\n i = i+1;\n end\n % Stripping section\n xs = linspace(xb,xi);\n ys = linspace(xb,yi);\n plot(xs,ys)\n ss = (yi-xb)/(xi-xb);\n S = 1/(ss-1); \n S = num2str(S);\n set(handles.boilupratioinput,'String',S)\n yp(i) = ss*(xp(i)-xb)+xb;\n y = yp(i);\n a = linspace(yp(i-1),yp(i));\n b = xp(i)*ones(length(a));\n plot(b,a)\n while xp (i) > xb\n xp(i+1) = predefeq(xeq,yeq,y);\n yp(i+1) = ss*(xp(i+1)-xb)+xb;\n y = yp(i+1);\n a = linspace(xp(i),xp(i+1));\n b = yp(i)*ones(length(a));\n plot(a,b)\n text ((xp(i+1)-.025),(yp(i)+.025),num2str (i))\n if xp (i+1) > xb\n a = linspace(yp(i),yp(i+1));\n b = xp(i+1)*ones(length(a));\n plot(b,a)\n end\n i = i+1;\n end\nend\n\n\n% Functions called with start button: operating & equilibrium lines\nfunction yf = yfeed(xf,Q,zf)\nyf = Q/(Q-1)*xf+zf/(1-Q);\n\nfunction xa = equilib(ya,Alpha)\nxa = ya./(Alpha-ya*(Alpha-1));\n\nfunction ybotop = ybot(x,S,xb)\nybotop = (S+1)/S*x-xb/S;\n\nfunction ytopop = ytop(x,R,xd)\nytopop = R/(R+1)*x+xd/(R+1);\n\nfunction backl = predefeq(xeq,yeq,val)\nxx = 0:.001:1;\nyy = spline(xeq,yeq,xx);\nym = val*ones(1,length(xx));\ndiffe = abs(yy-ym);\n[a b] = min(diffe);\nxk = xx(b);\nbackl = xk;\n\n%System of Nonlinear Equations -- Will be functional in a later version\n\n%User Input Vector\n%L = R*D;\n%V = D*(R+1);\n%Vbar = S*B;\n%Lbar = B*(S+1);\n%Input_Vector = [F,zf,zfnv,xd,xdnv,xb,xbnv,D,fv,fnv,B,S,Q,R,Rmin,hf,hD,hB,Qc,Qr,L,V,Lbar,Vbar,xie,yie,xi,yi];\n%for k = 1:20\n% if isnan(Input_Vector(k)) == 0\n% v(k) = Input_Vector(k);\n% end\n%end\n\n%v(1) = F;\n%v(2) = zf;\n%v(3) = zfnv;\n%v(4) = xd;\n%v(5) = xdnv;\n%v(6) = xb;\n%v(7) = xbnv;\n%v(8) = D;\n%v(9) = fv;\n%v(10) = fnv;\n%v(11) = B;\n%v(12) = S;\n%v(13) = Q;\n%v(14) = R;\n%v(15) = Rmin;\n%v(16) = hf;\n%v(17) = hD;\n%v(18) = hB;\n%v(19) = Qc;\n%v(20) = Qr;\n%v(21) = L;\n%v(22) = V;\n%v(23) = Lbar;\n%v(24) = Vbar;\n%v(25) = xie;\n%v(26) = yie;\n%v(27) = xi;\n%v(28) = yi;\n\n%F = @(v) [v(10)-v(11).*v(7)./v(1)./v(3); v(9)-v(8).*v(4)./v(1)./v(2); v(11)+v(24)-v(23); \n% v(21)+v(8)-v(22); v(23)./v(24)-1./v(12)+1; v(22)./v(21)-1./v(14)-1; v(11)+v(8)-v(1);\n% v(11).*v(6)+v(8).*v(4)-v(1).*v(2); v(2)+v(3)-1; v(6)+v(7)-1; v(4)+v(5)-1; \n% v(1).*v(16)+v(19)+v(20)-v(8).*v(17)-v(11).*v(18); v(15)./(1+v(15))-(v(4)-v(26))./(v(4)-v(25));\n% v(12)-1./(((v(28)-v(6))./(v(27)-v(6)))-1); v(14)./(1+v(14))-(v(4)-v(28))./(v(4)-v(27))];\n\n%InitialGuess = [50;.5;.5;.5;.5;.5;.5;25;.75;.75;25;2;.5;3;1.5;1;1;1;1;1;1;1;1;1;.5;.5;.5;.5];\n%Options = optimset('Display','iter');\n%XY = fsolve(F, InitialGuess, Options);\n\n%fnv - B*xbnv/F/zfnv\n%fv - D*xd/F/zf;\n%B + Vbar - Lbar;\n%L + D - V;\n%Lbar/Vbar - 1/S + 1;\n%V/L - 1/R - 1;\n%B + D - F;\n%B*xb + D*xd - F*zf;\n%zf + zfnv - 1;\n%xb + xbnv - 1;\n%xd + xdnv - 1;\n%F*hf + Qc + Qr - D*hD - B*hB;\n%Rmin/(1+Rmin) - (xd-yie)/(xd-xie);\n%S - 1/((yi-xb)/(xi-xb)-1);\n%R/(1+R)-(xd-yi)/(xd-xi);\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/28485-mccabe-thiele-method-gui-for-binary-column-distillation/McCabeThieleGUI.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.3414180135742385}} {"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% PARAMETERS Returns a data structure containing the parameters of the\n% EPSON C8.\n%\n% The author of this script is:\n%\t\t Silvia Moreno Serrano\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% Copyright (C) 2012, by Arturo Gil Aparicio\n%\n% This file is part of ARTE (A Robotics Toolbox for Education).\n% \n% ARTE is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Lesser General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% ARTE is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU Lesser General Public License for more details.\n% \n% You should have received a copy of the GNU Leser General Public License\n% along with ARTE. If not, see .\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction robot = parameters()\n\nrobot.name= '6AXIS_C8';\n\n%Path where everything is stored for this robot\nrobot.path = 'robots/EPSON/6AXIS_C8';\n\nrobot.DH.theta='[q(1)+pi/2 q(2)+pi/2 q(3) q(4) q(5) q(6)]';\nrobot.DH.d='[0.472 0 0 0.310 0 0.080]';\nrobot.DH.a='[0.100 0.300 0.03 0 0 0]';\nrobot.DH.alpha='[pi/2 0 pi/2 -pi/2 pi/2 0]';\n\nrobot.J=[];\n\n\nrobot.inversekinematic_fn = 'inversekinematic_C8(robot, T)';\nrobot.directkinematic_fn = 'directkinematic(robot, q)';\n\n\n%number of degrees of freedom\nrobot.DOF = 6;\n\n%rotational: 0, translational: 1\nrobot.kind=['R' 'R' 'R' 'R' 'R' 'R'];\n\n%minimum and maximum rotation angle in rad\nrobot.maxangle =[deg2rad(-240) deg2rad(240); %Axis 1, minimum, maximum\n deg2rad(-158) deg2rad(65); %Axis 2, minimum, maximum\n deg2rad(-61) deg2rad(202); %Axis 3\n deg2rad(-200) deg2rad(200); %Axis 4: Unlimited (400? default)\n deg2rad(-135) deg2rad(135); %Axis 5\n deg2rad(-360) deg2rad(360)]; %Axis 6: Really Unlimited to (800? default)\n\n%maximum absolute speed of each joint rad/s or m/s\nrobot.velmax = [deg2rad(331); %Axis 1, rad/s\n deg2rad(332); %Axis 2, rad/s\n deg2rad(450); %Axis 3, rad/s\n deg2rad(450); %Axis 4, rad/s\n deg2rad(450); %Axis 5, rad/s\n deg2rad(720)];%Axis 6, rad/s\n \nrobot.accelmax=robot.velmax/0.1; % 0.1 is here an acceleration time\n \n% end effectors maximum velocity\nrobot.linear_velmax = 1; %m/s\n\n\n\n%base reference system\nrobot.T0 = [1 0 0 0; 0 1 0 0; 0 0 1 0; 0 0 0 1]; %%cambiar para dar la vuelta?\n\n\n\n%INITIALIZATION OF VARIABLES REQUIRED FOR THE SIMULATION\n%position, velocity and acceleration\nrobot=init_sim_variables(robot);\nrobot.path = pwd;\n\n\n% GRAPHICS\nrobot.graphical.has_graphics=1;\nrobot.graphical.color = [255 102 51]./255;\n%for transparency\nrobot.graphical.draw_transparent=1;\n%draw DH systems\nrobot.graphical.draw_axes=1;\n%DH system length and Font size, standard is 1/10. Select 2/20, 3/30 for\n%bigger robots\nrobot.graphical.axes_scale=1;\n%adjust for a default view of the robot\nrobot.axis=[-0.5 1 -0.5 1 0 1];\n%read graphics files\nrobot = read_graphics(robot);\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% DYNAMIC PARAMETERS\n% WARNING! These parameters do not correspond to the actual IRB 140\n% robot. They have been introduced to demonstrate the necessity of \n% simulating the robot and should be used only for educational purposes\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nrobot.has_dynamics=1;\n\n%consider friction in the computations\nrobot.dynamics.friction=0;\n\n%link masses (kg)\nrobot.dynamics.masses=[22 13 6 5 2 1];\n\n%COM of each link with respect to own reference system\nrobot.dynamics.r_com=[0 0 0; %(rx, ry, rz) link 1\n -0.05\t 0.006\t 0.1; %(rx, ry, rz) link 2\n -0.0203\t-0.0141\t 0.070; %(rx, ry, rz) link 3\n 0 0.019 0;%(rx, ry, rz) link 4\n 0 0 0;%(rx, ry, rz) link 5\n 0 0 0.032];%(rx, ry, rz) link 6\n\n%Inertia matrices of each link with respect to its D-H reference system.\n% Ixx\tIyy\tIzz\tIxy\tIyz\tIxz, for each row\nrobot.dynamics.Inertia=[0 0.35\t0 \t0\t0\t0;\n .13 .524\t.539\t0\t0\t0;\n .066\t.086\t.0125\t0\t0\t0;\n 1.8e-3\t1.3e-3\t1.8e-3\t0\t0\t0;\n .3e-3\t.4e-3\t.3e-3\t0\t0\t0;\n .15e-3\t.15e-3\t.04e-3\t0\t0\t0];\n\n\n\nrobot.motors=load_motors([5 5 5 4 4 4]);\n%Speed reductor at each joint\nrobot.motors.G=[300 300 300 300 300 300];\n", "meta": {"author": "4rtur1t0", "repo": "ARTE", "sha": "6e836f3156bb36af63b70bd93375c8ff4ee643c4", "save_path": "github-repos/MATLAB/4rtur1t0-ARTE", "path": "github-repos/MATLAB/4rtur1t0-ARTE/ARTE-6e836f3156bb36af63b70bd93375c8ff4ee643c4/robots/EPSON/C8/parameters.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.3413975039337175}} {"text": "function [tissueModel,coreRxnBool,coreMetBool,coreCtrsBool] = fastcore(model, coreRxnInd, epsilon, printLevel)\n% Use the FASTCORE algorithm ('Vlassis et al, 2014') to extract a context\n% specific model. FASTCORE algorithm defines one set of core\n% reactions that is guaranteed to be active in the extracted model and find\n% the minimum of reactions possible to support the core.\n%\n% USAGE:\n%\n% tissueModel = fastcore(model, coreRxnInd)\n%\n% INPUTS:\n% model: (the following fields are required - others can be supplied)\n% * S - `m x 1` Stoichiometric matrix\n% * lb - `n x 1` Lower bounds\n% * ub - `n x 1` Upper bounds\n% * rxns - `n x 1` cell array of reaction abbreviations\n%\n% coreRxnInd: indices of reactions in cobra model that are part of the\n% core set of reactions (called 'C' in 'Vlassis et al,\n% 2014')\n%\n% OPTIONAL INPUTS:\n% epsilon: smallest flux value that is considered nonzero\n% (default getCobraSolverParams('LP', 'feasTol')*100)\n% printLevel: 0 = silent, 1 = summary, 2 = debug (default - 0)\n%\n% OUTPUT:\n%\n% tissueModel: extracted model\n%\n% coreRxnBool: n x 1 boolean vector indicating core reactions\n% \n% 'Vlassis, Pacheco, Sauter (2014). Fast reconstruction of compact\n% context-specific metbolic network models. PLoS Comput. Biol. 10,\n% e1003424.'\n%\n% .. Authors:\n% - Nikos Vlassis, Maria Pires Pacheco, Thomas Sauter, 2013 LCSB / LSRU, University of Luxembourg\n% - Ronan Fleming, commenting of code and inputs/outputs\n% - Anne Richelle, code adaptation to fit with createTissueSpecificModel\n\nif nargin < 4 || ~exist('printLevel','var')\n printLevel = 0;\nend\nif nargin < 3 || isempty(epsilon)\n epsilon=getCobraSolverParams('LP', 'feasTol')*100;\nend\n\nif printLevel > 1\n tic\nend\n\nmodel_orig = model;\n\n[nMets,nRxns] = size(model.S);\n\nLPproblem = buildLPproblemFromModel(model);\n\n%reactions irreversible in the reverse direction\nIr = model.lb < 0 & model.ub<=0;\n\n%flip direction of reactions irreversible in the reverse direction\nLPproblem.A(:,Ir) = -LPproblem.A(:,Ir);\ntmp = LPproblem.ub(Ir);\nLPproblem.ub(Ir) = -LPproblem.lb(Ir);\nLPproblem.lb(Ir) = -tmp;\n\n%Find irreversible reactions\nirrevRxns = find(model.lb>=0);\n \nA = [];\nflipped = false;\nsingleton = false;\n\n% Find irreversible core reactions\nJ = intersect(coreRxnInd, irrevRxns);\n\nif printLevel > 0\n fprintf('|J|=%d ', length(J));\nend\n\n%Find all the reactions that are not in the core\nnbRxns = 1:nRxns;\n% Non Core reactions (penalized)\nP = setdiff(nbRxns, coreRxnInd);\n\n% Find the minimum of set reactions from P that need to be included to\n% support the irreversible core set of reactions\n[Supp, basis] = findSparseMode(J, P, singleton, model, LPproblem, epsilon);\n\nif ~isempty(setdiff(J, Supp))\n warning('fastcore.m Error: Global network is not flux consistent, ignoring the following irreversible core reactions:\\n');\n model.rxns(setdiff(J, Supp))\n coreRxnInd = setdiff(coreRxnInd,setdiff(J, Supp));\n %error ('fastcore.m Error: Inconsistent irreversible core reactions.\\n');\nend\n\nA = Supp;\nif printLevel > 0\n fprintf('|A|=%d\\n', length(A));\nend\n\n% J is the set of core reactions not already in the extracted model\nJ = setdiff(coreRxnInd, A);\nif printLevel > 0\n fprintf('|J|=%d ', length(J));\nend\n\n% Main loop that reduce at each iteration the number of reactions from P that need to be included to\n% support the complete core set of reactions\nwhile ~isempty(J)\n \n P = setdiff(P, A);\n \n %reuse the basis from the previous solve if it exists\n [Supp, basis] = findSparseMode(J, P, singleton, model, LPproblem, epsilon, basis);\n \n A = union(A, Supp);\n if printLevel > 0\n fprintf('|A|=%d\\n', length(A));\n end\n \n if ~isempty( intersect(J, A))\n J = setdiff(J, A);\n if printLevel > 0\n fprintf('|J|=%d ', length(J));\n end\n flipped = false;\n else\n if singleton\n JiRev = setdiff(J(1),irrevRxns);\n else\n JiRev = setdiff(J,irrevRxns);\n end\n if flipped || isempty(JiRev)\n if singleton\n warning('\\n fastcore.m: Global network is not flux consistent, ignoring corresponding core reaction:\\n');\n disp(model.rxns(J))\n J = [];\n %error('\\n fastcore.m Error: Global network is not consistent.\\n');\n else\n flipped = false;\n singleton = true;\n end\n else\n LPproblem.A(:,JiRev) = -LPproblem.A(:,JiRev);\n tmp = LPproblem.ub(JiRev);\n LPproblem.ub(JiRev) = -LPproblem.lb(JiRev);\n LPproblem.lb(JiRev) = -tmp;\n flipped = true;\n \n if printLevel > 0\n fprintf('(flip) ');\n end\n end\n end\nend\nif printLevel > 0\n fprintf('|A|=%d\\n', length(A)); % A : indices of reactions in the new model\nend\n\nif printLevel > 1\n toc\nend\n\ncoreRxnBool=false(size(model.S,2),1);\ncoreRxnBool(A)=1;\n\nrxnRemoveList = setdiff(model.rxns,model.rxns(A));\n\ndummyMetBool = contains(model.mets,'dummy_Met_');\ndummyRxnBool = contains(model.rxns,'dummy_Rxn_');\ndummyRxnList = model.rxns(dummyRxnBool);\nif any(dummyMetBool) || any(dummyRxnBool)\n model = destroyDummyModel(model,dummyMetBool,dummyRxnBool);\n rxnRemoveList = setdiff(rxnRemoveList,dummyRxnList);\nend\n \n%removes any infeasible coupling constraints also\n[tissueModel, metRemoveList, ctrsRemoveList] = removeRxns(model, rxnRemoveList,'metRemoveMethod','exclusive','ctrsRemoveMethod','infeasible');\n\ncoreMetBool=~ismember(model_orig.mets,metRemoveList);\nif isfield(model,'ctrs')\n coreCtrsBool = ~ismember(model_orig.ctrs,ctrsRemoveList);\nelse\n coreCtrsBool = ctrsRemoveList;\nend\n\n%coreGeneBool\ntissueModel = removeUnusedGenes(tissueModel);", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/src/dataIntegration/transcriptomics/FASTCORE/fastcore.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.4765796510636759, "lm_q1q2_score": 0.34095651827306844}} {"text": "function [ T1temp MP2RAGEcorrected] = T1B1correctpackageTFL( B1img,MP2RAGEimg,T1,MP2RAGE,brain,varargin)\n% usage\n%\n% [ T1corr MP2RAGEcorr] = T1B1correctpackage(B1,MP2RAGEimg,T1,MP2RAGE,brain,varargin)\n%\n% B1 and MP2RAGEimg (and T1) are the nii structures resulting from loading\n% the MP2RAGE (MP2RAGEimg, T1) and the result of some B1 mapping technique\n% with load_nii or load_untouch_nii\n%\n% the variable B1 is compulsory\n%\n% Only MP2RAGEimg or the T1 have to be loaded (I usually use the MP2RAGEimg)\n%\n% the variables that are not loaded can be simply left empty []\n%\n% MP2RAGE variable contains all the relevant sequence\n% information as delailed below\n%\n% B1 will be given in relative units => 1 if it was correct; values can varie\n% from 0-2\n%\n% MP2RAGE.B0=7; % in Tesla\n% MP2RAGE.TR=6; % MP2RAGE TR in seconds\n% MP2RAGE.TRFLASH=6.7e-3; % TR of the GRE readout\n% MP2RAGE.TIs=[800e-3 2700e-3];% inversion times - time between middle of refocusing pulse and excitatoin of the k-space center encoding\n% MP2RAGE.NZslices=[40 80];% Slices Per Slab * [PartialFourierInSlice-0.5 0.5]\n% MP2RAGE.FlipDegrees=[4 5];% Flip angle of the two readouts in degrees\n%\n% brain can be an image in the same space as the MP2RAGE and the\n% Sa2RAGE that has zeros where there is no need to do any T1/B1 calculation\n% (can be a binary mask or not). if left empty the calculation is done\n% everywhere\n%\n% additionally the inversion efficiency of the adiabatic inversion can be\n% set as a last optional variable. Ideally it should be 1.\n% In the first implementation of the MP2RAGE the inversino efficiency was\n% measured to be ~0.96\n%\n% outputs are:\n% T1corr - T1map corrected for B1 bias\n% MP2RAGEcorr - MP2RAGE image corrected for B1 bias\n%\n%\n% please cite:\n% Marques, J.P., Gruetter, R., 2013. New Developments and Applications of the MP2RAGE Sequence - Focusing the Contrast and High Spatial Resolution R1 Mapping. PLoS ONE 8. doi:10.1371/journal.pone.0069294\n% Marques, J.P., Kober, T., Krueger, G., van der Zwaag, W., Van de Moortele, P.-F., Gruetter, R., 2010a. MP2RAGE, a self bias-field corrected sequence for improved segmentation and T1-mapping at high field. NeuroImage 49, 1271�1281. doi:10.1016/j.neuroimage.2009.10.002\n%\n\n\n% Check B1 range \nb1med = median(prctile(B1img(:),90));\n\nif b1med > 5\n \n warning(sprintf(['=============== mp2rage::b1correction ==========='...\n '\\n B1 data is not in [0-2] range. B1map magnitude will be scaled down.' ...\n '\\n ===========================================================' ...\n ]));\n\n if b1med > 10 && b1med < 500\n\n B1img = double(B1img)./100;\n \n elseif b1med>500 && b1med<1500\n \n B1img = double(B1img)./1000;\n end\nend\n\nb1med = median(prctile(B1img(:),90));\n\nif ~(b1med > 0.5) && ~(b1med < 1.5)\n\n warning(sprintf(['=============== mp2rage::b1correction ==========='...\n '\\n B1 data may not be in the required [0-2] range' ...\n '\\n ===========================================================' ...\n ]));\n\nend\n\nif nargin==6\n \n invEFF=varargin{1};\n \nelse\n \n invEFF=0.96;\n \nend\n\nif isempty(brain)\n \n if isempty(MP2RAGEimg)\n \n brain=T1;\n \n brain.img=ones(size(brain.img));\n \n else\n \n brain=MP2RAGEimg;\n \n brain.img=ones(size(brain.img));\n \n end;\n \nend;\n\nB1_vector=0.005:0.05:1.9;\n\nT1_vector=0.5:0.05:5.2;\n\n[MP2RAGE.Intensity MP2RAGE.T1vector ]=MP2RAGE_lookuptable(2,MP2RAGE.TR,MP2RAGE.TIs,MP2RAGE.FlipDegrees,MP2RAGE.NZslices,MP2RAGE.TRFLASH,'normal',invEFF);\n\nif isempty(MP2RAGEimg)\n \n T1.img=double(T1.img)/1000;\n \n MP2RAGEimg.img=reshape(interp1(MP2RAGE.T1vector,MP2RAGE.Intensity,T1.img(:)),size(B1img));\n \n MP2RAGEimg.img(isnan(MP2RAGEimg.img))=-0.5;\n \nelse\n \n MP2RAGEimg.img=double(MP2RAGEimg.img)/4095-0.5;\n \nend;\n\n\n%% now the fun starts\n\n% creates a lookup table of MP2RAGE intensities as a function of B1 and T1\n\nk=0;\n\nfor b1val=B1_vector\n \n k=k+1;\n \n [Intensity T1vector ]=MP2RAGE_lookuptable(2,MP2RAGE.TR,MP2RAGE.TIs,b1val*MP2RAGE.FlipDegrees,MP2RAGE.NZslices,MP2RAGE.TRFLASH,'normal',invEFF);\n \n MP2RAGEmatrix(k,:)=interp1(T1vector,Intensity,T1_vector);\n \nend;\n\nk=0;\n\n\n\n%% make the matrix MP2RAGEMatrix into T1_matrix(B1,ratio)\n\nnpoints=40;\n\nMP2RAGE_vector=linspace(-0.5,0.5,npoints);\n\nk=0;\n\nfor b1val=B1_vector\n \n k=k+1;\n \n try\n \n T1matrix(k,:)=interp1(MP2RAGEmatrix(k,:),T1_vector,MP2RAGE_vector,'pchirp');\n \n catch\n \n temp=MP2RAGEmatrix(k,:);\n \n temp(isnan(temp))=linspace(-0.5-eps,-1,length(find(isnan(temp)==1)));\n \n temp=interp1(temp,T1_vector,MP2RAGE_vector);\n \n T1matrix(k,:)=temp;\n \n \n \n end;\n \nend;\n\n%% correcting the estimates of T1 and B1 iteratively\n\nT1temp=MP2RAGEimg;\n\nbrain.img(B1img==0)=0;\n\nbrain.img(MP2RAGEimg.img==0)=0;\n\nT1temp.img(brain.img==0)=0;\n\nT1temp.img(brain.img==1)=0;\n\nB1img(brain.img==0)=0;\n\ntemp=squeeze(T1temp.img(:,end/2,:));\n\nT1temp.img(brain.img~=0)=interp2(MP2RAGE_vector,B1_vector,T1matrix,MP2RAGEimg.img(brain.img~=0),B1img(brain.img~=0));\n\nT1temp.img(isnan(T1temp.img))=4;\n\ntemp2=squeeze(T1temp.img(:,end/2,:));\n\n%% creates an MP2RAGEcorrected image and puts both the B1 and T1 in the ms scale\n\n[MP2RAGE.Intensity MP2RAGE.T1vector ]=MP2RAGE_lookuptable(2,MP2RAGE.TR,MP2RAGE.TIs,MP2RAGE.FlipDegrees,MP2RAGE.NZslices,MP2RAGE.TRFLASH,'normal',invEFF);\n\nMP2RAGEcorrected=MP2RAGEimg;\n\nMP2RAGEcorrected.img=reshape(interp1(MP2RAGE.T1vector,MP2RAGE.Intensity,T1temp.img(:)),size(T1temp.img));\n\nMP2RAGEcorrected.img(isnan(MP2RAGEcorrected.img))=-0.5;\n\nMP2RAGEcorrected.img=round(4095*(MP2RAGEcorrected.img+0.5));\n\n%T1temp.img=(T1temp.img)*1000;\n\nend\n\n", "meta": {"author": "qMRLab", "repo": "qMRLab", "sha": "036ff20b47e939877f746940a969494b55911636", "save_path": "github-repos/MATLAB/qMRLab-qMRLab", "path": "github-repos/MATLAB/qMRLab-qMRLab/qMRLab-036ff20b47e939877f746940a969494b55911636/src/Models_Functions/MP2RAGE/func/T1B1correctpackageTFL.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6406358411176238, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.34031176372086225}} {"text": "function [inflMap, colXCoord, rowYCoord, colDividerXCoord, rowDividerYCoord, rowLeafPositions] = getLSInfluenceMapFactorEx(LS,leak,beamIndex)\n%\"getLSInfluenceMap\"\n% Gets an image of the influence generated by the beam described in LS.\n% Use getDICOMLeafPositions to generate LS.\n%\n%JRA&KZ 02/8/05\n%\n%Usage:\n% function inflMap = getLSInfluenceMap(LS);\n%\n% Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team.\n% \n% This file is part of The Computational Environment for Radiotherapy Research (CERR).\n% \n% CERR development has been led by: Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy.\n% \n% CERR has been financially supported by the US National Institutes of Health under multiple grants.\n% \n% CERR is distributed under the terms of the Lesser GNU Public License. \n% \n% This version of CERR is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% CERR is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;\n% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n% See the GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with CERR. If not, see .\n\n%Maximum precision of leaf position, in mm.\nprecision = .1;\n\n%Get x max, min and round to precision value.\n% xMax = ceil(max(vertcat(LS.xLimits{1}),[],1) / precision) * precision;\n% xMin = floor(min(vertcat(LS.xLimits{1}),[],1) / precision) * precision;\n% fieldSize.x = max(xMax) - min(xMin);\n% fieldLim.x = [max(xMax) min(xMin)];\n\n%Siemens no X jaws exist\nif ~isfield(LS,'xLimits')\n xMax = ceil(max(vertcat(LS.xLeafPositions{:}),[],1) / precision) * precision;\n xMin = floor(min(vertcat(LS.xLeafPositions{:}),[],1) / precision) * precision;\n LS.xLimits{1}(1) = xMin;\n LS.xLimits{1}(2) = xMax;\nend\n\nxMax = ceil(max(vertcat(LS.xLimits{:}),[],1) / precision) * precision;\nxMin = floor(min(vertcat(LS.xLimits{:}),[],1) / precision) * precision;\nfieldSize.x = max(xMax) - min(xMin);\nfieldLim.x = [max(xMax) min(xMin)];\n\nyMax = ceil(max(vertcat(LS.yLimits{:}),[],1) / precision) * precision;\nyMin = floor(min(vertcat(LS.yLimits{:}),[],1) / precision) * precision;\nfieldSize.y = max(yMax) - min(yMin);\nfieldLim.y = [max(yMax) min(yMin)];\n\nyRes = precision;\nnyElements = ceil(fieldSize.y/yRes);\nxRes = precision;\nnxElements = ceil(fieldSize.x/xRes);\n\ninflMap=zeros(nyElements, nxElements);\ncolDividerXCoord = linspace(fieldLim.x(2), fieldLim.x(1), nxElements+1);\nrowDividerYCoord = linspace(fieldLim.y(2), fieldLim.y(1), nyElements+1);\n\nif isfield(LS, 'yLeafPositions')\n rowLeafPositions = round(interp1(rowDividerYCoord, 1:nyElements+1, LS.yLeafPositions,'linear', 'extrap'));\n rowLeafPositions = clip(rowLeafPositions, 1, nyElements+1, 'limits');\n leafBoundariesToKeep = [diff(rowLeafPositions)>0;logical(1)];\n rowLeafPositions = rowLeafPositions(leafBoundariesToKeep);\n leavesToKeep = leafBoundariesToKeep(1:end-1);\nelse\n %LS.xLeafPositions{1} = [xMin xMax-precision];\n LS.xLeafPositions{1} = [xMin xMax];\n LS.meterSetWeight = {1};\n rowLeafPositions = [1 nyElements+1];\n leavesToKeep = 1;\nend\n\nif length(LS.meterSetWeight) == 1\n doses = LS.meterSetWeight{:};\nelse\n doses = [0 diff([LS.meterSetWeight{:}])];\nend\n\nh = waitbar(0,['Generating Fluence Map For Beam ',num2str(beamIndex)]);\n\nfor i=1:length(LS.xLeafPositions)\n \n nLeaves = length(LS.xLeafPositions{i})/2;\n\n if length(LS.xLimits) > 1\n jpL = LS.xLimits{i}(1);\n jpR = LS.xLimits{i}(2);\n else\n jpL = LS.xLimits{1}(1);\n jpR = LS.xLimits{1}(2);\n end\n\n lpL = LS.xLeafPositions{i}(1:nLeaves);\n lpR = LS.xLeafPositions{i}(nLeaves+1:end);\n lpLK = lpL(leavesToKeep);\n lpRK = lpR(leavesToKeep);\n lpLCols = interp1(colDividerXCoord, 1:nxElements+1, lpLK, 'linear', 'extrap');\n lpRCols = interp1(colDividerXCoord, 1:nxElements+1, lpRK, 'linear', 'extrap');\n\n %Column divider positions of jaws.\n jpLCol = interp1(colDividerXCoord, 1:nxElements+1, jpL, 'linear', 'extrap');\n jpRCol = interp1(colDividerXCoord, 1:nxElements+1, jpR, 'linear', 'extrap');\n\n lpLCols = clip(lpLCols, jpLCol, jpRCol, 'limits');\n lpRCols = clip(lpRCols, jpLCol, jpRCol, 'limits');\n\n lpLCols = round(lpLCols);\n lpRCols = round(lpRCols);\n\n %head scatter radiation parametrs for varian\n a2 = 0.078;\n beta = 1.79;\n lambda = 7.69;\n\n\n for j=1:length(lpLCols)\n %HCF from output ratio for MLC fields Zhu, MedPhys\n YMLC = rowDividerYCoord(rowLeafPositions(j)) + abs((rowDividerYCoord(rowLeafPositions(j+1)) - rowDividerYCoord(rowLeafPositions(j))))/2;\n YMLC = YMLC/10;\n sizeLeaf = abs((rowDividerYCoord(rowLeafPositions(j+1)) - rowDividerYCoord(rowLeafPositions(j))));\n sizeLeaf = sizeLeaf/10;\n HCF_UP = 1 + a2*(erf(2*lpLK(j)*beta/(10*lambda)) + erf(2*lpRK(j)*beta/(10*lambda)))*(erf(2*(YMLC + sizeLeaf/2)/lambda) - erf(2*(YMLC - sizeLeaf/2)/lambda))/4;\n HCF_Down = 1 + a2*(erf(2*jpL/(10*lambda)) + erf(2*jpR/(10*lambda)))*(erf(2*(YMLC + sizeLeaf/2)/lambda) - erf(2*(YMLC - sizeLeaf/2)/lambda))/4;\n HCF = HCF_UP/HCF_Down;\n inflMap(rowLeafPositions(j):rowLeafPositions(j+1)-1, lpLCols(j):lpRCols(j)-1) = inflMap(rowLeafPositions(j):rowLeafPositions(j+1)-1, lpLCols(j):lpRCols(j)-1) + HCF*doses(i);\n inflMap(rowLeafPositions(j):rowLeafPositions(j+1)-1, jpLCol:lpLCols(j)-1) = inflMap(rowLeafPositions(j):rowLeafPositions(j+1)-1, jpLCol:lpLCols(j)-1) + leak*doses(i);\n inflMap(rowLeafPositions(j):rowLeafPositions(j+1)-1, lpRCols(j):jpRCol-1) = inflMap(rowLeafPositions(j):rowLeafPositions(j+1)-1, lpRCols(j):jpRCol-1) + leak*doses(i);\n end\n \n waitbar(i/length(LS.xLeafPositions));\nend\nclose(h);\ncolXCoord = colDividerXCoord(1:end-1) + precision/2;\nrowYCoord = rowDividerYCoord(1:end-1) + precision/2;", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/IMRTP/recompDose/FFDC/getLSInfluenceMapFactorEx.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947425132314, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.34023178236994955}} {"text": "function f = plus(f, g)\n%+ Addition of two TRIGTECH objects.\n% F + G adds F and G, where F and G may be TRIGTECH objects or scalars.\n%\n% If F is an array-valued TRIGTECH, then F + C is supported if C is a row\n% vector of doubles with the same number of columns as F.\n%\n% See also MINUS, UPLUS.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers. \n% See http://www.chebfun.org/ for Chebfun information.\n\nif ( isempty(f) || isempty(g) ) % TRIGTECH + [] = [].\n \n f = [];\n \nelseif ( isa(g, 'double') ) % TRIGTECH + double.\n \n % Update values (use bsxfun() to handle the case in which g is a vector\n % and f is an array-valued TRIGTECH):\n f.values = bsxfun(@plus, f.values, g);\n \n % Update coeffs:\n if ( (size(g, 2) > 1) && (size(f.coeffs, 2) == 1) )\n % Perform singleton expansion of f:\n f.coeffs = repmat(f.coeffs, 1, size(g, 2));\n end\n N = size(f.coeffs,1);\n \n % Determine the index in the coefficient vector where the constant term\n % is stored. The way we have arranged the coefficients means it should\n % be in the middle of the array, but that depends on whether the number\n % of coefficients is even or odd.\n if mod(N,2) == 1\n const_index = (N+1)/2;\n else\n const_index = N/2+1;\n end\n f.coeffs(const_index,:) = f.coeffs(const_index,:) + g;\n \n % Update isReal:\n f.isReal = f.isReal & isreal(g);\n \nelseif ( isa(f, 'double') ) % double + TRIGTECH.\n \n % Switch argument order and call TRIGTECH/PLUS again:\n f = plus(g, f);\n \nelseif ( isa(f, 'trigtech') && isa(g, 'trigtech') ) % TRIGTECH + TRIGTECH.\n \n % We will simply add the values together then compute the coefficients\n % of the result. This is probably not the most efficient means of\n % determing the sum.\n nf = size(f.values, 1);\n ng = size(g.values, 1);\n if ( nf > ng )\n % Increase the length of g (via PROLONG):\n g = prolong(g, nf);\n elseif ( nf < ng )\n % Increase the length of f (via PROLONG):\n f = prolong(f, ng);\n end\n \n % Update values and coefficients:\n f.values = f.values + g.values;\n f.coeffs = f.vals2coeffs(f.values);\n\n % Update isReal:\n f.isReal = f.isReal & g.isReal;\n \n % Force the values to be real where f is real.\n f.values(:,f.isReal) = real(f.values(:,f.isReal));\n \n % Look for a zero output:\n if ( ~any(f.values(:)) || ~any(f.coeffs(:)) )\n % Create a zero TRIGTECH:\n ishappy = f.ishappy && g.ishappy;\n z = zeros(1, size(f.values, 2));\n data.vscale = z;\n f = f.make(z, data);\n f.ishappy = ishappy;\n else\n f.ishappy = f.ishappy && g.ishappy;\n end\n \nelse % Don't know how to do the addition of the objects.\n \n error('CHEBFUN:TRIGTECH:plus:typeMismatch',['Incompatible operation between objects.\\n', ...\n 'Make sure functions are of the same type.']);\n \nend\n\nend\n", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/@trigtech/plus.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926666143433998, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.34000003946679236}} {"text": "function vel = veldim(vel,from,to)\n%VELDIM Convert velocity units\n%\n% velOut = VELDIM(velIn, FROM, TO) converts velIn from the units\n% specified by the string FROM to the units specified by the string\n% TO. FROM and TO are case-insensitive, and may equal any of the\n% following:\n%\n% 'meters per second', 'mps' or 'm/s'\n% 'feet per second', 'ftps' or 'ft/s' <== U.S. survey feet\n% 'kilometers per hour', 'kmph', 'km/hr', or 'km/h'\n% 'knots', 'kts', 'nm/hr' or 'nm/h'\n% 'miles per hour', 'mph', 'mi/hr', 'mi/h', sm/hr' or 'sm/h' <== statute miles\n%\n% Exercise caution with 'feet' and 'miles'\n% ----------------------------------------\n% VELDIM interprets 'feet per second', 'ftps', and 'ft/s' as U.S. survey\n% feet per second, and does not support international feet at all.\n%\n% By definition, one international foot is exactly 0.3048 meters and\n% one U.S. survey foot is exactly 1200/3937 meters. For many\n% applications, the difference is significant.\n%\n% Likewise, VELDIM interprets 'miles per hour', 'mph', 'mi/h', and 'sm/h'\n% as statute miles per hour (also known as U.S. survey miles), and does\n% not support international miles per hour at all. By definition, one\n% international mile is 5280 international feet and one statute mile is\n% 5280 survey feet.\n%\n% See also MPS2FTPS, MPS2KMPH, MPS2KTS, MPS2MPH,\n% FTPS2MPS, FTPS2KMPH, FTPS2KTS, FTPS2MPH,\n% KMPH2MPS, KMPH2FTPS, KMPH2KTS, KMPH2MPH,\n% KTS2MPS, KTS2FTPS, KTS2KMPH, KTS2MPH, \n% MPH2MPS, MPH2FTPS, MPH2KMPH, MPH2KTS\n\nerror(nargchk(3, 4, nargin, 'struct'))\n\n% Warn and convert to real if VEL is complex.\nvel = ignoreComplex(vel, mfilename, 'VEL');\n\n% Convert units only if there's something to change.\nif ~strcmp(from, to)\n vel = applyconversion(vel, from, to);\nend\n\nfunction vel = applyconversion(vel, from, to)\n\nfrom = lower(from);\nto = lower(to);\n\ntoIsSupported = true;\nfromIsSupported = true;\n\nswitch from\n case {'meters per second','mps','m/s'}\n switch to\n case {'feet per second','ftps','ft/s'}\n vel = mps2ftps(vel);\n case {'kilometers per hour','kmph','km/h','km/hr'}\n vel = mps2kmph(vel);\n case {'knots','kts','nm/h','nm/hr'}\n vel = mps2kts(vel);\n case {'miles per hour','mph','mi/hr','mi/h','sm/hr','sm/h'}\n vel = mps2mph(vel);\n otherwise\n toIsSupported = false;\n end\n case {'feet per second','ftps','ft/s'}\n switch to\n case {'meters per second','mps','m/s'}\n vel = ftps2mps(vel);\n case {'kilometers per hour','kmph','km/h','km/hr'}\n vel = ftps2kmph(vel);\n case {'knots','kts','nm/h','nm/hr'}\n vel = ftps2kts(vel);\n case {'miles per hour','mph','mi/hr','mi/h','sm/hr','sm/h'}\n vel = ftps2mph(vel);\n otherwise\n toIsSupported = false;\n end\n case {'kilometers per hour','kmph','km/h','km/hr'}\n switch to\n case {'feet per second','ftps','ft/s'}\n vel = kmph2ftps(vel);\n case {'meters per second','mps','m/s'}\n vel = kmph2mps(vel);\n case {'knots','kts','nm/h','nm/hr'}\n vel = kmph2kts(vel);\n case {'miles per hour','mph','mi/hr','mi/h','sm/hr','sm/h'}\n vel = kmph2mph(vel);\n otherwise\n toIsSupported = false;\n end\n case {'knots','kts','nm/h','nm/hr'}\n switch to\n case {'feet per second','ftps','ft/s'}\n vel = kts2ftps(vel);\n case {'kilometers per hour','kmph','km/h','km/hr'}\n vel = kts2kmph(vel);\n case {'meters per second','mps','m/s'}\n vel = kts2mps(vel);\n case {'miles per hour','mph','mi/hr','mi/h','sm/hr','sm/h'}\n vel = kts2mph(vel);\n otherwise\n toIsSupported = false;\n end\n case {'miles per hour','mph','mi/hr','mi/h','sm/hr','sm/h'}\n switch to\n case {'feet per second','ftps','ft/s'}\n vel = mph2ftps(vel);\n case {'kilometers per hour','kmph','km/h','km/hr'}\n vel = mph2kmph(vel);\n case {'knots','kts','nm/h','nm/hr'}\n vel = mph2kts(vel);\n case {'meters per second','mps','m/s'}\n vel = mph2mps(vel);\n otherwise\n toIsSupported = false;\n end\n\n otherwise\n fromIsSupported = false;\nend\n\nassert(toIsSupported, 'map:distdim:UnsupportedToUnits', ...\n 'Unsupported ''TO'' units: %s.', to)\n\nassert(fromIsSupported, 'map:distdim:UnsupportedFromUnits', ...\n 'Unsupported ''FROM'' units: %s.', from)", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/31665-velocity-conversion-toolbox/veldim.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.5698526514141572, "lm_q1q2_score": 0.33987900979018465}} {"text": "function edgeFaces = meshEdgeFaces(vertices, edges, faces) %#ok\n%MESHEDGEFACES Compute index of faces adjacent to each edge of a mesh.\n%\n% EF = meshEdgeFaces(V, E, F)\n% Compute index array of faces adjacent to each edge of a mesh.\n% V, E and F define the mesh: V is vertex array, E contains vertex\n% indices of edge extremities, and F contains vertex indices of each\n% face, either as a numerical array or as a cell array.\n% The result EF has as many rows as the number of edges, and two column.\n% The first column contains index of faces located on the left of the\n% corresponding edge, whereas the second column contains index of the\n% face located on the right. Some indices may be 0 if the mesh is not\n% 'closed'.\n% \n% Note: a faster version is available for triangular meshes.\n%\n% Example\n% meshEdgeFaces\n%\n% See also \n% meshes3d, trimeshEdgeFaces, meshDihedralAngles, polyhedronMeanBreadth\n\n% ------\n% Author: David Legland\n% E-mail: david.legland@grignon.inra.fr\n% Created: 2010-10-04, using Matlab 7.9.0.529 (R2009b)\n% Copyright 2010-2022 INRA - Cepia Software Platform\n\nNe = size(edges, 1);\n\n% indices of faces adjacent to each edge\nedgeFaces = zeros(Ne, 2);\n\n% different method for extracting current face depending if faces are\n% stored as index 2D array or as cell array of 1D arrays.\nif isnumeric(faces)\n Nf = size(faces, 1);\n for i = 1:Nf\n face = faces(i, :);\n processFace(face, i)\n end\nelseif iscell(faces)\n Nf = length(faces);\n for i = 1:Nf\n face = faces{i};\n processFace(face, i)\n end\nend\n\n function processFace(face, indFace)\n % iterate on face edges\n for j = 1:length(face)\n % build edge: array of vertices\n j2 = mod(j, length(face)) + 1;\n \n % do not process edges with same vertices\n if face(j) == face(j2)\n continue;\n end\n \n % vertex indices of current edge\n currentEdge = [face(j) face(j2)];\n \n % find index of current edge, assuming face is left-located\n b1 = ismember(edges, currentEdge, 'rows');\n indEdge = find(b1);\n if ~isempty(indEdge)\n if edgeFaces(indEdge, 1) ~= 0\n error('meshes3d:IllegalTopology', ...\n 'Two faces were found on left side of edge %d ', indEdge);\n end\n \n edgeFaces(indEdge, 1) = indFace;\n continue;\n end\n \n % otherwise, assume the face is right-located\n b2 = ismember(edges, currentEdge([2 1]), 'rows');\n indEdge = find(b2);\n if ~isempty(indEdge)\n if edgeFaces(indEdge, 2) ~= 0\n error('meshes3d:IllegalTopology', ...\n 'Two faces were found on left side of edge %d ', indEdge);\n end\n \n edgeFaces(indEdge, 2) = indFace;\n continue;\n end\n \n % If face was neither left nor right, error\n warning('meshes3d:IllegalTopology', ...\n 'Edge %d of face %d was not found in edge array', ...\n j, indFace);\n continue;\n end\n end\n\nend\n", "meta": {"author": "mattools", "repo": "matGeom", "sha": "1fd2c937064be1ee1f4fd09fbfdf96145ebe5271", "save_path": "github-repos/MATLAB/mattools-matGeom", "path": "github-repos/MATLAB/mattools-matGeom/matGeom-1fd2c937064be1ee1f4fd09fbfdf96145ebe5271/matGeom/meshes3d/meshEdgeFaces.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.3398790097901846}} {"text": "%This Matlab script can be used to reproduce Figure 6.4 in the monograph:\n%\n%Emil Bjornson, Jakob Hoydis and Luca Sanguinetti (2017), \n%\"Massive MIMO Networks: Spectral, Energy, and Hardware Efficiency\", \n%Foundations and Trends in Signal Processing: Vol. 11, No. 3-4, \n%pp. 154-655. DOI: 10.1561/2000000093.\n%\n%For further information, visit: https://www.massivemimobook.com\n%\n%This is version 1.0 (Last edited: 2017-11-04)\n%\n%License: This code is licensed under the GPLv2 license. If you in any way\n%use this code for research that results in publications, please cite our\n%monograph as described above.\n\n\n%Empty workspace and close figures\nclose all;\nclear;\n\n\n%Number of BSs\nL = 16;\n\n%Range of number of UEs per BS\nKrange = [10 20];\n\n%Compute maximum number of UEs\nKmax = max(Krange);\n\n%Number of BS antennas\nM = 100;\n\n%Define the range of pilot reuse factors\nfRange = [1 2 4];\n\n%Select the number of setups with random UE locations\nnbrOfSetups = 1;\n\n%Select the number of channel realizations per setup\nnbrOfRealizations = 200;\n\n%Select the range of hardware qualities. The values at the same position in\n%the different vectors are considered simultaneously.\nkappatUE = [0.9 0.92 0.94 0.96 0.97 0.98 0.99 0.995 1];\nkapparBS = kappatUE;\n\n\n%% Propagation parameters\n\n%Communication bandwidth\nB = 20e6;\n\n%Define total uplink transmit power per UE (mW)\np = 100;\n\n%Define noise figure at BS (in dB)\nnoiseFigure = 7;\n\n%Compute noise power\nnoiseVariancedBm = -174 + 10*log10(B) + noiseFigure;\n\n%Select length of coherence block\ntau_c = 200;\n\n%Use the approximation of the Gaussian local scattering model\naccuracy = 2;\n\n%Angular standard deviation in the local scattering model (in degrees)\nASDdeg = 10;\n\n\n%Prepare to save simulation results\nsumSE_MR = zeros(length(kappatUE),length(fRange),nbrOfSetups,length(Krange));\nsumSE_RZF = zeros(length(kappatUE),length(fRange),nbrOfSetups,length(Krange));\nsumSE_MMMSE = zeros(length(kappatUE),length(fRange),nbrOfSetups,length(Krange));\n\n\n%% Go through all setups\nfor n = 1:nbrOfSetups\n \n %Output simulation progress\n disp([num2str(n) ' setups out of ' num2str(nbrOfSetups)]);\n \n %Compute channel statistics for one setup\n [R,channelGaindB] = functionExampleSetup(L,Kmax,M,accuracy,ASDdeg);\n \n %Compute the normalized average channel gain, where the normalization\n %is based on the noise power\n channelGainOverNoise = channelGaindB - noiseVariancedBm;\n \n \n %Go through all pilot reuse factors\n for s = 1:length(fRange)\n \n %Output simulation progress\n disp([num2str(s) ' reuse factors out of ' num2str(length(fRange))]);\n \n %Extract pilot reuse factor\n f = fRange(s);\n \n %Go through all hardware qualities\n for r = 1:length(kappatUE)\n \n for kind = 1:length(Krange)\n \n %Extract number of UEs\n K = Krange(kind);\n \n %Generate channel realizations with estimates and estimation\n %error correlation matrices, using LMMSE estimation\n [Hhat,C,tau_p,~,H] = functionChannelEstimates_impairments(R(:,:,1:K,:,:),channelGainOverNoise(1:K,:,:),nbrOfRealizations,M,K,L,p,f,kappatUE(r),kapparBS(r));\n \n %Compute SEs using Monte Carlo realizations\n [SE_MR,SE_RZF,SE_MMMSE] = functionComputeSE_UL_impairments(H,Hhat,C,tau_c,tau_p,nbrOfRealizations,M,K,L,p,kappatUE(r),kapparBS(r));\n \n %Save results\n sumSE_MR(r,s,n,kind) = mean(sum(SE_MR,1));\n sumSE_RZF(r,s,n,kind) = mean(sum(SE_RZF,1));\n sumSE_MMMSE(r,s,n,kind) = mean(sum(SE_MMMSE,1));\n \n %Delete large matrices\n clear Hhat C H;\n \n end\n \n end\n \n end\n \n %Delete large matrices\n clear R;\n \nend\n\n\n%% Plot the simulation results\nfor kind = 1:length(Krange)\n \n figure;\n hold on; box on;\n \n plot(kappatUE,max(mean(sumSE_MMMSE(:,:,:,kind),3),[],2),'rd-','LineWidth',1);\n plot(kappatUE,max(mean(sumSE_RZF(:,:,:,kind),3),[],2),'k-.','LineWidth',1);\n plot(kappatUE,max(mean(sumSE_MR(:,:,:,kind),3),[],2),'bs-','LineWidth',1);\n \n xlabel('Hardware quality');\n ylabel('Average sum SE [bit/s/Hz/cell]');\n legend('M-MMSE','RZF','MR','Location','NorthWest');\n ylim([0 ceil(max(max(mean(sumSE_MMMSE(:,:,:,kind),3),[],2))/10)*10]);\n \nend\n", "meta": {"author": "emilbjornson", "repo": "massivemimobook", "sha": "4e429497dea72d52172972f3f686b34d1d047013", "save_path": "github-repos/MATLAB/emilbjornson-massivemimobook", "path": "github-repos/MATLAB/emilbjornson-massivemimobook/massivemimobook-4e429497dea72d52172972f3f686b34d1d047013/Code/section6_figure4.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5964331319177487, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.33987900161457885}} {"text": "%%*******************************************************************\n%% HSDNTrhsfun: compute the right-hand side vector of the\n%% Schur complement equation for the NT direction.\n%%\n%% SDPT3: version 3.1\n%% Copyright (c) 1997 by\n%% K.C. Toh, M.J. Todd, R.H. Tutuncu\n%% Last Modified: 16 Sep 2004\n%%*******************************************************************\n\nfunction [rhs,EinvRc,hRd] = HSDNTrhsfun(blk,At,par,X,Z,rp,Rd,sigmu,hRd,dX,dZ)\nglobal spdensity\n\nm = par.m;\nif (nargin > 8)\n corrector = 1;\nelse\n corrector = 0;\n hRd = zeros(m+2,1);\nend\nhEinvRc = zeros(m+2,1);\nEinvRc = cell(size(blk,1),1);\nif length(sigmu)==1; sigmu = sigmu*ones(1,size(blk,1)); end\n%%\nfor p = 1:size(blk,1)\n pblk = blk(p,:);\n n = sum(pblk{2}); numblk = length(pblk{2});\n if strcmp(pblk{1},'l')\n if (corrector)\n Rq = dX{p}.*dZ{p};\n else\n Rq = sparse(n,1);\n tmp = par.dd{p}.*Rd{p};\n tmp2 = mexMatvec(At{p},tmp,1);\n hRd = hRd + tmp2;\n end\n EinvRc{p} = sigmu(p)./Z{p}-X{p} -Rq./Z{p};\n tmp2 = mexMatvec(At{p},EinvRc{p},1);\n hEinvRc = hEinvRc + tmp2;\n elseif strcmp(pblk{1},'q')\n w = sqrt(par.gamz{p}./par.gamx{p});\n if (corrector)\n hdx = qops(pblk,w,par.ff{p},5,dX{p});\n hdz = qops(pblk,w,par.ff{p},6,dZ{p});\n hdxdz = Arrow(pblk,hdx,hdz);\n vv = qops(pblk,w,par.ff{p},5,X{p});\n Vihdxdz = Arrow(pblk,vv,hdxdz,1);\n Rq = qops(pblk,w,par.ff{p},6,Vihdxdz);\n else\n Rq = sparse(n,1);\n tmp = par.dd{p}.*Rd{p} + qops(pblk,qops(pblk,Rd{p},par.ee{p},1),par.ee{p},3);\n tmp2 = mexMatvec(At{p},tmp,1);\n hRd = hRd + tmp2;\n end\n EinvRc{p} = qops(pblk,-sigmu(p)./(par.gamz{p}.*par.gamz{p}),Z{p},4)-X{p}-Rq;\n tmp2 = mexMatvec(At{p},EinvRc{p},1);\n hEinvRc = hEinvRc + tmp2;\n elseif strcmp(pblk{1},'s')\n n2 = pblk{2}.*(pblk{2}+1)/2;\n if (corrector)\n hdZ = Prod3(pblk,par.G{p},dZ{p},par.G{p}',1);\n hdX = spdiags(-par.sv{p},0,n,n)-hdZ;\n tmp = Prod2(pblk,hdX,hdZ,0);\n tmp = 0.5*(tmp+tmp');\n if (numblk == 1)\n d = par.sv{p};\n e = ones(pblk{2},1);\n Rq = 2*tmp./(d*e'+e*d');\n if (nnz(Rq) <= spdensity*n2); Rq = sparse(Rq); end\n else\n Rq = sparse(n,n);\n s = [0, cumsum(pblk{2})];\n for i = 1:numblk\n pos = s(i)+1 : s(i+1);\n d = par.sv{p}(pos); e = ones(length(pos),1);\n Rq(pos,pos) = 2*tmp(pos,pos)./(d*e' + e*d'); %#ok\n end\n end\n else\n Rq = sparse(n,n);\n EinvRc{p} = Prod3(pblk,par.W{p},Rd{p},par.W{p},1,par.nzlistAy{p});\n tmp2 = AXfun(pblk,At(p,:),par.permA(p,:),EinvRc(p));\n hRd = hRd + tmp2;\n end\n tmp = spdiags(sigmu(p)./par.sv{p} -par.sv{p},0,n,n);\n EinvRc{p} = Prod3(pblk,par.G{p}',tmp-Rq,par.G{p},1);\n tmp2 = AXfun(pblk,At(p,:),par.permA(p,:),EinvRc(p));\n hEinvRc = hEinvRc + tmp2;\n end\nend\n%%\nrhs = rp + hRd - hEinvRc;\nrhs(m+1) = rhs(m+1) + (par.mu/par.tau - par.kap);\nif (corrector)\n rhs(m+1) = rhs(m+1) - par.dtau*par.dkap/par.tau;\nend\n%%*******************************************************************\n", "meta": {"author": "zarathustr", "repo": "LibQPEP", "sha": "99e5c23e746ace0bac4a86742c31db6fcf7297ba", "save_path": "github-repos/MATLAB/zarathustr-LibQPEP", "path": "github-repos/MATLAB/zarathustr-LibQPEP/LibQPEP-99e5c23e746ace0bac4a86742c31db6fcf7297ba/MATLAB/sdpt3/HSDSolver/HSDNTrhsfun.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7248702880639791, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.33981239656425855}} {"text": "function lambda = parlett_eigenvalues ( )\n\n%*****************************************************************************80\n%\n%% PARLETT_EIGENVALUES returns the eigenvalues of the PARLETT matrix.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 17 October 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Output, real LAMBDA(100,1), the eigenvalues.\n%\n n = 100;\n lambda = zeros ( n, 1 );\n\n for i = 1 : n\n lambda(i,1) = i;\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_mat/parlett_eigenvalues.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.33971055063006994}} {"text": "function tapas_hgf_categorical_plotTraj(r)\n% Plots trajectories estimated by fitModel for the hgf_categorical perceptual model\n% Usage: est = tapas_fitModel(responses, inputs); tapas_hgf_plotTraj(est);\n%\n% --------------------------------------------------------------------------------------------------\n% Copyright (C) 2012-2013 Christoph Mathys, TNU, UZH & ETHZ\n%\n% This file is part of the HGF toolbox, which is released under the terms of the GNU General Public\n% Licence (GPL), version 3. You can redistribute it and/or modify it under the terms of the GPL\n% (either version 3 or, at your option, any later version). For further details, see the file\n% COPYING or .\n\n% Check whether we have a configuration structure\nif ~isfield(r,'c_prc')\n error('tapas:hgf:ConfigRequired', 'Configuration required: before calling tapas_hgf_categorical_plotTraj, tapas_hgf_categorical_config has to be called.');\nend\n\n% Number of outcomes\nno = r.c_prc.n_outcomes;\n\n% Define colors\ncolors = [1 0 0; 0.67 0 1; 0 0.67 1; 0.67 1 0];\n\n% Set up display\nscrsz = get(0,'screenSize');\nouterpos = [0.2*scrsz(3),0.2*scrsz(4),0.8*scrsz(3),0.8*scrsz(4)];\nfigure(...\n 'OuterPosition', outerpos,...\n 'Name','HGF trajectories');\n\n% Number of trials\nt = size(r.u,1);\n\n% Optional plotting of standard deviations (true or false)\nplotsd2 = true;\nplotsd3 = true;\n\n% Subplots\nsubplot(3,1,1);\n\nif plotsd3 == true\n upper3prior = r.p_prc.mu3_0 +sqrt(r.p_prc.sa3_0);\n lower3prior = r.p_prc.mu3_0 -sqrt(r.p_prc.sa3_0);\n upper3 = [upper3prior; r.traj.mu(:,3)+sqrt(r.traj.sa(:,3))];\n lower3 = [lower3prior; r.traj.mu(:,3)-sqrt(r.traj.sa(:,3))];\n \n plot(0, upper3prior, 'ob', 'LineWidth', 1);\n hold all;\n plot(0, lower3prior, 'ob', 'LineWidth', 1);\n fill([0:t, fliplr(0:t)], [(upper3)', fliplr((lower3)')], ...\n 'b', 'EdgeAlpha', 0, 'FaceAlpha', 0.15);\nend\nplot(0:t, [r.p_prc.mu3_0; r.traj.mu(:,3)], 'b', 'LineWidth', 2);\nhold all;\nplot(0, r.p_prc.mu3_0, 'ob', 'LineWidth', 2); % prior\nxlim([0 t]);\ntitle('Posterior expectation \\mu_3 of log-volatility of tendency x_3', 'FontWeight', 'bold');\nxlabel('Trial number');\nylabel('\\mu_3');\n\nsubplot(3,1,2);\nif plotsd2 == true\n for j=1:no\n upper2prior = r.p_prc.mu2_0(j) +sqrt(r.p_prc.sa2_0(j));\n lower2prior = r.p_prc.mu2_0(j) -sqrt(r.p_prc.sa2_0(j));\n upper2 = [upper2prior; r.traj.mu(:,2,j)+sqrt(r.traj.sa(:,2,j))];\n lower2 = [lower2prior; r.traj.mu(:,2,j)-sqrt(r.traj.sa(:,2,j))];\n \n plot(0, upper2prior, 'o', 'Color', colors(j,:), 'LineWidth', 1);\n hold all;\n plot(0, lower2prior, 'o', 'Color', colors(j,:), 'LineWidth', 1);\n fill([0:t, fliplr(0:t)], [(upper2)', fliplr((lower2)')], ...\n colors(j,:), 'EdgeAlpha', 0, 'FaceAlpha', 0.15);\n end\nend\nfor j=1:no\n plot(0:t, [r.p_prc.mu2_0(j); r.traj.mu(:,2,j)], 'Color', colors(j,:), 'LineWidth', 2);\n hold all;\n plot(0, r.p_prc.mu2_0(j), 'o', 'Color', colors(j,:), 'LineWidth', 2); % prior\nend\nxlim([0 t]);\ntitle('Posterior expectations \\mu_2 of tendencies x_2', 'FontWeight', 'bold');\nxlabel({'Trial number', ' '}); % A hack to get the relative subplot sizes right\nylabel('\\mu_2');\nhold off;\n\nsubplot(3,1,3);\nfor j=1:no\n plot(0:t, [tapas_sgm(r.p_prc.mu2_0(j), 1); tapas_sgm(r.traj.mu(:,2,j), 1)], 'Color', colors(j,:), 'LineWidth', 2);\n hold all;\n plot(0, tapas_sgm(r.p_prc.mu2_0(j), 1), 'o', 'Color', colors(j,:), 'LineWidth', 2); % prior\nend\nu = r.u(:,1);\nfor j=1:no\n plot(find(u==j), -0.08*ones([1 length(find(u==j))]), '.', 'Color', colors(j,:)); % inputs\nend\nif ~isempty(find(strcmp(fieldnames(r),'y'))) && ~isempty(r.y)\n y = r.y(:,1);\n if ~isempty(find(strcmp(fieldnames(r),'irr')))\n y(r.irr) = NaN; % weed out irregular responses\n plot(r.irr, 1.08.*ones([1 length(r.irr)]), 'x', 'Color', [1 0.7 0], 'Markersize', 11, 'LineWidth', 2); % irregular responses\n end\n for j=1:no\n plot(find(y==j), 1.08*ones([1 length(find(y==j))]), '.', 'Color', colors(j,:)); % responses\n end\n title(['Response y (top dot row), input u (bottom dot row), and posterior probability of outcomes s(\\mu_2) for \\kappa=', ...\n num2str(r.p_prc.ka), ', \\omega=', num2str(r.p_prc.om), ', \\vartheta=', num2str(r.p_prc.th)], ...\n 'FontWeight', 'bold');\n ylabel('y, u, s(\\mu_2)');\n axis([0 t -0.1 1.15]);\nelse\n title(['Input u (bottom dot row) and posterior probability of outcomes s(\\mu_2) for \\kappa=', ...\n num2str(r.p_prc.ka), ', \\omega=', num2str(r.p_prc.om), ', \\vartheta=', num2str(r.p_prc.th)], ...\n 'FontWeight', 'bold');\n ylabel('u, s(\\mu_2)');\n axis([0 t -0.1 1.1]);\nend\nplot(1:t, 0.5, 'k');\nxlabel('Trial number');\nhold off;\n", "meta": {"author": "translationalneuromodeling", "repo": "tapas", "sha": "604c56843c15411f5bd80190f81d845ac57d8592", "save_path": "github-repos/MATLAB/translationalneuromodeling-tapas", "path": "github-repos/MATLAB/translationalneuromodeling-tapas/tapas-604c56843c15411f5bd80190f81d845ac57d8592/HGF/tapas_hgf_categorical_plotTraj.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.33951628505760295}} {"text": "function [S, mets, badRxns, reversible]=constructS(equations,mets,rxns)\n% constructS\n% Constructs a stoichiometric matrix from a cell array of equations\n%\n% equations cell array of equations on the form 'A + 2 B <=> 3 C',\n% where <=> indicates reversible and => irreversible reactions\n% mets cell array of metabolites. All metabolites in the equations\n% must be present in the list (opt, default generated from\n% the equations)\n% rxns cell array of reaction ids. This is only used for printing\n% reaction ids instead of equations in warnings/errors (opt,\n% default [])\n%\n% S the resulting stoichiometric matrix mets cell array with\n% metabolites that corresponds to the order in the S matrix\n% badRxns boolean vector with the reactions that have one or more\n% metabolites as both substrate and product. An example would\n% be the phosphotransferase ATP + ADP <=> ADP + ATP. In the\n% stoichiometric matrix this equals to an empty reaction\n% which can be problematic\n% reversible boolean vector with true if the equation is reversible\n%\n% Usage: [S, mets, badRxns, reversible]=constructS(equations,mets)\n\nequations=convertCharArray(equations);\nswitch nargin\n case 2\n mets=convertCharArray(mets);\n case 3\n rxns=convertCharArray(rxns);\nend\n\nbadRxns=false(numel(equations),1);\n\n%Check that no equations are too short to have reversibility data\nI=cellfun(@numel,equations);\nI=find(I<4,1);\nif any(I)\n if isempty(rxns)\n EM=['The following equation does not have reversibility data: ' equations{I} ];\n dispEM(EM);\n else\n EM=['The reaction ' rxns{I} ' does not have reversibility data'];\n dispEM(EM);\n end\nend\n\n%Makes life a little easier\nequations=strtrim(equations);\nequations=fixEquations(equations);\n\nif nargin<2\n mets=parseRxnEqu(equations);\nend\nif nargin<3\n rxns=[];\nend\n\n%Get which reactions are reversible\nreversible=cellfun(@any,strfind(equations,' <=> '));\n\n%Make them all reversible. This is not all that neat, but nevermind\nequations=strrep(equations,' => ',' <=> ');\n\n%Replace the the plus signs with some weird character that will be used for\n%parsing\nequations=strrep(equations,' + ', '€');\n\n%Generate the stoichiometric matrix\nS=zeros(numel(mets),numel(equations));\n\n%Keep track of coefficients to be added to S-matrix\nmetsToS = cell(100000,1);\nrxnsToS = zeros(100000,1);\ncoefToS = zeros(100000,1);\nnewEntry = 1;\n%Loop through the equations and add the info to the S matrix\nfor i=1:numel(equations)\n %Start by finding the position of the (=> or <=>)\n arrowIndex=strfind(equations{i},' <=> ');\n \n if numel(arrowIndex)~=1\n if isempty(rxns)\n EM=['The following equation does not have reversibility data: ' equations{i} ];\n dispEM(EM);\n else\n EM=['The reaction ' rxns{i} ' does not have reversibility data'];\n dispEM(EM);\n end\n end\n \n reactants=regexp(equations{i}(1:arrowIndex-1),'€','split');\n products=regexp(equations{i}(arrowIndex+5:end),'€','split');\n \n %If the splitting character is at the end (if exchange rxns), then an\n %empty string will exist together with the real ones. Remove it\n reactants(cellfun(@isempty,reactants))=[];\n products(cellfun(@isempty,products))=[];\n \n %A vector where an element is -1 is the corresponding metabolite is a\n %reactant and 1 if it's a product\n multiplyWith=[ones(numel(reactants),1)*-1; ones(numel(products),1)];\n \n metabolites=strtrim([reactants products]);\n \n %Now loop through the reactants and see if the metabolite has a\n %coefficient (it will look as 'number name')\n for j=1:numel(metabolites)\n space=strfind(metabolites{j},' ');\n \n if isempty(space)\n %No coefficient\n coeff=1;\n name=metabolites{j};\n else\n coeff=str2double(metabolites{j}(1:space(1)));\n \n %If it was not a coefficiant\n if isnan(coeff)\n coeff=1;\n name=strtrim(metabolites{j});\n else\n name=strtrim(metabolites{j}(space+1:end));\n end\n end\n \n %Find the name in the mets list [a b]=ismember(name,mets);\n metsToS{newEntry}=name;\n rxnsToS(newEntry)=i;\n coefToS(newEntry)=coeff*multiplyWith(j);\n newEntry=newEntry+1;\n end\nend\n%Remove unused fields\nmetsToS(newEntry:end)=[];\nrxnsToS(newEntry:end)=[];\ncoefToS(newEntry:end)=[];\n\n%Match to mets array\n[metsPresent,metsLoc]=ismember(metsToS,mets);\n\n%Find badRxns\n[~,I]=unique([rxnsToS,metsLoc],'rows','stable');\nx=1:length(rxnsToS);\nx(I)=[];\nx=unique(rxnsToS(x));\nbadRxns(x)=true;\n\nif any(~metsPresent)\n if isempty(rxns)\n error(['Could not find the following metabolites in the metabolite list: ',...\n strjoin(unique(metsToS(~metsPresent)),', ')],'')\n else\n missingMet = find(~metsPresent);\n missingMet = char(strcat(metsToS(missingMet),' (reaction:',rxns(rxnsToS(missingMet)),')\\n'));\n error(['Could not find the following metabolites (reaction indicated) in the metabolite list: \\n' ...\n missingMet '%s'],'');\n end\nend\nlinearIndices=sub2ind(size(S),metsLoc,rxnsToS);\nS(linearIndices)=coefToS;\nS=sparse(S);\nend\n\nfunction equ=fixEquations(equ)\n%If the equation starts with \"=>\" or \"<=>\" then add a space again. This is\n%an alternative way to represent uptake reactions. The opposite way for\n%producing reactions\nequ=equ(:);\nfor i=1:numel(equ)\n if strcmp(equ{i}(1:2),'=>') || strcmp(equ{i}(1:3),'<=>')\n equ{i}=[' ' equ{i}];\n else\n if strcmp(equ{i}(end-1:end),'=>') || strcmp(equ{i}(end-2:end),'<=>')\n equ{i}=[equ{i} ' '];\n end\n end\nend\nend\n", "meta": {"author": "SysBioChalmers", "repo": "RAVEN", "sha": "cf4d3e0be954fde96a1a09ae3353dd2ee46552ed", "save_path": "github-repos/MATLAB/SysBioChalmers-RAVEN", "path": "github-repos/MATLAB/SysBioChalmers-RAVEN/RAVEN-cf4d3e0be954fde96a1a09ae3353dd2ee46552ed/core/constructS.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.658417487156366, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.3394931692381252}} {"text": "function [media,density,medname,xbound,ybound,zbound] = dicomrt_readegs4phant(patient_position,filename)\n% dicomrt_readegs4phant(patient_position,filename)\n%\n% Read a ct phantom which comply to BEAM/DOSXYZ file format\n% Return media matrix and density matrix.\n%\n% patient_position is a code which correspond to one of the supported\n% patient position cases\n% Filename is an character string which contain the name of the egs4phantom file (no extension).\n%\n% Example:\n%\n% [A,B,medname]=dicomrt_readegs4phant(1,'demo')\n%\n% will store in A the medium number and in B the density read from the egs4phantom demo.egs4phant;\n% Materials name are stored in medname. This information is required when converting \n% dose2medium <-> dose2water.\n%\n% See also dicomrt_ctcreate, dicomrt_getPatientPosition\n%\n% Copyright (C) 2002 Emiliano Spezi (emiliano.spezi@physics.org) \n\nfilename=[filename,'.egs4phant'];\nfid=fopen(filename);\nnummedia = fscanf(fid,'%i');\nmedname=cell(nummedia,1);\n\nfor i=1:nummedia\n medname{i,1}=fgetl(fid);\nend\n\nfor i=1:nummedia\n estepe(i,:) = fscanf(fid,'%f',1);\nend\n\nglobal xnum;\nglobal ynum;\nglobal znum;\n\nxnum = fscanf(fid,'%i',1);\nynum = fscanf(fid,'%i',1);\nznum = fscanf(fid,'%i',1);\n\nxbound = fscanf(fid,'%f',xnum+1);\nybound = fscanf(fid,'%f',ynum+1);\nzbound = fscanf(fid,'%f',znum+1);\n\nxbound = dicomrt_mmdigit(xbound,7,10,'fix');\nybound = dicomrt_mmdigit(ybound,7,10,'fix');\nzbound = dicomrt_mmdigit(zbound,7,10,'fix');\n\nif patient_position == 1\n % 1st case: supported Patient Position is HFS\n %load the media matrix\n media=[];\n for k=1:znum\n media_temp = fscanf(fid,'%1i',[xnum, ynum]);\n media(:,:,k) = media_temp';\n line = fgets(fid);\n end\n % load the density matrix\n for k = 1:znum \n density_temp = fscanf(fid,'%f',[xnum, ynum]);\n density(:,:,k) = density_temp';\n end\nelseif patient_position == 2\n % 2nd case: supported Patient Position is FFS \n %load the media matrix\n media=[];\n for k=1:znum\n media_temp = fscanf(fid,'%1i',[xnum, ynum]);\n media(:,:,k) = media_temp';\n line = fgets(fid);\n end\n % load the density matrix\n for k = 1:znum \n density_temp = fscanf(fid,'%f',[xnum, ynum]);\n density(:,:,k) = density_temp';\n end\nend\nfclose(fid);", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/CERR_core/Importing/dicomrt-toolbox-v2/mctp/utils/dicomrt_readegs4phant.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.689305616785446, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.3392680464675018}} {"text": "function Q = cost(V,t,tc,Run)\n%\n% Least-squares cost function for the IL model\n%\n% INPUT:\n% Run = stick function\n% tc = time course\n% t = vector of time points\n% V = parameters\n%\n% OUTPUT:\n% Q = cost\n%\n% By Martin Lindquist and Tor Wager\n% Edited 12/12/06\n%\n\nlen = length(Run);\n\nh1 = Get_Logit(V(1:7),t); % Get IL model corresponding to parameters V\nyhat = conv(Run, h1); % Convolve IL model with stick function\nyhat = yhat(1:len);\n\nQ = sum((yhat-tc).^2); % Calculate cost function\n\nreturn", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/HRF_Est_Toolbox2/Old_stuff/cost.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7057850278370111, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.33911465716113237}} {"text": "function [w]=iwtt(v,wtt_transform)\n%Inverse WTT transform with previously computed filters\n% W=IWTT(V,WTT_TRANSFORM) computes the inverse WTT tranformation of a \n% given tensor with filters, stored in the WTT_TRANSFORM structure.\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\nu=wtt_transform.u;\nr=wtt_transform.rks;\nsz=wtt_transform.sz;\nw=iwtt_loc(v,u,r,sz);\nreturn\nend\nfunction [w]=iwtt_loc(v,u,r,sz)\n%[W]=IWTT(V,U,R,SZ)\n%Applies Inverse WTT transform to vector V with linear filters U \n%and ranks R\n%SZ is optional\nif ( nargin == 1 )\n sz=size(v);% d=numel(sz);\nelse\n % d=numel(sz);\nend\n%Apply one transform back\n N=numel(v);\n v=reshape(v,[r(1)*sz(1),N/(r(1)*sz(1))]);\nif ( numel(u) == 1 )\n w=u{1}*v;\n w=reshape(w,[r(1),N/(r(1))]);\nelse\n %Simplest one is recursion\n w=v;\n w0=v(1:r(2),:);\n unew=u(2:numel(u)); rnew=r(2:numel(r)); sznew=[sz(2),sz(3:numel(sz))];\n w0=iwtt_loc(w0,unew,rnew,sznew);\n w(1:r(2),:)=w0;\n m=size(u{1},1);\n w=reshape(w,[m,N/m]);\n w=u{1}*w;\n w=reshape(w,[r(1),N/r(1)]);\nend\n return\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/exp/iwtt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6113819874558603, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.33899325485308096}} {"text": "function [pc, fvecm2, p, c] = gp_predcm(gp,x,y,varargin)\n%GP_PREDCM Corrections for latent marginal posterior\n%\n% Description\n% [PC, FVEC, P, C] = GP_PREDCM(GP, X, Y, XT, OPTIONS) Evaluates the\n% corrected marginal posterior of latent variable at given indices\n% of XT or X if XT is empty or not given. Marginal posterior\n% corrections are evaluated in 9 Gauss-Hermite points, after which\n% piecewise cubic Hermite interpolation is used interpolate\n% logarithm of the correction terms to a finer grid. Returns tilted\n% distribution P if XT is empty or equal to X, otherwise predictive\n% distribution, corrected predictive/tilted distribution PC and\n% correction terms C, where PC_i = P_i*C_i for every grid point i\n% in grid FVEC. FVEC is linearly spaced grid from predictive\n% distribution between mean minus/plus 4 standard deviations\n%\n%\n% OPTIONS is optional parameter-value pair\n% z - optional observed quantity in triplet (x_i,y_i,z_i)\n% Some likelihoods may use this. For example, in case of\n% Poisson likelihood we have z_i=E_i, that is, expected value\n% for ith case.\n% ind - Index vector or scalar defining the indices of data\n% points at which the marginal posterior corrections are\n% done. Default = 1.\n% fcorr - Method used for evaluating correction terms C. Possible\n% methods are 'fact' (default) for EP and either 'fact'\n% or 'cm2' (default) for Laplace. If method is 'on',\n% the default methods are used.\n% ng - Number of grid points evaluated from the spline. Default is 50.\n%\n% Reference\n% Cseke & Heskes (2011). Approximate Marginals in Latent Gaussian\n% Models. Journal of Machine Learning Research 12 (2011), 417-454\n%\n% See also\n% DEMO_IMPROVEDMARGINALS\n%\n% Copyright (c) 2011,2013 Ville Tolvanen\n\n% This software is distributed under the GNU General Public\n% License (version 3 or later); please refer to the file\n% License.txt, included with the software, for details.\n\nip=inputParser;\nip.addRequired('gp',@isstruct);\nip.addRequired('x', @(x) ~isempty(x) && isreal(x) && all(isfinite(x(:))))\nip.addRequired('y', @(x) ~isempty(x) && isreal(x) && all(isfinite(x(:))))\n%ip.addRequired('fvec', @(x) ~isempty(x) && isreal(x) && all(isfinite(x(:))))\nip.addOptional('xt', [], @(x) isreal(x) && all(isfinite(x(:))))\nip.addParamValue('z', [], @(x) isreal(x) && all(isfinite(x(:))))\nip.addParamValue('ind', 1, @(x) isreal(x) && all(isfinite(x(:))))\nip.addParamValue('ng', 50, @(x) isreal(x) && all(isfinite(x(:))) && x > 1)\nip.addParamValue('fcorr', 'on', @(x) ismember(x, {'fact', 'cm2', 'on','lr'}))\nip.addParamValue('tstind', [], @(x) isempty(x) || iscell(x) ||...\n (isvector(x) && isreal(x) && all(isfinite(x)&x>0)))\nif rem(size(varargin,2), 2) == 0\n ip.parse(gp, x, y, [],varargin{:});\nelse\n ip.parse(gp, x, y, varargin{:});\nend\ntstind = ip.Results.tstind;\nz = ip.Results.z;\nind = ip.Results.ind;\nxt = ip.Results.xt;\nng = ip.Results.ng;\npredictive=false;\ngplik=gp.lik;\nn=size(x,1);\n[Ef, Covf] = gp_jpred(gp,x,y,x, 'z', z, 'tstind', 1:n);\nCovf=full(Covf);\nif ismember('fcorr', ip.UsingDefaults)\n if isequal(gp.latent_method, 'Laplace')\n % Default for Laplace\n fcorr='cm2';\n else\n % Default for EP\n fcorr='fact';\n end\nelse\n fcorr=ip.Results.fcorr;\nend\nind=ind(:);\nif ~isempty(xt) && ~isequal(xt, x)\n % Predictive equations if given xt, mind that if xt(ind) is in training\n % input x, predictive equations might not work correctly.\n predictive = true;\n [Ef2, Varf2]=gp_pred(gp,x,y,xt,'z',z,'tstind',tstind);\n% [Ef2, Covf2] = gp_jpred(gp,x,y,xt,'z',z, 'tstind', tstind);\n% Covf2=full(Covf2);\nend\nnin = 11;\nfvecm=zeros(nin,length(ind));\nfvecm2=zeros(ng,length(ind));\nfor i1=1:length(ind)\n i2=ind(i1);\n % Form evaluation points for spline formation & grid points to be\n % evaluated from the spline\n minf = 6;\n maxf = 6;\n if ~predictive\n fvecm(:,i1)=Ef(i2)+[-3.668 -2.783 -2.026 -1.326 -0.657 0 0.657 1.326 2.026 2.783 3.668].*sqrt(Covf(i2,i2));\n% fvecm(:,i1)=Ef(i2)+[-3.191 -2.267 -1.469 -0.724 0 0.724 1.469 2.267 3.191].*sqrt(Covf(i2,i2));\n fvecm2(:,i1)=linspace(Ef(i2)-minf.*sqrt(Covf(i2,i2)), Ef(i2)+maxf.*sqrt(Covf(i2,i2)),ng)';\n else\n fvecm(:,i1)=Ef2(i2)+[-3.668 -2.783 -2.026 -1.326 -0.657 0 0.657 1.326 2.026 2.783 3.668].*sqrt(Varf2(i2));\n% fvecm(:,i1)=Ef2(i2)+[-3.191 -2.267 -1.469 -0.724 0 0.724 1.469 2.267 3.191].*sqrt(Covf2(i2,i2));\n fvecm2(:,i1)=linspace(Ef2(i2)-minf.*sqrt(Varf2(i2)), Ef2(i2)+maxf.*sqrt(Varf2(i2)),ng)';\n end\nend\nlc = zeros(nin, length(ind));\npc = zeros(ng, size(ind,1)); lp = zeros(ng,size(ind,1)); c = zeros(ng,size(ind,1));\nlp2 = zeros(nin,size(ind,1)); p = zeros(ng,size(ind,1));\n\nswitch gp.latent_method\n case 'EP'\n \n if isequal(fcorr, 'lr')\n [Efloo,Varfloo]=gpep_loopred(gp,x,y,'z',z);\n end\n \n switch fcorr\n case {'fact', 'lr'}\n [tmp, tmp, tmp, param] = gpep_e(gp_pak(gp), gp, x,y,'z',z);\n [tautilde, nutilde, muvec_i, sigm2vec_i] = ...\n deal(param.tautilde, param.nutilde, param.muvec_i, param.sigm2vec_i);\n \n \n % Compute tilted moments\n logM02 = gp.lik.fh.tiltedMoments(gp.lik, y, 1:n, sigm2vec_i, muvec_i, z);\n \n if predictive\n K_ff = gp_trcov(gp, x);\n end\n \n % Loop through grid indices\n for i1=1:size(ind,1)\n fvec = fvecm(:,i1);\n if ~predictive\n inds=[1:(ind(i1)-1) (ind(i1)+1):n];\n cii = Covf(ind(i1),ind(i1));\n if isempty(z)\n z_ind = [];\n else\n z_ind = z(ind(i1));\n end\n \n % Here we keep track of normalizing constants so we dont have to\n % normalize distributions at any point.\n % Z_q = sqrt(2*pi*cii);\n% logM0 = gp.lik.fh.tiltedMoments(gp.lik, y, ind(i1), sigm2vec_i(ind(i1)), muvec_i(ind(i1)), z);\n% Z_p = exp(logM0)*sqrt(2*pi)*sqrt(sigm2vec_i(ind(i1))+1./tautilde(ind(i1)))*exp(0.5*(muvec_i(ind(i1))-nutilde(ind(i1))./tautilde(ind(i1))).^2/(sigm2vec_i(ind(i1))+1./tautilde(ind(i1))));\n \n % Function handle to marginal distribution without any fcorr parameters\n if isequal(fcorr, 'fact')\n cav = @(f) norm_lpdf(f,Ef(ind(i1)),sqrt(cii)) - norm_lpdf(f, nutilde(ind(i1))/tautilde(ind(i1)), 1/sqrt(tautilde(ind(i1))));\n else\n cav = @(f) norm_lpdf(f, Efloo(ind(i1)), sqrt(Varfloo(ind(i1))));\n end\n fh_p = @(f) (arrayfun(@(a) gplik.fh.ll(gplik, y(ind(i1)), a, z_ind), f)) + cav(f);\n else\n inds=1:n;\n cii = Varf2(ind(i1));\n fh_p = @(f) norm_lpdf(f,Ef2(ind(i1)),sqrt(cii));\n end\n \n % Loop through grid points\n for i=1:nin\n \n % Variance and mean for global Gaussian approximation conditioned on\n % other data grid points, q(x_j|x_i) or in predictive case, q(x_j,\n % x_*)\n if ~predictive\n cji = Covf(ind(i1),:);% cji(ind(i1)) = [];\n cjj = Covf;% cjj(ind(i1),:) = []; cjj(:,ind(i1)) = [];\n ci = diag(cjj)-(cji'*(1/cii)).*cji';\n mf = Ef; %mf(ind(i1)) = [];\n mu = mf+cji'./cii.*(fvec(i)-Ef(ind(i1)));\n else\n K_fstar = gp_cov(gp, x, xt(ind(i1),:));\n cjj = Covf;\n cji = (K_fstar'/K_ff)*cjj;\n ci = diag(cjj)-cji'.*(1/cii).*cji';\n mu = Ef+cji'./cii.*(fvec(i)-Ef2(ind(i1)));\n end\n % Loop through other points in x, exclude point to which current latent grid\n % corresponds to (if not predictive).\n lZtilde=logM02 + log(sqrt(2*pi)) + log(sqrt(sigm2vec_i+1./tautilde)) + 0.5*(muvec_i-nutilde./tautilde).^2./(sigm2vec_i+1./tautilde);\n m1 = nutilde./tautilde;\n s1 = 1./sqrt(tautilde);\n m2 = mu;\n s2 = sqrt(ci);\n \n s = sqrt(1./(1./s2.^2 - 1./s1.^2));\n m = (m2./s2.^2 - m1./s1.^2).*s.^2;\n lZ = log(s1) - log(s2) - 1./(2*(-s1.^2+s2.^2)).*(m1-m2).^2 +log(sqrt(2*pi*s.^2));\n lc_ii = lZ(inds) - lZtilde(inds) + gp.lik.fh.tiltedMoments(gplik, y(inds), 1:length(inds), s(inds).^2, m(inds), z);\n lc(i,i1) = sum(lc_ii);\n %p(i,i1) = fh_p(fvec(i,i1));\n \n end\n lp(:,i1) = fh_p(fvecm2(:,i1));\n lp2(:,i1) = fh_p(fvecm(:,i1));\n lp(:,i1) = lp(:,i1)-max(lp(:,i1));\n lp2(:,i1) = lp2(:,i1)-max(lp2(:,i1));\n end\n otherwise\n error('Invalid method for EP, use fact');\n end\n case 'Laplace'\n \n [tmp, tmp, tmp, param] = gpla_e(gp_pak(gp), gp, x,y,'z',z);\n f_mode = param.f;\n if ~isempty(z)\n ll = arrayfun(@(f,yy, zz) gplik.fh.ll(gplik, yy, f, zz), f_mode, y, z);\n else\n ll = arrayfun(@(f,yy) gplik.fh.ll(gplik, yy, f, z), f_mode, y);\n end\n llg = gplik.fh.llg(gplik, y, f_mode, 'latent', z);\n llg2 = gplik.fh.llg2(gplik, y, f_mode, 'latent', z);\n K_ff = gp_trcov(gp, x);\n if isequal(fcorr, 'lr')\n [Efloo,Varfloo]=gpla_loopred(gp,x,y,'z',z,'method','lrs');\n end\n \n switch fcorr\n case 'fact'\n % Loop through grid indices\n for i1=1:size(ind,1)\n fvec = fvecm(:,i1);\n if ~predictive\n cii = Covf(ind(i1),ind(i1));\n if isempty(z)\n z_ind = [];\n else\n z_ind = z(ind(i1));\n end\n \n % Function handle to marginal distribution without any fcorr parameters\n t_tilde = @(f) (ll(ind(i1)) + (f-f_mode(ind(i1)))*llg(ind(i1)) + 0.5*(f-f_mode(ind(i1))).^2*llg2(ind(i1)));\n fh_p = @(f) (arrayfun(@(a) gplik.fh.ll(gplik, y(ind(i1)), a, z_ind), f)) - t_tilde(f) + norm_lpdf(f,Ef(ind(i1)),sqrt(cii));\n else\n cii = Varf2(ind(i1));\n fh_p = @(f) norm_lpdf(f,Ef2(ind(i1)),sqrt(cii));\n end\n \n if ~predictive\n cji = Covf(ind(i1),:); %cji(ind(i1)) = [];\n cjj = Covf; %cjj(ind(i1),:) = []; cjj(:,ind(i1)) = [];\n ci = diag(cjj)-(cji'*(1/cii)).*cji';\n mf = Ef; %mf(ind(i1)) = [];\n inds=[1:(ind(i1)-1) (ind(i1)+1):n];\n else\n K_fstar = gp_cov(gp, x, xt(ind(i1),:));\n cjj = Covf;\n cji = (K_fstar'/K_ff)*cjj;\n ci = diag(cjj)-cji'.*(1/cii).*cji';\n inds=1:n;\n end\n % Loop through grid points\n for i=1:nin\n \n % Variance and mean for global gaussian approximation conditioned on\n % other data grid poins, q(x_j|x_i) or in predictive case, q(x_j,\n % x_*)\n if ~predictive\n mu = mf+cji'./cii.*(fvec(i)-Ef(ind(i1)));\n else\n mu = Ef+cji'./cii.*(fvec(i)-Ef2(ind(i1)));\n end\n m1 = (f_mode-llg./llg2);\n s1 = sqrt(-1./llg2);\n lC1 = ll+llg2.*f_mode.^2-llg2.*m1.^2 - llg.*f_mode;\n m2 = mu;\n s2 = sqrt(ci);\n lC2 = log(1./sqrt(2*pi*s2.^2));\n \n s = sqrt(1./(1./s2.^2 - 1./s1.^2));\n m = (m2./s2.^2 - m1./s1.^2).*s.^2;\n \n lZ = lC1 - lC2 - 1./(2*(-s1.^2+s2.^2)).*(m1-m2).^2 + log(sqrt(2*pi*s.^2));\n lc_ii = lZ(inds) + gp.lik.fh.tiltedMoments(gplik, y(inds), 1:length(inds), s(inds).^2, m(inds), z);\n \n %c(i,i1) = prod(c_ii);\n lc(i,i1) = sum(lc_ii);\n %p(i,i1) = fh_p(fvec(i,i1));\n \n end\n lp(:,i1) = fh_p(fvecm2(:,i1));\n lp2(:,i1) = fh_p(fvecm(:,i1));\n lp(:,i1) = lp(:,i1)-max(lp(:,i1));\n lp2(:,i1) = lp2(:,i1)-max(lp2(:,i1));\n end\n \n case {'cm2', 'lr'}\n % Loop through grid indices\n for i1=1:size(ind,1)\n fvec = fvecm(:,i1);\n if ~predictive\n cii = Covf(ind(i1),ind(i1));\n if isempty(z)\n z_ind = [];\n else\n z_ind = z(ind(i1));\n end\n \n % Function handle to marginal distribution without any fcorr parameters\n if isequal(fcorr, 'cm2')\n% t_tilde(f) = @(f) (ll(ind(i1)) + (f-f_mode(ind(i1)))*llg(ind(i1)) + 0.5*(f-f_mode(ind(i1))).^2*llg2(ind(i1)));\n cav = @(f) norm_lpdf(f,Ef(ind(i1)),sqrt(cii)) - (ll(ind(i1)) + (f-f_mode(ind(i1)))*llg(ind(i1)) + 0.5*(f-f_mode(ind(i1))).^2*llg2(ind(i1)));\n else\n cav = @(f) norm_lpdf(f, Efloo(ind(i1)), sqrt(Varfloo(ind(i1))));\n end\n fh_p = @(f) arrayfun(@(a) gplik.fh.ll(gplik, y(ind(i1)), a, z_ind), f) + cav(f);\n% fh_p = @(f) (arrayfun(@(a) gplik.fh.ll(gplik, y(ind(i1)), a, z_ind), f)) - t_tilde(f) + norm_lpdf(f,Ef(ind(i1)),sqrt(cii));\n else\n cii = Varf2(ind(i1));\n fh_p = @(f) norm_lpdf(f,Ef2(ind(i1)),sqrt(cii));\n end\n \n if ~predictive\n cji = Covf(ind(i1),:);\n cji(ind(i1)) = [];\n inds=[1:(ind(i1)-1) (ind(i1)+1):n];\n else\n K_fstar = gp_cov(gp, x, xt(ind(i1),:));\n cji = (K_fstar'/K_ff)*Covf;\n inds=1:n;\n end\n mf = Ef(inds);\n cjj = Covf(inds,inds);\n y_tmp = y(inds);\n ci = cjj - cji'*(1/cii)*cji;\n f_mode_tmp=f_mode(inds);\n llg2_mode=diag(llg2(inds));\n llg_mode=llg(inds);\n ll_mode=sum(ll(inds));\n \n lnZ0 = -1/cii - ll_mode + 0.5*log(cii);\n icW = -eye(size(ci))/ci - llg2_mode;\n % Loop through grid points\n for i=1:nin\n \n if isempty(z)\n z_tmp = [];\n else\n z_tmp = z(inds);\n end\n % Compute conditional covariance matrices and mean vector\n if ~predictive\n mu = mf+cji'./cii.*(fvec(i)-Ef(ind(i1)));\n else\n mu = mf+cji'./cii.*(fvec(i)-Ef2(ind(i1)));\n end\n W = -diag(gplik.fh.llg2(gplik, y_tmp, mu, 'latent', z_tmp));\n deriv = gplik.fh.llg(gplik, y_tmp, mu, 'latent', z_tmp);\n logll = gplik.fh.ll(gplik,y_tmp, mu, z_tmp);\n \n % Computation of correction term by integrating the second order Taylor\n % expansion of product of global Gaussian approximation conditioned on latent\n % value x_i, q(x_-i|x_i), and t_-i(x_-i)/ttilde_-i(x_-i)\n mu1=mu-f_mode_tmp;\n lnZ = lnZ0 + logll - mu1'*llg_mode - 0.5*mu1'*llg2_mode*mu1;\n mu2=deriv-llg_mode-(mu1'*llg2_mode)';\n lnZ = lnZ - (0.5*mu2'/(icW - W))*mu2;\n lnZ = lnZ - evaluate_q(diag(W+llg2_mode), ci);\n \n lc(i,i1) = lnZ;\n %p(i,i1) = fh_p(fvec(i,i1));\n \n end\n lp(:,i1) = fh_p(fvecm2(:,i1));\n lp2(:,i1) = fh_p(fvecm(:,i1));\n lp(:,i1) = lp(:,i1)-max(lp(:,i1));\n lp2(:,i1) = lp2(:,i1)-max(lp2(:,i1)); \n \n end\n end\n \nend\n\nfor i1=1:length(ind)\n fvec = fvecm(:,i1);\n \n % Interpolate correction to these grid points \n % using piecewise cubic Hermite interpolation\n fvec2 = fvecm2(:,i1);\n lc(:,i1)=lc(:,i1)-lc(6,i1);\n \n % Check that the corrected distribution has decreasing tails\n lctmp=lc(:,i1);\n lptmp=(lp2(:,i1)+lc(:,i1));\n fvectmp=fvec;\n while lptmp(end)-lptmp(end-1) > 0\n lctmp=lctmp(1:end-1);\n lptmp=lptmp(1:end-1);\n fvectmp=fvectmp(1:end-1);\n end\n while lptmp(1)-lptmp(2) > 0\n lctmp=lctmp(2:end);\n lptmp=lptmp(2:end);\n fvectmp=fvectmp(2:end);\n end\n \n \n if (sum(isnan(lctmp))>0)\n warning('NaNs in moment computations')\n lctmp(isnan(lctmp))=0;\n end\n lc2(:,i1) = interp1(fvectmp, lctmp, fvec2, 'pchip');\n\n % Make correction\n pc(:,i1)=exp(lc2(:,i1) + lp(:,i1));\n \n if any(isnan(pc(:,i1))) || any(isinf(pc(:,i1))) \n warning('NaNs in moment computations')\n pc(isnan(pc(:,i1)),i1)=0;\n pc(isinf(pc(:,i1)),i1)=0;\n end\n if any(pc(:,i1)0); n1=length(ii1); W1=sqrt(tau_q(ii1));\nii2=find(tau_q<0); n2=length(ii2); W2=sqrt(abs(tau_q(ii2)));\n\nif ~isempty(ii1)\n % Cholesky decomposition for positive sites\n L1=(W1*W1').*K(ii1,ii1);\n L1(1:n1+1:end)=L1(1:n1+1:end)+1;\n L1=chol(L1);\n \nelse\n L1=1;\nend\n\nif ~isempty(ii2)\n % Cholesky decomposition for negative sites\n V=bsxfun(@times,K(ii2,ii1),W1')/L1;\n L2=(W2*W2').*(V*V'-K(ii2,ii2));\n L2(1:n2+1:end)=L2(1:n2+1:end)+1;\n \n L2=chol(L2);\n \nelse\n L2=1;\nend\n\n% log normalization\nlnZ_q = sum(log(diag(L1))) + sum(log(diag(L2)));\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/gp_predcm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.33870491540349534}} {"text": "function aps_powerlaw(start_step,end_step,save_path)\n% aps_powerlaw(start_step,end_step)\n% Program to compute the powerlaw tropsoheric delays. \n% STEP 1 = Estimate powerlaw delay and maximum height from sounding data\n% (when this is available), or use defaults or user set values\n% STEP 2 = Rotate dataset to minimize interpolation effects, Powerlaw scaling and interpolate to regular grid \n% STEP 3 = 1D/2D bandfiltering in the frequency domain and interpolate \n% back to local grid \n% STEP 4 = Spatial local estimation of the powerlaw scaling coefficient,\n% estimate final values from reliable frequency band, extrapolate \n% to all point locations and compute powerlaw tropospheric delay. \n% \n% To change the processing parameters use setparm_aps and getparm_aps\n%\n% **** when using this estimation method please cite:\n% D.P.S. Bekaert, A.J. Hooper and T.J. Wright, A spatially-variable power-law tropospheric correction\n% \t \t technique for InSAR data, JGR, doi:10.1029/2014JB011558 *****\n%\n% \n% Copyright (C) 2015 Bekaert David - University of Leeds\n% Email: eedpsb@leeds.ac.uk or davidbekaert.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 2 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License along\n% with this program; if not, write to the Free Software Foundation, Inc.,\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n%\n% By David Bekaert - University of Leeds\n%\n% modifications:\n% 04/2013 DB: Incorportate a parm_aps list with all the processing\n% options and variables.\n% 05/2013 DB: Include powerlaw coefficient sensitivity analysis\n% 05/2013 DB: Allow for an interferogram based estimation\n% 12/2013 DB: Put the flag of ifg correction on prior to powerlaw computation\n% 02/2014 DB: Integrate the plotting with the running of the sounding data\n% 02/2014 DB: Include a mountain ridge code, user interaction needed\n% 07/2014 DB: Have the option to plot the ridges\n% 07/2014 DB: Include a cropping option\n% 11/2014 DB: Fix bug and include paper reference\n% 03/2015 DB: Ask for the reference technique in step 5\n% 01/2016 DB: Fix ll.lonlat, ph_uw, hgt for non-stamps data, replace\n% save calls with aps_save, in case no -append flag is included\n% 02/2016 DB: Expand option 5 to plot with the unwrapped phase too.\n\n\nif nargin<3\n save_path = [pwd filesep]; \nend\n\ncurrdir = pwd;\t\t% current working directory\nplot_flag = 0;\nhydro =1;\nwet=1;\n\nfprintf(['\\n********************************************************************************************************** \\n','D.P.S. Bekaert, A.J. Hooper and T.J. Wright,\\n', 'A spatially-variable power-law tropospheric correction technique for InSAR data, JGR, doi:10.1029/2014JB011558\\n', '**********************************************************************************************************\\n\\n'])\n\n\n%% PART 1: Define the powerlaw coefficents, from the user or by using sounding data.\nsounding_data = getparm_aps('sounding_data',1);\nstamps_processed = getparm_aps('stamps_processed',1);\npowerlaw_ridge_constraint = getparm_aps('powerlaw_ridge_constraint',1);\n\nif strcmp(stamps_processed,'y')\n load psver\nelse\n psver = 2; \nend\n\n% file names of the output data\napsname = [save_path filesep 'tca' num2str(psver) '.mat'];\napssbname = [save_path filesep 'tca_sb' num2str(psver) '.mat'];\napsbandsname = [save_path filesep 'tca_bands' num2str(psver) '.mat'];\napsbandssbname = [save_path filesep 'tca_bands_sb' num2str(psver) '.mat'];\n\n\n% saving part of the data in a subfolder\nsave_path = [save_path filesep 'aps_p'];\nif exist(save_path,'dir')~=7\n mkdir(save_path);\nend\n\nif start_step==0 && strcmp(powerlaw_ridge_constraint,'y')\n \n mountain_ridge=[];\n if exist('tca_support.mat')==2\n load('tca_support.mat','powerlaw_ridges')\n if exist('powerlaw_ridges','var')==1\n mountain_ridge = powerlaw_ridges.mountain_ridge;\n end\n end\n if isempty(mountain_ridge)==1\n str_repr='y';\n str_vis = 'n';\n end\n \n % data has been computed before - reporcess? - visualize?\n if length(mountain_ridge)>0\n str_repr = '';\n while strcmpi(str_repr,'y')~=1 && strcmpi(str_repr,'n')~=1\n str_repr = input(['Ridges have been defined before, reprocess the data? [y/n] \\n'],'s');\n end\n \n % no reprocessing, do you want to visualize it?\n if strcmpi(str_repr,'n')\n str_vis = '';\n while strcmpi(str_vis,'y')~=1 && strcmpi(str_vis,'n')~=1\n str_vis = input(['Do you want to visualize the data? [y/n] \\n'],'s');\n end\n else\n str_vis = 'n';\n end\n \n end\n \n if strcmpi(str_repr,'y')\n [mountain_ridge] = aps_powerlaw_watershed;\n end\n if strcmpi(str_vis,'y')\n aps_support_plot(1);\n end\nend\n\nif start_step==1 && strcmp(sounding_data,'y')\n fprintf('\\n\\nStep 1: Powerlaw coefficients from the sounding data\\n')\n \n \n % getting the variables from the parm_aps file\n look_angle = getparm_aps('look_angle',1);\n lambda = getparm_aps('lambda',1);\n sounding_h0= getparm_aps('sounding_h0',1);\n sounding_h_alpha_thres= getparm_aps('sounding_h_alpha_thres',1);\n sounding_start_date= getparm_aps('sounding_start_date',1);\n sounding_end_date= getparm_aps('sounding_end_date',1);\n sounding_time_stamp= getparm_aps('sounding_time_stamp',1);\n sounding_dir= getparm_aps('sounding_dir',1);\n sounding_error_promp= getparm_aps('sounding_error_promp',1);\n sounding_sensitivity= getparm_aps('sounding_sensitivity',1);\n n_months = getparm_aps('sounding_months',1);\n time_stamp = getparm_aps('sounding_time_stamp',1);\n sounding_ifg_dates = getparm_aps('sounding_ifg_dates',1);\n \n %%% check if the file is already exisiting - ask if reprocessing is\n %%% needed, if not load exisitng file and plot results \n time_stamp_str = [];\n for k=1:size(time_stamp,1)\n if k>1\n time_stamp_str = [time_stamp_str '_' time_stamp(k,:)];\n else\n time_stamp_str = [time_stamp(k,:)];\n end\n end\n \n \n if strcmp(sounding_sensitivity,'y')\n fprintf('Sensitivity analyses of sounding data \\n\\n')\n \n % check first if the output file is already exisiting otherwize\n % ask if it needs to be reprocessed or visualised.\n \n if strcmp(sounding_ifg_dates,'y')\n fprintf('Coefficient estimation for each interferogram \\n\\n')\n if hydro==1 && wet==0\n save_name = [sounding_dir filesep 'Powerlaw' filesep 'Powerlaw_sensitivity_hydro_SAR_dates_1month_' time_stamp_str 'Hr.mat' ];\n elseif hydro==0 && wet==1\n save_name = [sounding_dir filesep 'Powerlaw' filesep 'Powerlaw_sensitivity_wet_SAR_dates_1month_' time_stamp_str 'Hr.mat' ];\n else\n save_name = [sounding_dir filesep 'Powerlaw' filesep 'Powerlaw_sensitivity_SAR_dates_1month_' time_stamp_str 'Hr.mat' ];\n end\n n_months =1;\n else\n fprintf('Coefficient estimation based on average \\n\\n')\n % putting the variables in the right set-up\n start_year = str2num(sounding_start_date(1:4));\n end_year = str2num(sounding_end_date(1:4));\n start_str = sounding_start_date(5:6);\n end_str = sounding_end_date(5:6);\n\n % the file name to be loaded\n if hydro==1 && wet==0\n save_name = [sounding_dir filesep 'Powerlaw' filesep 'Powerlaw_sensitivity_hydro_' num2str(n_months) 'month_' time_stamp_str 'Hr_' num2str(start_year) start_str '_' num2str(end_year) end_str '.mat' ];\n elseif hydro==0 && wet==1\n save_name = [sounding_dir filesep 'Powerlaw' filesep 'Powerlaw_sensitivity_wet_' num2str(n_months) 'month_' time_stamp_str 'Hr_' num2str(start_year) start_str '_' num2str(end_year) end_str '.mat' ];\n else\n save_name = [sounding_dir filesep 'Powerlaw' filesep 'Powerlaw_sensitivity_' num2str(n_months) 'month_' time_stamp_str 'Hr_' num2str(start_year) start_str '_' num2str(end_year) end_str '.mat' ];\n end\n end\n\n\n if exist(save_name,'file')==2\n str = '';\n while strcmpi(str,'y')~=1 && strcmpi(str,'n')~=1\n str = input(['This file already exist, do you want to re-process the data? [y/n] \\n'],'s');\n end\n \n if strcmpi(str,'y')\n sounding_powerlaw_sens(hydro,wet)\n else\n sounding_powerlaw_sens_display\n end\n else\n % estimate the coefficients for individual interferograms\n sounding_powerlaw_sens(hydro,wet)\n end\n \n \n else\n fprintf('Based on specified sounding period \\n\\n')\n % When having sounding data estimate the powerlaw and b coefficient\n [alpha_log_all,alpha,h0,n_soundings] = sounding;\n\n\n % setting the estimated parameters in the parameter file\n fprintf('Updating the parm_aps list \\n')\n setparm_aps('powerlaw_h0',h0)\n setparm_aps('powerlaw_alpha',alpha)\n \n % saving the data\n save([save_path filesep 'aps_p_step1.mat'],'alpha','h0','look_angle','lambda','sounding_h0','sounding_h_alpha_thres','sounding_start_date','sounding_end_date','sounding_time_stamp')\n\n end\nend\nif start_step==1 && strcmp(sounding_data,'n')\n fprintf('\\n\\n Step 1: powerlaw coefficents set by user \\n\\n')\n \n % as set by the user\n h0 = getparm_aps('powerlaw_h0');\n alpha = getparm_aps('powerlaw_alpha');\nend\n\n%% PART 2: Rotate the dataset to get mimumal white space around it\n% Scaling and interpolation of the data to a regular grid\nif start_step<=2 && end_step >=2\n fprintf('\\n\\nStep 2: Rotate the dataset \\n')\n \n % getting the variables from the parm_aps file\n heading = getparm_aps('heading',1);\n crop_flag = getparm_aps('crop_flag',1);\n\n % loading the lonlat information \n ll_matfile = getparm_aps('ll_matfile',1);\n ll = load(ll_matfile);\n ll = ll.lonlat;\n \n % retrieving the coefficients\n h0 = getparm_aps('powerlaw_h0',1);\n alpha = getparm_aps('powerlaw_alpha',1);\n getparm_aps('powerlaw_xy_res',1);\n phuw_matfile = getparm_aps('phuw_matfile',1);\n hgt_matfile = getparm_aps('hgt_matfile',1);\n DEM_corr = getparm_aps('powerlaw_DEM_corr',1);\n bperp_matfile = getparm_aps('bperp_matfile',1);\n\n % rotating the data\n [xy_rotatelocal_full,xy_local_full,local_origin_full] = ll2rotatelocal(ll,heading);\n \n \n % cropping if needed\n crop = [];\n if strcmpi(crop_flag,'y')\n if exist('area_ex.mat','file')==2 \n crop = load('area_ex.mat'); \n elseif exist('../area_ex.mat','file')==2\n crop = load('../area_ex.mat'); \n else\n crop = [];\n fprintf(['There is no area_ex.mat file found, no data is cropped... \\n']) \n end\n end\n if ~isempty(crop)\n ix_remove = inpolygon(ll(:,1),ll(:,2),crop.lonlat(:,1),crop.lonlat(:,2));\n else\n ix_remove = [];\n end\n ll(ix_remove,:) =[]; \n \n % get the InSAR convexhull -- not needed at this stage!\n ix_convexhull = convhull(ll(:,1),ll(:,2));\n InSAR_convexhull = ll(ix_convexhull,:);\n if exist('tca_support.mat','file')==2\n save('tca_support.mat','-append','InSAR_convexhull')\n else\n save('tca_support.mat','InSAR_convexhull') \n end\n clear InSAR_convexhull\n \n \n \n % rotating the data using all data including the region cropped. \n % This will be used in the last stage of the power-law code.\n [xy_rotatelocal,xy_local,local_origin] = ll2rotatelocal(ll,heading);\n \n\n fprintf(' Scaling and interpolation to a regular grid \\n\\n')\n % loading the unwrapped interferograms\n ph = load(phuw_matfile);\n ph = ph.ph_uw; \n \n % keep track of those pixels which are NaN\n ix_phase_nan = isnan(ph);\n \n % remove crop if needed\n ph(ix_remove,:)=[];\n \n \n % loading the topography information\n hgt = load(hgt_matfile);\n hgt = hgt.hgt; \n % remove crop if needed\n hgt(ix_remove,:)=[];\n\n % geting the number of interferograms and points from the phase matrix\n n_interferograms= size(ph,2);\n n_points = size(ph,1);\n \n % Scaling of the topography according to the powerlaw\n % ifg based powerlaw correction?\n if length(alpha)==n_interferograms\n hgt_max = max(hgt);\n hgt_scaled=repmat(hgt,1,size(ph,2));\n ifg_based_correction='y';\n\n for k=1:length(alpha)\n if h0(k)*1000-hgt_max<=0\n error('myApp:argChk', ['Power law is not valid above h0 heights,... \\nAbort,... \\n']) \n end\n hgt_scaled(:,k)=(h0(k)*1000-hgt_scaled(:,k)).^(alpha(k));\n end\n else\n % Scaling of the topography according to the powerlaw\n ifg_based_correction='n';\n ix = find(h0*1000-hgt < 0);\n if isempty(ix)~=1\n error('myApp:argChk', ['Power law is not valid above h0 heights,... \\nAbort,... \\n']) \n end\n hgt_scaled = (h0*1000-hgt).^(alpha);\n end\n\n % define a new dataset were the height is actually the first column and\n % the interferograms are in the other columns\n % optional remove an estimate for the DEM errors \n if strcmp(DEM_corr,'y') && n_interferograms>5;\n % these are erros that scale with perpendicular baseline\n % loading the perpendicualr baseline information\n bperp = load(bperp_matfile);\n if strcmp(stamps_processed,'y')\n bperp = bperp.bperp; \n end\n % checking the size of bperp\n if size(bperp,2) > 1\n bperp = bperp';\n if size(bperp,2) >1\n error('myApp:argChk', ['bperp is not a vector,... \\nAbort,... \\n']) \n end\n end\n % estimating the correlated errors\n DEM_corr_e = lscov(bperp,ph')';\n \n % removing DEM correlated errors \n ph_temp = ph-repmat(bperp',n_points,1).*repmat(DEM_corr_e,1,n_interferograms);\n dataset = [hgt_scaled ph_temp];\n clear ph_temp A\n else\n if strcmp(DEM_corr,'y') && n_interferograms<=5\n fprintf('Not enough interferograms to make a reliable estimate for the DEM error \\n')\n DEM_corr = 'n';\n end\n dataset = [hgt_scaled ph];\n DEM_corr_e = zeros([n_points 1]);\n end\n \n \n \n \n %% do an initial reference correction for each interferogram. \n % This is to scope for regions that are small and which can have bandfiltering\n % arctifacts introduced. What happens is that each interferogram is\n % shifted such that the phase is zero at h0. Note that this is a long\n % wavelength shift that will be filtered out latter on. But in case of\n % irregularities it will reduce introduced arctifacts. To cope with\n % spatial varying signals this offset estimation is done over multiple\n % windows, but the constant offset is the same for all windows. \n % get the position of some subwindows\n\n [iterate] = window_generation(xy_rotatelocal,1);\n \n counter=0;\n for k=1:length(iterate.window_ix)\n counter = counter + size(iterate.window_ix{k},1);\n end\n\n for k=1:n_interferograms\n % separate between ifg based correction or using a single alpha and h0\n if length(alpha)==n_interferograms\n height_data = dataset(:,k);\n scaling = 1./nanmean(abs(dataset(:,k)));\n phase_data = dataset(:,n_interferograms+k);\n else\n scaling = 1./nanmean(abs(dataset(:,1)));\n height_data = dataset(:,1);\n phase_data = dataset(:,1+k);\n end\n \n\n % estimating the reference, forced to be the same for all windows\n A_temp = zeros([counter length(iterate.window_ix)]);\n data_temp = zeros([counter size(phase_data,2)]);\n counter =1;\n for kk=1:length(iterate.window_ix)\n A_temp(counter:counter+size(iterate.window_ix{kk},1)-1,kk) = [height_data(iterate.window_ix{kk},1)]*scaling;\n data_temp(counter:counter+size(iterate.window_ix{kk},1)-1,:) = [phase_data(iterate.window_ix{kk},1)];\n counter = counter + size(iterate.window_ix{kk},1);\n\n end\n A_temp = [A_temp ones([size(data_temp,1) 1])];\n \n % allowing for NaN in interferogram {DB}\n% ix = find(isnan(data_temp(:,1))~=1); \n ix = ~((isnan(data_temp(:,1)) + sum(isnan(A_temp),2))>=1);\n coeff = lscov(A_temp(ix,:),data_temp(ix,1));\n\n % plot the interferogram before and after the reference shift.\n if plot_flag ==1\n figure('name',['Correction of the reference for ifg ', num2str(k)])\n subplot(2,1,1)\n plot(height_data,phase_data,'k.')\n if length(alpha)==n_interferograms\n temp =getparm_aps('powerlaw_alpha');\n xlabel(['(h_0-h)^{' num2str(temp(k)) '}'])\n else\n xlabel(['(h_0-h)^{' num2str(getparm_aps('powerlaw_alpha')) '}']) \n end\n ylabel('Phase')\n end\n\n if plot_flag ==1\n for kk=1:length(iterate.window_ix)\n y_temp = [[height_data(iterate.window_ix{kk},1)]*scaling ones(size([height_data(iterate.window_ix{kk},1)]*scaling))]*[coeff(kk) coeff(end)]';\n hold on\n plot([height_data(iterate.window_ix{kk},1)],y_temp,'r-')\n end \n title('power-law plot with ifg reference to be the mean')\n end\n \n % correct the data for the reference\n data_temp = data_temp - coeff(end);\n % separate between ifg based correction or using a single alpha and h0\n if length(alpha)==n_interferograms\n dataset(:,n_interferograms+k) = dataset(:,n_interferograms+k) - coeff(end);\n else\n dataset(:,k+1) = dataset(:,k+1) - coeff(end);\n end\n \n % plot the corrected result\n if plot_flag ==1\n subplot(2,1,2)\n if length(alpha)==n_interferograms\n plot(dataset(:,k),dataset(:,n_interferograms+k),'k.')\n temp =getparm_aps('powerlaw_alpha');\n xlabel(['(h_0-h)^{' num2str(temp(k)) '}'])\n else\n plot(dataset(:,1),dataset(:,k+1),'k.')\n xlabel(['(h_0-h)^{' num2str(getparm_aps('powerlaw_alpha')) '}'])\n end\n ylabel('Phase shifted to h0 reference')\n \n % plot line on top\n coeff = lscov(A_temp,data_temp(:,1));\n for kk=1:length(iterate.window_ix)\n if length(alpha)==n_interferograms\n y_temp = [[dataset(iterate.window_ix{kk},k)]*scaling ones(size([dataset(iterate.window_ix{kk},k)]*scaling))]*[coeff(kk) coeff(end)]';\n else\n y_temp = [[dataset(iterate.window_ix{kk},1)]*scaling ones(size([dataset(iterate.window_ix{kk},1)]*scaling))]*[coeff(kk) coeff(end)]';\n end\n hold on\n plot([dataset(iterate.window_ix{kk},k)],y_temp,'r-')\n\n end\n title('power law plot with h0 as reference')\n end\n end\n\n \n %% Extrapolate such the convexhull contains the full grid\n xy_res = getparm_aps('powerlaw_xy_res');\n [xy_local_box,dataset_box] = extrapolate_local_new(xy_rotatelocal,dataset, xy_res(1), xy_res(2));\n\n % Interpolate to a regular grid\n [X_regular,Y_regular,Z_regular] = interpolate_regular(xy_local_box,dataset_box, xy_res(1), xy_res(2));\n \n % Saving the results of this step\n aps_save([save_path filesep 'aps_p_step2.mat'],xy_rotatelocal,xy_rotatelocal_full,ifg_based_correction,xy_local,xy_local_full,heading,ll,local_origin,local_origin_full,X_regular,Y_regular,Z_regular,xy_rotatelocal,xy_res,DEM_corr,DEM_corr_e,ix_remove,ix_phase_nan)\n \nend\n\n\n%% PART 3: Bandfiltering and interpolation back to a local grid\nif start_step<=3 && end_step >=3\n fprintf('Step 3: Bandfiltering of the regular grid and converting back to a local grid \\n\\n')\n % Loading the data from the previous step\n if start_step==3\n load([save_path filesep 'aps_p_step2.mat'])\n end\n\n \n % loading the lonlat information \n ll_matfile = getparm_aps('ll_matfile');\n temp = load(ll_matfile);\n if strcmp(stamps_processed,'y')\n temp = temp.lonlat;\n end\n \n n_points_original = size(temp,1);\n clear temp;\n \n % getting the extend of the spatial bandfilters\n spatial_bands = getparm_aps('powerlaw_spatial_bands');\n \n % Bandfiltering\n bandfiltering(Z_regular,xy_res(1),xy_res(2),spatial_bands,save_path,ifg_based_correction)\n \n % Interpolate back to local grid\n n_datasets = size(Z_regular,3);\n % calling the function for each bandfiltered dataset\n fprintf(['*Interpolate the band filtered data to the local grid: \\n'])\n if strcmp(ifg_based_correction,'y')\n h_ifg_number = n_datasets/2;\n else\n h_ifg_number = 1;\n end\n for k=1:n_datasets\n \n % the file names, vary depending if the correction is varying for each interferogram \n if k<=h_ifg_number && h_ifg_number~=1\n % thse are interferograms\n load_name = ['bandfilter_regular_hgt_ifg_' num2str(k) '.mat'];\n save_name = ['bandfilter_local_hgt_ifg' num2str(k) '.mat'];\n elseif k<=h_ifg_number && h_ifg_number==1\n % these are the heights\n load_name = 'bandfilter_regular_hgt.mat';\n save_name = 'bandfilter_local_hgt.mat';\n else\n % thse are interferograms\n load_name = ['bandfilter_regular_ifg_' num2str(k-h_ifg_number) '.mat'];\n save_name = ['bandfilter_local_ifg_' num2str(k-h_ifg_number) '.mat'];\n end\n\n dataset_band = load([save_path filesep load_name]);\n \n % Storing the information what type of filtering was done for which band\n dimension_filter = dataset_band.dimension_filter; % 1 for 1D, 2 for 2D \n % loading the data for each dataset\n dataset_band = dataset_band.data_band_out;\n \n % computing the bandfiltered data at the local grid\n % note that this is xy_rotatelocal and does not include the cropped\n % region!\n [z_local_out_temp] = interpolate2local(X_regular,Y_regular,dataset_band,xy_rotatelocal);\n % in case data has been cropped then path the cropped region with NaNs\n z_local_out = NaN([n_points_original size(z_local_out_temp,2)]);\n \n if isempty(ix_remove)\n z_local_out = z_local_out_temp; \n else\n z_local_out(~ix_remove,:) = z_local_out_temp;\n end\n \n % Check in case some of the orginal phase values were nan.\n % if so set them to nan here too.\n if k<=h_ifg_number && h_ifg_number~=1\n % these are interferograms heights not the phase. No need to\n % modify this here.\n elseif k<=h_ifg_number && h_ifg_number==1\n % these are the heights, nothing needs to be done as the\n % heights remain the same for each interferogram.\n else\n % these are interferograms\n fprintf('Allowing for NaN''s in the interferograms \\n')\n z_local_out(ix_phase_nan(:,k-h_ifg_number),:)=NaN;\n end\n \n \n % saving the data for each dataset\n aps_save([save_path filesep save_name],z_local_out,spatial_bands,dimension_filter);\n % outputting the progress to the user\n fprintf(['Progress: ' num2str(k) '/' num2str(n_datasets) ' done \\n'])\n end\n \n % Saving the results of this step\n aps_save([save_path filesep 'aps_p_step3.mat'],ifg_based_correction,n_datasets,local_origin,local_origin_full,xy_rotatelocal,xy_rotatelocal_full,DEM_corr,DEM_corr_e,dimension_filter,ix_remove,ix_phase_nan)\nend\n\n%% PART 4: Estimating the scaling coefficient of the powerlaw for the local dataset \n% and computing the corresponding troposheric delay\nif start_step<=4 && end_step >=4\n \n \n fprintf('\\n\\nStep 4: Estimating scaling coefficient of the powerlaw locally \\n')\n fprintf('and estimating the tropospheric interferometric phase delay \\n\\n')\n \n % Loading the data from the previous step\n if start_step==4\n load([save_path filesep 'aps_p_step3.mat'])\n end\n\n % loading information from the parm file\n hgt_matfile = getparm_aps('hgt_matfile');\n powerlaw_all_bands = getparm_aps('powerlaw_all_bands');\n hgt = load(hgt_matfile);\n hgt = hgt.hgt; \n \n % checking if its an interferogram based correction or not:\n if strcmp(ifg_based_correction,'y')\n n_interferograms = n_datasets/2;\n else\n n_interferograms = n_datasets-1;\n end\n \n \n % initialization\n n_points = size(hgt,1);\n ph_tropo_powerlaw = NaN([n_points n_interferograms]);\n K_tropo_powerlaw = NaN([n_points n_interferograms]);\n perc_cons_K_powerlaw= NaN([ n_interferograms 1]);\n if strcmp(powerlaw_all_bands,'y')\n ph_tropo_powerlaw_bands = NaN([n_points n_interferograms size(getparm_aps('powerlaw_spatial_bands'),1)]); \n K_tropo_powerlaw_bands = NaN([n_points n_interferograms size(getparm_aps('powerlaw_spatial_bands'),1)]);\n end\n \n \n % Linear estimation for multiple windows based on bandfitlered data\n % final slope value is estimated for reliable bands only\n iterate = [];\n % getting the patch information from the parm_aps file\n \n \n % processing only those images that are not dropped in case of stamps\n ix_ifgs = 1:n_interferograms;\n if strcmp(stamps_processed,'y')\n ix_drop_ifgs = getparm('drop_ifg');\n else\n ix_drop_ifgs = [];\n end\n ix_ifgs(ix_drop_ifgs)=[];\n \n for k=1:length(ix_ifgs)\n \n ix_interferogram = ix_ifgs(k);\n\n % the file names, vary depending if the correction is varying for each interferogram \n if strcmp(ifg_based_correction,'y') && n_interferograms~=1\n % the first dataset was set the be the topography\n topo_data = load([save_path filesep 'bandfilter_local_hgt_ifg' num2str(ix_interferogram) '.mat']);\n topo_data = topo_data.z_local_out;\n % the other dataset were the phase\n phase_data = load([save_path filesep 'bandfilter_local_ifg_' num2str(ix_interferogram) '.mat']);\n phase_data = phase_data.z_local_out;\n ifg_number=k;\n else\n % the first dataset was set the be the topography\n topo_data = load([save_path filesep 'bandfilter_local_hgt.mat']);\n topo_data = topo_data.z_local_out;\n % the other dataset were the phase\n phase_data = load([save_path filesep 'bandfilter_local_ifg_' num2str(ix_interferogram) '.mat']);\n phase_data = phase_data.z_local_out;\n ifg_number=1;\n end\n \n % keep the figures of the outlier rejection as validation\n if k==0\n save_path_outlier_windows = [save_path filesep 'ifg_' num2str(ix_interferogram) '_outlier_window'];\n else\n save_path_outlier_windows=[];\n end\n \n if k==10000\n debug_fig_linear=1;\n else\n debug_fig_linear=0;\n end\n \n [ph_tropo_powerlaw_temp,ph_tropo_powerlaw_band_temp,iterate,K_temp,K_band,perc_cons_K] = aps_powerlaw_linear_local(xy_rotatelocal_full,local_origin_full,topo_data,phase_data,iterate,dimension_filter,save_path_outlier_windows,ifg_number,ix_phase_nan(:,ix_interferogram));\n \n \n % storing of the data\n % Computation of the tropospheric delay for all ifgs\n ph_tropo_powerlaw(:,ix_interferogram) = ph_tropo_powerlaw_temp;\n K_tropo_powerlaw(:,ix_interferogram) = K_temp;\n perc_cons_K_powerlaw(ix_interferogram,1) = perc_cons_K;\n if strcmp(powerlaw_all_bands,'y')\n % keeping all bands with in the columns the ifgs and the third\n % dimention the bands\n ph_tropo_powerlaw_bands(:,ix_interferogram,:) = ph_tropo_powerlaw_band_temp;\n K_tropo_powerlaw_bands(:,ix_interferogram,:)=K_band;\n \n % keeping the interferogram and the respective bands.\n eval(['ph_tropo_powerlaw_ifg_' num2str(ix_interferogram) '= ph_tropo_powerlaw_band_temp;']);\n eval(['K_tropo_powerlaw_ifg_' num2str(ix_interferogram) '= K_band;']);\n \n clear ph_tropo_powerlaw_band_temp\n % saving the data from this step\n if strcmp(stamps_processed,'y')\n % This is StaMPS\n if strcmp(getparm('small_baseline_flag'),'y')\n if exist(apsbandssbname,'file')==2\n save(apsbandssbname,'-append',['ph_tropo_powerlaw_ifg_' num2str(ix_interferogram)],['K_tropo_powerlaw_ifg_' num2str(ix_interferogram)])\n else\n save(apsbandssbname,['ph_tropo_powerlaw_ifg_' num2str(ix_interferogram)],['K_tropo_powerlaw_ifg_' num2str(ix_interferogram)])\n end\n else\n if exist(apsbandsname,'file')==2\n save(apsbandsname,'-append',['ph_tropo_powerlaw_ifg_' num2str(ix_interferogram)],['K_tropo_powerlaw_ifg_' num2str(ix_interferogram)])\n else\n save(apsbandsname,['ph_tropo_powerlaw_ifg_' num2str(ix_interferogram)],['K_tropo_powerlaw_ifg_' num2str(ix_interferogram)])\n end\n end\n else\n % This is not StaMPS\n if exist(apsbandsname,'file')==2\n save(apsbandsname,'-append',['ph_tropo_powerlaw_ifg_' num2str(ix_interferogram)],['K_tropo_powerlaw_ifg_' num2str(ix_interferogram)])\n else\n save(apsbandsname,['ph_tropo_powerlaw_ifg_' num2str(ix_interferogram)],['K_tropo_powerlaw_ifg_' num2str(ix_interferogram)])\n end \n end \n eval(['clear ph_tropo_powerlaw_ifg_' num2str(ix_interferogram) ' K_tropo_powerlaw_ifg_' num2str(ix_interferogram) ';']);\n end\n \n % give output to the screen\n fprintf(['Progress ifgs: ' num2str(k) '/' num2str(length(ix_ifgs)) ' done \\n'])\n end\n % saving the data from this step\n aps_save([save_path filesep 'aps_p_step4.mat'],ph_tropo_powerlaw,DEM_corr,DEM_corr_e,iterate,K_tropo_powerlaw)\n \n % saving the data into the final variable togehter were other\n % correction values are saved.\n ph_tropo_powerlaw_or= ph_tropo_powerlaw;\n K_tropo_powerlaw_or=K_tropo_powerlaw;\n if strcmp(stamps_processed,'y')\n % This is StaMPS\n if strcmp(getparm('small_baseline_flag'),'y')\n if exist(apssbname,'file')==2\n save(apssbname,'-append','ph_tropo_powerlaw','K_tropo_powerlaw','perc_cons_K_powerlaw')\n else\n save(apssbname,'ph_tropo_powerlaw','K_tropo_powerlaw','perc_cons_K_powerlaw')\n end\n \n % saving the band information\n if strcmpi(powerlaw_all_bands,'y')\n if exist(apsbandssbname,'file')==2\n save(apsbandssbname,'-append','ph_tropo_powerlaw_or','K_tropo_powerlaw_or','ph_tropo_powerlaw_bands','K_tropo_powerlaw_bands','perc_cons_K_powerlaw')\n else\n save(apsbandssbname,'ph_tropo_powerlaw_or','K_tropo_powerlaw_or','ph_tropo_powerlaw_bands','K_tropo_powerlaw_bands','perc_cons_K_powerlaw')\n end\n end\n else\n % this is single master\n if exist(apsname,'file')==2\n save(apsname,'-append','ph_tropo_powerlaw','K_tropo_powerlaw','perc_cons_K_powerlaw')\n else\n save(apsname,'ph_tropo_powerlaw','K_tropo_powerlaw','perc_cons_K_powerlaw')\n end\n \n % saving the band information\n if strcmpi(powerlaw_all_bands,'y')\n if exist(apsbandsname,'file')==2\n save(apsbandsname,'-append','ph_tropo_powerlaw_or','K_tropo_powerlaw_or','ph_tropo_powerlaw_bands','K_tropo_powerlaw_bands','perc_cons_K_powerlaw')\n else\n save(apsbandsname,'ph_tropo_powerlaw_or','K_tropo_powerlaw_or','ph_tropo_powerlaw_bands','K_tropo_powerlaw_bands','perc_cons_K_powerlaw')\n end\n end\n end\n else\n % This is not StaMPS\n if exist(apsname,'file')==2\n save(apsname,'-append','ph_tropo_powerlaw','K_tropo_powerlaw','perc_cons_K_powerlaw')\n else\n save(apsname,'ph_tropo_powerlaw','K_tropo_powerlaw','perc_cons_K_powerlaw')\n end \n \n % saving the band information\n if strcmpi(powerlaw_all_bands,'y')\n if exist(apsbandsname,'file')==2\n save(apsbandsname,'-append','ph_tropo_powerlaw_or','K_tropo_powerlaw_or','ph_tropo_powerlaw_bands','K_tropo_powerlaw_bands','perc_cons_K_powerlaw')\n else\n save(apsbandsname,'ph_tropo_powerlaw_or','K_tropo_powerlaw_or','ph_tropo_powerlaw_bands','K_tropo_powerlaw_bands','perc_cons_K_powerlaw')\n end\n end\n end\n setparm_aps('powerlaw_kept',[0]);\n\nend\n\nif start_step<=5 && end_step >=5 && exist('aps_RMSE_comparison')==2\n fprintf('\\n\\nStep 5: Powerlaw band comparison with reference\\n')\n\n if strcmpi(getparm_aps('stamps_processed'),'y')\n % check which technique it needs to be compared with\n technique_number = -10;\n while isnumeric(technique_number)~=1 | (technique_number<1 | technique_number>7)\n technique_number = input(['*Select the technique number you want to compare with: \\n---- MERIS (1), MODIS (2), MODIS Recal (3), ERA-I (4), WRF (5), u(sb) (6), u(sb)-d (7) : \\n'],'s');\n technique_number = floor(str2num(technique_number));\n end\n % the technique component as a string\n if technique_number==1\n comp_str = 'a_mi';\n elseif technique_number==2\n comp_str = 'a_MI';\n elseif technique_number==3\n comp_str = 'a_RMI';\n elseif technique_number==4\n comp_str = 'a_e';\n elseif technique_number==5\n comp_str = 'a_w';\n elseif technique_number==6\n if strcmpi(getparm('small_baseline_flag'),'y')\n comp_str = 'usb';\n else\n comp_str = 'u';\n end\n elseif technique_number==7\n if strcmpi(getparm('small_baseline_flag'),'y')\n comp_str = 'usb-d';\n else\n comp_str = 'u-d';\n end\n end\n\n % check if we should add the hydrostatic delays too in case this is\n % possible\n if technique_number==1 | technique_number==2 | technique_number==3\n hydro_comp = inf;\n while isnumeric(hydro_comp)~=1 | (hydro_comp<0 | hydro_comp>2)\n hydro_comp = input(['*Do you want to add a hydrostatic component:\\n---- None (0), ERA-I hydr (1), WRF hydro (2): \\n'],'s');\n hydro_comp = floor(str2num(hydro_comp));\n end\n else\n hydro_comp = 0;\n end\n % the hydrostatic component as a string\n hydro_str = '';\n if hydro_comp==1\n hydro_str = '+a_eh';\n elseif hydro_comp==2\n hydro_str = '+a_wh';\n end\n\n % The reference technique is combination of both\n tech_ref = [comp_str hydro_str];\n clear hydro_str comp_str technique_number hydro_comp\n\n\n % running the RMSE script\n aps_RMSE_comparison(tech_ref,'a_pbands')\n str = '';\n while strcmpi(str,'y')~=1 && strcmpi(str,'n')~=1\n str = input(['Do you want to update ''powerlaw_kept'' to a different band? [y/n] \\n'],'s');\n end\n if strcmpi(str,'y')\n bandnumber = -10;\n while (bandnumber<0 | bandnumber>size(getparm_aps('powerlaw_spatial_bands'),1))\n bandnumber = input(['Which the band? (row number of the band to keep, or 0 for all bands combined) \\n'],'s');\n bandnumber = str2num(bandnumber);\n if isempty(bandnumber)\n bandnumber = -10;\n end\n end \n setparm_aps('powerlaw_kept',[bandnumber]);\n end\n else\n fprintf('This option uses the StaMPS ps_plot function, and therefore only works if your data is stamps processed \\n') \n end\n\n \nend\n", "meta": {"author": "dbekaert", "repo": "TRAIN", "sha": "6c93feb95ae95eaf4c8468e89ec0b8325eac946f", "save_path": "github-repos/MATLAB/dbekaert-TRAIN", "path": "github-repos/MATLAB/dbekaert-TRAIN/TRAIN-6c93feb95ae95eaf4c8468e89ec0b8325eac946f/matlab/aps_powerlaw.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.3384414199218035}} {"text": "function [biomassValues, targetLowerBounds, targetUpperBounds, plottedReactions] = multiProductionEnvelope(model, deletions, biomassRxn, geneDelFlag, nPts, plotAllFlag, plotTools)\n% Calculates the byproduct secretion envelopes for\n% every product (excreted metabolites with 1 or more Carbons)\n%\n% USAGE:\n%\n% [biomassValues, targetValues] = multiProductionEnvelope(model, deletions, biomassRxn, geneDelFlag, nPts, plotTools)\n%\n% INPUT:\n% model: COBRA model structure\n%\n% OPTIONAL INPUT:\n% deletions: List of reaction or gene deletions (empty if wild type)\n% (Default = {})\n% biomassRxn: Biomass `rxn` name (Default = whatever is defined in model)\n% geneDelFlag: Perform gene and not reaction deletions (Default = false)\n% nPts: Number of points in the plot (Default = 20)\n% plotTools: boolean (default = false) - add tools for editing the figure and its properties\n% plotAllFlag: plot all envelopes, even ones that are not growth\n% coupled (Default = false)\n% plotTools: boolean (default = false) - add tools for editing the figure and its properties\n%\n% OUTPUT:\n% biomassValues: Biomass values for plotting\n% targetUpperBounds: Target upper bounds for plotting (\n% biomassvalues x reactions)\n% targetLowerBounds: Target lower bounds for plotting (\n% biomassvalues x reactions)\n% plottedReactions: Reactions that led to relevant side product \n%\n% .. Author: - Jeff Orth 8/16/07\n\nif (nargin < 2)\n deletions = {};\nend\nif (nargin < 3)\n % Biomass flux\n biomassRxn = model.rxns(model.c==1);\nend\nif (nargin < 4)\n % Gene or rxn deletions\n geneDelFlag = false;\nend\nif (nargin < 5)\n nPts = 20;\nend\nif ~exist('plotTools','var')\n plotTools = false;\nend\n\nif ~exist('plotAllFlag','var')\n plotAllFlag = false;\nend\n\n% Create model with deletions\nif (length(deletions) > 0)\n if (geneDelFlag)\n model = deleteModelGenes(model,deletions);\n else\n model = changeRxnBounds(model,deletions,zeros(size(deletions)),'b');\n end\nend\n\n%get all C exchange reactions\nexcRxns = model.rxns(findExcRxns(model,false,false));\nCRxns = findCarbonRxns(model,1);\nCExcRxns = intersect(excRxns,CRxns);\nsubstrateIDs = find(model.lb(findRxnIDs(model,CExcRxns))<0);\n%remove the substrate reactions\nfor i = 1:length(substrateIDs)\n j = substrateIDs(i);\n if j == 1\n CExcRxns = CExcRxns(2:length(CExcRxns));\n elseif j == length(CExcRxns)\n CExcRxns = CExcRxns(1:length(CExcRxns)-1);\n else\n CExcRxns = cat(1,CExcRxns(1:j-i),CExcRxns(j-i+2:length(CExcRxns)));\n end\nend\n\n\n% Run FBA to get upper bound for biomass\nmodel = changeObjective(model,biomassRxn,1);\nsolMax = optimizeCbModel(model,'max');\nsolMin = optimizeCbModel(model,'min');\n\n% Create biomass range vector\nbiomassValues = linspace(solMin.f,solMax.f,nPts);\n\nplottedReactions = {};\ntargetUpperBounds = zeros(0,0);\ntargetLowerBounds = zeros(0,0);\n% Max/min for target production\nfor i = 1:length(CExcRxns)\n model = changeObjective(model,CExcRxns(i),1);\n model2 = changeRxnBounds(model,biomassRxn,max(biomassValues),'b');\n fbasol2 = optimizeCbModel(model2,'max');\n maxRate = fbasol2.f; %find max production at max growth rate\n if (plotAllFlag)||(maxRate > getCobraSolverParams('LP','feasTol')) %Change to plot everything that is above the detection limit \n plottedReactions = [plottedReactions,CExcRxns(i)];\n targetUpperBounds(end+1,1) = 0;\n targetLowerBounds(end+1,1) = 0;\n for j = 1:length(biomassValues) \n model = changeRxnBounds(model,biomassRxn,biomassValues(j),'b');\n sol = optimizeCbModel(model,'max');\n if (sol.stat == 1)\n targetUpperBounds(end,j) = sol.f;\n elseif (sol.stat == 2)\n targetUpperBounds(end,j) = Inf;\n else\n targetUpperBounds(end,j) = NaN;\n end\n sol = optimizeCbModel(model,'min');\n if (sol.stat == 1)\n targetLowerBounds(end,j) = sol.f;\n elseif (sol.stat == 2)\n targetUpperBounds(end,j) = Inf;\n else\n targetLowerBounds(end,j) = NaN;\n end\n end\n end\nend\n\n% Plot results\ncolors = {'b','g','r','c','m','y','k'};\nfor i = 1:length(plottedReactions)\n plot([biomassValues fliplr(biomassValues)],[targetUpperBounds(i,:) fliplr(targetLowerBounds(i,:))],colors{mod(i-1,length(colors))+1},'LineWidth',2)\n axis tight;\n hold on;\nend\nhold off;\nlegend(plottedReactions);\nlegend off;\nylabel('Production Rate (mmol/gDW h)');\nxlabel('Growth Rate (1/h)');\nif plotTools\n plottools, plotbrowser('on'), figurepalette('hide'), propertyeditor('off');\nend\nbiomassValues = biomassValues';\ntargetLowerBounds = targetLowerBounds';\ntargetUpperBounds = targetUpperBounds';\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/src/design/multiProductionEnvelope.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6926419704455588, "lm_q2_score": 0.4882833952958347, "lm_q1q2_score": 0.33820557305355464}} {"text": "%{\n * Copyright (C) 2013-2020, The Regents of The University of Michigan.\n * All rights reserved.\n * This software was developed in the Biped Lab (https://www.biped.solutions/) \n * under the direction of Jessy Grizzle, grizzle@umich.edu. This software may \n * be available under alternative licensing terms; contact the address above.\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\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 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n * The views and conclusions contained in the software and documentation are those\n * of the authors and should not be interpreted as representing official policies,\n * either expressed or implied, of the Regents of The University of Michigan.\n * \n * AUTHOR: Bruce JK Huang (bjhuang[at]umich.edu)\n * WEBSITE: https://www.brucerobot.com/\n%}\n\nfunction cost = verifyCornerAccuracy(X_verification, Y_verification, P)\n C_X_transformed = P * X_verification;\n C_X_transformed = C_X_transformed ./ C_X_transformed(3,:);\n cost = (norm(C_X_transformed(1:2,:) - Y_verification(1:2,:), 'fro'))^2;\nend\n", "meta": {"author": "UMich-BipedLab", "repo": "extrinsic_lidar_camera_calibration", "sha": "d423c81e95c6de595e1dff79871385348b1c68f4", "save_path": "github-repos/MATLAB/UMich-BipedLab-extrinsic_lidar_camera_calibration", "path": "github-repos/MATLAB/UMich-BipedLab-extrinsic_lidar_camera_calibration/extrinsic_lidar_camera_calibration-d423c81e95c6de595e1dff79871385348b1c68f4/verifyCornerAccuracy.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.709019146082187, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.3379040972373141}} {"text": "function [wtRes, delRes] = simpleOptKnock(model, targetRxn, deletions, geneDelFlag, minGrowth, doubleDelFlag)\n% Simple `OptKnock` is used to check all one gene or reaction deletions for\n% growth-coupled metabolite production\n%\n% USAGE:\n%\n% [wtRes, delRes] = simpleOptKnock(model, targetRxn, deletions, geneDelFlag, minGrowth, doubleDelFlag)\n%\n% INPUTS:\n% model: COBRA model structure\n% targetRxn: Target metabolite production reaction\n%\n% OPTIONAL INPUTS:\n% deletions: Set of gene or reaction deletions to consider for `KO`\n% (Default = all reactions)\n% geneDelFlag: Gene deletion flag (Default = false)\n% minGrowth: Minimum `KO` growth rate (Default = 0.05)\n% doubleDelFlag: Double deletions (Default = false)\n%\n% OUTPUTS:\n% wtRes: Wild type results\n% delRes: Deletion strain results\n%\n% .. Author: - Markus Herrgard 2/14/07\n%\n% The results structures have fields:\n%\n% * `growth` - Growth rate of strain\n% * `minProd` - Minimum prod rate of target metabolite\n% * `maxProd` - Maximum prod rate of target metabolite\n\nif (nargin < 3)\n deletions = model.rxns;\nend\nif (nargin < 4)\n geneDelFlag = false;\nend\nif (nargin < 5)\n minGrowth = 0.05;\nend\nif (nargin < 6)\n doubleDelFlag = false;\nend\n\ntol = 1e-7;\n\n%rxnGeneMat is a required field for this function, so if it does not exist,\n%build it.\nif ~isfield(model,'rxnGeneMat')\n model = buildRxnGeneMat(model);\nend\n\n% Number of deletions\nnDel = length(deletions);\n\n% Wild type values\nsolWT = optimizeCbModel(model);\ngrRounded = floor(solWT.f/tol)*tol;\nmodelWT = changeRxnBounds(model,model.rxns(model.c==1),grRounded,'l');\nmodelWT = changeObjective(modelWT,targetRxn,1);\nsolMax = optimizeCbModel(modelWT);\nsolMin = optimizeCbModel(modelWT);\n\nwtRes.growth = solWT.f;\nwtRes.maxProd = solMax.f;\nwtRes.minProd = solMin.f;\n\nif (doubleDelFlag)\n growthRate = sparse(nDel,nDel);\n maxProd = sparse(nDel,nDel);\n minProd = sparse(nDel,nDel);\nelse\n growthRate = zeros(nDel,1);\n maxProd = zeros(nDel,1);\n minProd = zeros(nDel,1);\nend\n\n\nif (~doubleDelFlag)\n showprogress(0,'Simple OptKnock in progress ...');\nend\nt0 = cputime;\ndelCounter = 0;\nfor i = 1:nDel\n if (~doubleDelFlag)\n if mod(i,10) == 0\n showprogress(i/nDel);\n end\n end\n if (geneDelFlag)\n % Gene deletion\n modelKO = deleteModelGenes(model,deletions{i});\n else\n % Reaction deletion\n modelKO = changeRxnBounds(model,deletions{i},0,'b');\n end\n % Calculate optimal growth rate\n solKO = optimizeCbModel(modelKO);\n %fprintf('Single %s %f\\n',deletions{i},solKO.f);\n growthRate(i,1) = solKO.f;\n if (solKO.f > minGrowth && solKO.stat == 1)\n % Max & min production of the metabolite at the optimal growth rate\n grRounded = floor(solKO.f/tol)*tol;\n modelKO = changeRxnBounds(modelKO,modelKO.rxns(modelKO.c==1),grRounded,'l');\n modelKO = changeObjective(modelKO,targetRxn,1);\n solMax = optimizeCbModel(modelKO,'max');\n solMin = optimizeCbModel(modelKO,'min');\n if (~doubleDelFlag)\n maxProd(i,1) = solMax.f;\n minProd(i,1) = solMin.f;\n %fprintf('%f %f\\n',solMax.f,solMin.f);\n else\n maxProd(i,i) = solMax.f;\n minProd(i,i) = solMin.f;\n for j = i+1:nDel\n delCounter = delCounter+1;\n if mod(j,50) == 0\n fComp = delCounter/(nDel*(nDel-1)/2);\n fprintf('%d\\t%f\\t%f\\n',delCounter,100*fComp,(cputime-t0)/60);\n end\n if (geneDelFlag)\n % Gene deletion\n modelKO2 = deleteModelGenes(model,deletions{i});\n modelKO2 = deleteModelGenes(modelKO2,deletions{j});\n else\n modelKO2 = changeRxnBounds(model,deletions{i},0,'b');\n modelKO2 = changeRxnBounds(modelKO2,deletions{j},0,'b');\n end\n % Calculate optimal growth rate\n solKO2 = optimizeCbModel(modelKO2);\n growthRate(i,j) = solKO2.f;\n %fprintf('Double %s %s %f\\n',deletions{i},deletions{j},solKO2.f);\n if (solKO2.f > minGrowth && solKO2.stat == 1)\n grRounded2 = floor(solKO2.f/tol)*tol;\n modelKO2 = changeRxnBounds(modelKO2,modelKO2.rxns(modelKO2.c==1),grRounded2,'l');\n modelKO2 = changeObjective(modelKO2,targetRxn,1);\n solMax2 = optimizeCbModel(modelKO2,'max');\n solMin2 = optimizeCbModel(modelKO2,'min');\n if (solMin2.f > 0)\n fprintf('%s %s %f %f %f\\n',deletions{i},deletions{j},solKO2.f,solMax2.f,solMin2.f);\n end\n maxProd(i,j) = solMax2.f;\n minProd(i,j) = solMin2.f;\n end\n end\n end\n end\nend\n\n% Store results\ndelRes.maxProd = maxProd;\ndelRes.minProd = minProd;\ndelRes.growth = growthRate;\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/src/design/simpleOptKnock.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7090191337850933, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.3379040913767695}} {"text": "function [suppressionIndex, pos_Vol, neg_Vol, pos_Vol_pRF, neg_Vol_pRF] = rmGetDoGSuppressionIndex(model,varargin)\n%[suppressionIndex, pos_Vol, neg_Vol, pos_Vol_pRF, neg_Vol_pRF] = rmGetDoGSuppressionIndex(model,ROIcoords)\n%\n% rmGetDoGSuppressionIndex - calculates the suppression Index from the DoG model\n% Calculates both the volume of the positive gaussian and the negative gaussian that make the\n% pRF, it only takes into account the part of the gaussians that fall inside the stimulus window.\n% The suppression index is the ratio of the negative and the positive\n% volumes. Higher values indicate more suppression. (JOV Zuiderbaan et al.\n% 2012)\n%\n% !! Needs at least the size of the stimulus (sts) as an input in varargin !!\n% either by its direct value or by the params of the model:\n% [suppressionIndex, pos_Vol, neg_Vol, pos_Vol_pRF, neg_Vol_pRF] = rmGetDoGSuppressionIndex(model,'sts',6.25)\n% [suppressionIndex, pos_Vol, neg_Vol, pos_Vol_pRF, neg_Vol_pRF] = rmGetDoGSuppressionIndex(model,'rm',vw.rm)\n%\n% suppressionIndex : ratio of the volumes of the negative and the positive gaussian that fall inside the stimuluswindow\n% pos_Vol : volume of the positive gaussian that falls inside the stimuluswindow\n% neg_Vol : volume of the negative gaussian that falls inside the stimuluswindow\n% pos_Vol_pRF : volume of the positive part of the pRF that falls inside the stimuluswindow\n% neg_Vol_pRF : volume of the negative part of the pRF that falls inside the stimuluswindow\n%\n% WZ 02/12: Wrote it\n\n\n% set default parameters\nparams.sampleRate = 0.125; % samplerate of the grid to make the gaussians\nparams.SI_Centered = false; % by default the pRF has its original position on the grid, you can make it centered on (0,0) \n % by giving this parameter the value true, using varargin\n\nif nargin > 1,\n addArg = varargin;\n if numel(addArg) == 1,\n addArg=addArg{1};\n end;\nelse\n addArg = [];\nend;\n\n% parse command line inputs:\nparams = rmProcessVarargin(params,addArg);\n\n% the stimulus size needs to be given \nif ~isfield(params,'stimSize') || isempty(params.stimSize),\n disp('ERROR: Need size of the stimulus');\n error('Need size of the stimulus');\nend\n\n% make the stimuluswindow\nmygridx = (-params.stimSize:params.sampleRate:params.stimSize);\n[X2, Y2] = meshgrid(mygridx,mygridx);\nY2 = flipud(Y2);\nX2 = X2(:);\nY2 = Y2(:);\n\necc = sqrt(X2.^2 + Y2.^2);\nkeep = ecc > -params.stimSize & ecc < params.stimSize;\nX = X2(keep);\nY = Y2(keep);\n\ngridsize = params.sampleRate.^2;\n\nsigma = model.sigma.major;\nsigma2 = model.sigma2.major;\nbeta1 = model.beta(1,:,1);\nbeta2 = model.beta(1,:,2); \nx = model.x0;\ny = model.y0;\n\n% if ROI indices are given, take only the data for that ROI\nif isfield(params,'ROIindex') && ~isempty(params.ROIindex)\n sigma = sigma(params.ROIindex);\n sigma2 = sigma2(params.ROIindex);\n beta1 = beta1(params.ROIindex);\n beta2 = beta2(params.ROIindex);\n x = x(params.ROIindex);\n y = y(params.ROIindex);\nend\n\nsuppressionIndex = zeros(1,numel(sigma2));\npos_Vol = zeros(1,numel(sigma2));\nneg_Vol = zeros(1,numel(sigma2));\npos_Vol_pRF = zeros(1,numel(sigma2));\nneg_Vol_pRF = zeros(1,numel(sigma2));\n\nfor k =1:numel(sigma2)\n if ~params.SI_Centered\n rfpositive = rfGaussian2d(X,Y,sigma(k),sigma(k),0,x(k),y(k)); % original position of the pRF in the stimulus window\n rfnegative = rfGaussian2d(X,Y,sigma2(k),sigma2(k),0,x(k),y(k)); \n else\n rfpositive = rfGaussian2d(X,Y,sigma(k),sigma(k),0,0,0); % center the pRF at (0,0)\n rfnegative = rfGaussian2d(X,Y,sigma2(k),sigma2(k),0,0,0);\n end\n rfposGaus = beta1(k).*rfpositive; \n rfnegGaus = beta2(k).*rfnegative;\n rftotal = rfposGaus + rfnegGaus;\n\n % calculate the volume of both gaussians that make the pRF\n pos_Vol(k) = (sum(rfposGaus)).*gridsize; \n neg_Vol(k) = -(sum(rfnegGaus)).*gridsize;\n ipos = rftotal > 0;\n ineg = rftotal < 0;\n % calculate the volume of the positive and negative part of the pRF\n pos_Vol_pRF(k) = (sum(rftotal(ipos))).*gridsize;\n neg_Vol_pRF(k) = -(sum(rftotal(ineg))).*gridsize;\n\n if beta2(k)>= 0;\n suppressionIndex(k) = 0; % if beta2 is bigger or equal to zero, there is no suppression and the suppression index will be 0\n else\n suppressionIndex(k) = neg_Vol(k)./pos_Vol(k);\n end\n\nend\n\n\nfunction params = rmProcessVarargin(params,vararg)\nif ~exist('vararg','var') || isempty(vararg), return; end\nfor n=1:2:numel(vararg),\n data = vararg{n+1};\n fprintf(1,' %s,',vararg{n});\n switch lower(vararg{n}),\n case {'ri','roi','roiindex', 'roi_index','roi index'}\n params.ROIindex = data;\n\n case {'sts','stimsize','size of the stimulus'}\n params.stimSize = data;\n\n case {'rm','rm params','params struct of the retinotopic model'} %vw.rm\n params.stimSize = data.retinotopyParams.stim.stimSize;\n \n case {'sr','samplerate','samplerate of the grid'}\n params.sampleRate = data;\n \n case {'sic','si_centered','si centered','suppression index centered'}\n params.SI_Centered = logical(data);\n\n otherwise,\n fprintf(1,'[%s]:IGNORING unknown parameter: %s\\n',...\n mfilename,vararg{n});\n end;\nend;\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrBOLD/Analysis/retinotopyModel/rmGetDoGSuppressionIndex.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.3378178717264721}} {"text": "function [y]=funcrs2(tt,fun,eps,y,nswp)\n%Cross approximation of a function of a TT-tensor, Method 2\n% [Y]=FUNCRS2(TT,FUN,EPS,Y,NSWP)\n% Computes approximation to the function FUN(TT) with accuracy EPS\n% Auxiliary parameters: Y (initial approximation), NSWP\n% (number of sweeps in the method\n% Much faster then usual cross by vectorized computation of subtensors\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\n%PARAMETERS SECTION\nrmin=1;\nverb=true;\nkick_rank=5;\nif (~isempty(y))\n yold=y;\nend\ny1=y;\n%For this procedure we need only local (!) indices, since it\n%is more or less equivalent to orthogonalization;\nd=tt.d;\nps=tt.ps;\ncore0=tt.core;\nn=tt.n;\nr=tt.r;\n\nry=y.r;\npsy=y.ps;\ncry=y.core;\nphi=cell(d+1,1);\nphi{d+1}=1;\nphi{1}=1;\nphx=cell(d+1,1);\nphx{d+1}=1; %For storing submatrices in U & V\nphx{1}=1;\n%Warmup procedure: orthogonalize from right-to-left & maxvol\n cry_old=cry; %This is for checking the accuracy\n psy=cumsum([1;n.*ry(1:d).*ry(2:d+1)]);\n pos1=psy(d+1);\n %The first is the the o\n for i=d-1:-1:1\n %Do right-to-left SVD + maxvol (i.e., no fun() is employed, just the\n %current approximation)\n cr=cry(pos1-ry(i+1)*n(i+1)*ry(i+2):pos1-1);\n cr2=cry_old(psy(i):psy(i+1)-1);\n cr2=reshape(cr2,[ry(i)*n(i),ry(i+1)]);\n cr=reshape(cr,[ry(i+1),n(i+1)*ry(i+2)]);\n %cr=cr.';\n %[cr,rm]=qr(cr,0);\n %rm=2*eye(ry(i+1));\n %cr=cr/2;\n [u,s,v]=svd(cr,'econ'); s=diag(s);\n ry(i+1) = my_chop2(s,norm(s)*eps/sqrt(d-1));\n %cr = u * s * v', I think we should leave v orthogonal\n u=u(:,1:ry(i+1)); v=v(:,1:ry(i+1));\n s=s(1:ry(i+1)); u=u*diag(s);\n cr=conj(v); %cr is n(i+1),ry(i+2),ry(i+1) --- No. it is conj(v)\n rm=u.'; %This is discussable --- maybe u' (or u.')?\n ry(i+1)=size(cr,2);\n %Maxvol should be computed in a different matrix\n cr0=reshape(cr,[n(i+1),ry(i+2),ry(i+1)]);\n cr0=permute(cr0,[3,1,2]);\n cr0=reshape(cr0,[ry(i+1)*n(i+1),ry(i+2)]);\n cr0=cr0*phx{i+2}.';\n cr0=reshape(cr0,[ry(i+1),n(i+1)*ry(i+2)]);\n cr0=cr0.';\n ind=maxvol2(cr0);\n r1=cr0(ind,:);\n phx{i+1}=r1;\n\n cr=cr.';\n\n cry(pos1-ry(i+1)*n(i+1)*ry(i+2):pos1-1)=cr(:);\n pos1=pos1-ry(i+1)*n(i+1)*ry(i+2);\n cr2=cr2*(rm).';\n cry(pos1-ry(i)*n(i)*ry(i+1):pos1-1)=cr2(:);\n %Take phi matrix; convolve from right with current cors of V\n cr0=core0(ps(i+1):ps(i+2)-1);\n cr0=reshape(cr0,[r(i+1)*n(i+1),r(i+2)]);\n cr0=cr0*phi{i+2}; %cr0 is now r(i)*n(i)*ry(i+1);\n cr0=reshape(cr0,[r(i+1),n(i+1)*ry(i+2)]);\n phi{i+1}=cr0(:,ind);\n end\n pos1=pos1-ry(1)*n(1)*ry(2);\n psy=cumsum([1;n.*ry(1:d).*ry(2:d+1)]);\n cry=cry(pos1:numel(cry));\n y.core=cry;\n y.r=ry;\n y.ps=psy;\n\n swp=1;\nyold=[];\nnot_converged = true;\nwhile ( swp < nswp && not_converged )\n max_er=0;\ncry_old=cry; %This is for checking the accuracy\npsy=cumsum([1;n.*ry(1:d).*ry(2:d+1)]);\npos1=1;\n for i=1:d-1\n %fprintf('i=%d \\n',i);\n %We care for two cores, with number i & number i+1, and use\n %psi(i) and psi(i+2) as a basis; also we will need to recompute\n %psi(i+1)\n ps1=phi{i}; ps2=phi{i+2}; px1=phx{i}; px2=phx{i+2};\n %Compute (!) superblock and function (!) of it\n cr1=core0(ps(i):ps(i+1)-1);\n cr2=core0(ps(i+1):ps(i+2)-1);\n cr1=reshape(cr1,[r(i),n(i)*r(i+1)]);\n cr1=ps1*cr1;\n cr2=reshape(cr2,[r(i+1)*n(i+1),r(i+2)]);\n cr2=cr2*ps2;\n cr1=reshape(cr1,[ry(i)*n(i),r(i+1)]);\n cr2=reshape(cr2,[r(i+1),n(i+1)*ry(i+2)]);\n cr=cr1*cr2;\n %cr=reshape(cr,[ry(i)*n(i)*n(i+1),ry(i+2)]);\n cr=fun(cr); %Elements are evaluated here!\n cr=reshape(cr,[ry(i)*n(i)*n(i+1),ry(i+2)]);\n cr = cr/(px2.');\n cr=reshape(cr,[ry(i),n(i)*n(i+1)*ry(i+2)]);\n cr=px1 \\cr;\n cr=reshape(cr,[ry(i)*n(i),n(i+1)*ry(i+2)]);\n %Check for local approximation of cr for the error\n cry1=cry(pos1:pos1+ry(i)*n(i)*ry(i+1)-1);\n %cry2=cry(pos1+ry(i)*n(i)*ry(i+1):pos1+ry(i)*n(i)*ry(i+1)+ry(i+1)*n(i+1)*ry(i+2)-1);\n %if ( swp == 2 )\n % if ( i == 5 )\n % keyboard;\n % end\n %end\n cry2=cry_old(psy(i+1):psy(i+2)-1);\n\n cry1=reshape(cry1,[ry(i)*n(i),ry(i+1)]);\n cry2=reshape(cry2,[ry(i+1),n(i+1)*ry(i+2)]);\n appr=cry1*cry2;\n er=norm(appr-cr,'fro')/norm(cr,'fro');\n %keyboard;\n max_er=max(er,max_er);\n\n %Compute SVD of cr\n\n [u,s,v]=svd(cr,'econ');\n s=diag(s);\n r2=my_chop2(s,eps*norm(s)/sqrt(d-1));\n s=s(1:r2); u=u(:,1:r2); v=conj(v(:,1:r2));\n v=v*diag(s);\n\n %Kick rank of u\n ur=randn(size(u,1),kick_rank);\n %Orthogonalize ur to u by Golub-Kahan reorth <- it sucks!!\n [u,rv]=qr([u,ur], 0);\n% u=reort(u,ur);\n% radd=size(u,2)-r2;\n% if ( radd > 0 )\n vr=zeros(size(v,1),kick_rank);\n v=[v,vr];\n v = v*(rv.');\n% end\n r2=size(u,2);\n\n\n %ind=maxvol2(u);\n %r1=u(ind,:);\n %u=u/r1; v=v*r1'; v=v.';\n v=v.';\n ry(i+1)=r2;\n cry(pos1:pos1+ry(i)*n(i)*ry(i+1)-1)=u(:);\n pos1=pos1+ry(i)*n(i)*ry(i+1);\n cry(pos1:pos1+ry(i+1)*n(i+1)*ry(i+2)-1)=v(:);\n\n\n\n %Compute new maxvol and (new) submatrices\n u=reshape(u,[ry(i),n(i)*ry(i+1)]);\n u=px1*u;\n u=reshape(u,[ry(i)*n(i),ry(i+1)]);\n ind=maxvol2(u);\n phx{i+1}=u(ind,:);\n %Now we have to: cr1 with phi from the left\n phi{i+1}=cr1(ind,:); %phi{i+1}=phi{i+1};\n\n\n end\n %Truncate local memory\n cry=cry(1:pos1+ry(d)*n(d)*ry(d+1)-1);\n psy=cumsum([1;n.*ry(1:d).*ry(2:d+1)]);\ny.core=cry;\ny.r=ry;\ny.ps=psy;\ncry_old=cry;\n%m=numel(cry);\n%cry=[zeros(size(cry)),cry];\n%pos1=pos1+m;\n%cry2=cry_old(psy(i+1):psy(i+2)-1);\ncry=cry(psy(d):psy(d+1)-1); %Start--only two cores\n for i=d-1:-1:1\n %fprintf('i=%d \\n',i);\n %We care for two cores, with number i & number i+1, and use\n %psi(i) and psi(i+2) as a basis; also we will need to recompute\n %psi(i+1)\n ps1=phi{i}; ps2=phi{i+2}; px1=phx{i}; px2=phx{i+2};\n %Take current core; convolve it with\n %core=core(ps\n %Compute (!) superblock and function (!) of it\n cr1=core0(ps(i):ps(i+1)-1);\n cr2=core0(ps(i+1):ps(i+2)-1);\n cr1=reshape(cr1,[r(i),n(i)*r(i+1)]);\n cr1=ps1*cr1;\n cr2=reshape(cr2,[r(i+1)*n(i+1),r(i+2)]);\n cr2=cr2*ps2;\n cr1=reshape(cr1,[ry(i)*n(i),r(i+1)]);\n cr2=reshape(cr2,[r(i+1),n(i+1)*ry(i+2)]);\n cr=cr1*cr2;\n cr=reshape(cr,[ry(i)*n(i),n(i+1)*ry(i+2)]);\n cr=fun(cr); %Elements are evaluated here!\n cr=reshape(cr,[ry(i)*n(i)*n(i+1),ry(i+2)]);\n cr = cr/(px2.');\n cr=reshape(cr,[ry(i),n(i)*n(i+1)*ry(i+2)]);\n cr=px1 \\cr;\n cr=reshape(cr,[ry(i)*n(i),n(i+1)*ry(i+2)]);\n %Check for local approximation of cr for the error\n %cry1=cry(pos1-ry(i)*n(i)*ry(i+1):pos1-1);\n cry1=cry_old(psy(i):psy(i+1)-1);\n %cry2=cry(ry(:ry(i+1)*n(i+1)*ry(i+2));\n %cry1=cry(1:ry(i)*n(i)*ry(i+1));\n %cry2=cry(ry(i)*n(i)*ry(i+1)+1:ry(i)*n(i)*ry(i+1)+ry(i+1)*n(i+1)*ry(i+2));\n cry2=cry(1:ry(i+1)*n(i+1)*ry(i+2));\n cry(1:ry(i+1)*n(i+1)*ry(i+2))=[];\n %cry2=cry_old(psy(i+1):psy(i+2)-1);\n %cry(1:(ry(i+1)*n(i+1)*ry(i+2)))=[]; %Delete both of first cores\n %cry(1:ry(i)*n(i)*ry(i+1)+ry(i+1)*n(i+1)*ry(i+2))=[];\n cry1=reshape(cry1,[ry(i)*n(i),ry(i+1)]);\n cry2=reshape(cry2,[ry(i+1),n(i+1)*ry(i+2)]);\n appr=cry1*cry2;\n er=norm(appr-cr,'fro')/norm(cr,'fro');\n %er\n max_er=max(er,max_er);\n\n %Compute SVD of cr\n [u,s,v]=svd(cr,'econ');\n s=diag(s);\n r2=my_chop2(s,eps*norm(s)/sqrt(d-1));\n s=s(1:r2); u=u(:,1:r2); v=v(:,1:r2);\n \n v = conj(v); % <- bug was here\n \n %Make it standard\n u=u*diag(s);\n\n\n %Kick rank\n\n vr=randn(size(v,1),kick_rank);\n [v,rv]=qr([v,vr], 0);\n% v=reort(v,vr);\n% radd=size(v,2)-r2;\n% if ( radd > 0 )\n ur=zeros(size(u,1),kick_rank);\n u=[u,ur];\n u = u*(rv.');\n% end\n r2=size(v,2);\n\n\n\n v=v.';v0=v;\n %Compute new phi;\n ry(i+1)=r2;\n u=u(:); u=u.'; v=v(:); v=v.';\n cry=[u,v,cry];\n %keyboard;\n %We need new memory for\n %cry(pos1:pos1+ry(i+1)*n(i+1)*ry(i+2)-1)=v(:); %Here memory has to be (?) enlarged\n %if ( pos1 <= ry(i)*n(i)*ry(i+1) ) %Have to enlarge memory\n % cry=cry(pos1:numel(cry));\n % cry=[u(:)',cry];\n % pos1=ry(i)*n(i)*ry(i+1)+1;\n %else\n % pos1=pos1-ry(i)*n(i)*ry(i+1);\n % cry(pos1:pos1+ry(i)*n(i)*ry(i+1)-1)=u(:);\n %end\n %Compute new maxvol and (new) submatrices\n v0=reshape(v0,[ry(i+1)*n(i+1),ry(i+2)]);\n v0=v0*px2.';\n v0=reshape(v0,[ry(i+1),n(i+1)*ry(i+2)]);\n v0=v0.';\n ind=maxvol2(v0);\n phx{i+1}=v0(ind,:);\n %Now we have to: cr1 with phi from the left\n phi{i+1}=cr2(:,ind);\n\n end\n\n psy=cumsum([1;n.*ry(1:d).*ry(2:d+1)]);\n\ny.core=cry;\ny.r=ry;\ny.ps=psy;\nif ( isempty(yold) )\n yold=y;\n er_nrm=1;\nelse\n\n er_nrm=norm(yold-y)/norm(y);\n yold=y;\nend\n fprintf('sweep=%d, er=%3.2e er_nrm=%3.2e \\n',swp,max_er,er_nrm);\n\nswp=swp+1;\nend\n psy=cumsum([1;n.*ry(1:d).*ry(2:d+1)]);\n\ny.core=cry;\ny.r=ry;\ny.ps=psy;\n\nend\n", "meta": {"author": "oseledets", "repo": "TT-Toolbox", "sha": "1b87616b1e84de89699697fe196eba814aabe954", "save_path": "github-repos/MATLAB/oseledets-TT-Toolbox", "path": "github-repos/MATLAB/oseledets-TT-Toolbox/TT-Toolbox-1b87616b1e84de89699697fe196eba814aabe954/@tt_tensor/funcrs2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.3376767649961489}} {"text": "function N1 = plus(N1, N2) \n%PLUS Plus for CHEBOP2.\n%\n% N = PLUS(N1, N2) is the same as N = N1 + N2. \n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n \n% Check domains are the same. \nif ( all( N1.domain ~= N1.domain ) )\n error('CHEBFUN:CHEBOP2:plus:domain', ...\n 'Domains of operators must be identical.');\nend\n\n% Plus the coefficient matrices together. \nA = N1.coeffs; \nB = N2.coeffs;\n\n% PLUS the coefficient cellarrays or matrices together: \nif ( iscell(A) && iscell(B) )\n C = cell(max(size(A, 1), size(B, 1)), max(size(A, 2), size(B, 2)));\n if size(B, 1) < size(C, 1) \n B{size(C, 1),1} = [];\n end\n if ( size(B, 2) < size(C, 2) )\n B{1,size(C, 2)} = [];\n end \n if ( size(A, 1) < size(C, 1) )\n A{size(C, 1),1} = [];\n end \n if ( size(A, 2) < size(C, 2) )\n A{1,size(C, 2)} = [];\n end \n for jj = 1:size(C, 1)\n for kk = 1:size(C, 2)\n if ( isempty(B{jj,kk}) )\n C{jj,kk} = A{jj,kk};\n elseif ( isempty(A{jj,kk}) )\n C{jj,kk} = B{jj,kk};\n else\n C{jj,kk} = A{jj,kk} + B{jj,kk};\n end\n end\n end\n \nelseif ( iscell(A) )\n BB = cell(size(B, 2), size(B, 1));\n for jj = 1:size(B, 1)\n for kk = 1:size(B, 2)\n BB(kk,jj) = {B(jj,kk)};\n end\n end\n N2.coeffs = BB;\n N1 = plus(N1, N2); \n return\n \nelseif ( iscell(B) )\n AA = cell(size(A, 2), size(A, 1));\n for jj = 1:size(A, 1)\n for kk = 1:size(A, 2)\n AA(kk,jj) = {A(jj,kk)};\n end\n end\n N1.coeffs = AA;\n N1 = plus(N1, N2); \n return\n \nelse\n C = zeros(max(size(A, 1), size(B, 1)), max(size(A, 2), size(B, 2)));\n if size(B, 1) < size(C, 1) \n B(size(B, 1)+1:size(C, 1),:) = 0;\n end\n if size(B, 2) < size(C, 2) \n B(:,size(B, 2)+1:size(C, 2)) = 0;\n end\n if size(A, 1) < size(C, 1) \n A(size(A, 1)+1:size(C, 1),:) = 0;\n end \n if size(A, 2) < size(C, 2) \n A(:,size(A, 2)+1:size(C, 2)) = 0;\n end \n C = A + B; \nend\n\n% Loop over to remove empty cells (replace with zeros). \nfor jj = 1:size(C, 1)\n for kk = 1:size(C, 2)\n if ( isempty(C{jj,kk}) ) \n C{jj,kk} = 0;\n end\n end\nend\n\n% Do not add boundary conditions together. Ignore them. \nif ( ~isempty(N1.lbc) || ~isempty(N1.rbc) ||...\n ~isempty(N1.ubc) || ~isempty(N1.dbc) )\n warning('CHEBFUN:CHEBOP2:plus:ignoredBCs', 'BCs were ignored.');\n N1.lbc =[]; \n N1.rbc =[];\n N1.ubc =[]; \n N1.dbc =[]; \nend\nif ( ~isempty(N2.lbc) || ~isempty(N2.rbc) ||...\n ~isempty(N2.ubc) || ~isempty(N2.dbc) )\n warning('CHEBFUN:CHEBOP2:plus:ignoredBCs', 'BCs were ignored.');\n N2.lbc =[]; \n N2.rbc =[]; \n N2.ubc =[]; \n N2.dbc =[];\nend\n\n% Assign to output: \nN1.coeffs = C;\nN1.xorder = max(N1.xorder, N2.xorder); \nN1.yorder = max(N1.yorder, N2.yorder); \n% Plus the ops together:\nop1 = N1.op; \nop2 = N2.op; \nN1.op = @(u) op1(u) + op2(u); \n\nend\n", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/@chebop2/plus.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5964331319177487, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.3375922076705073}} {"text": "function [d pred f]=astar_search(A,s,h,varargin)\n% ASTAR_SEARCH Perform a heuristically guided (A*) search on the graph.\n%\n% [d pred rank]=astar_search(A,s,h,optionsu) returns the distance map,\n% search tree and f-value of each node in an astar_search. \n% The search begins at vertex s. The heuristic h guides the search, \n% h(v) should be small close to a goal and large far from a goal. The\n% heuristic h can either be a vector with an entry for each vertex in the\n% graph or a function which maps vertices to values.\n%\n% This method works on non-negatively weighted directed graphs.\n% The runtime is O((E+V)log(V)).\n%\n% ... = astar_search(A,u,...) takes a set of\n% key-value pairs or an options structure. See set_matlab_bgl_options\n% for the standard options. \n% options.visitor: a visitor to use with the A* search (see Note)\n% options.inf: the value to use for unreachable vertices \n% [double > 0 | {Inf}]\n% options.target: a special vertex that will stop the search when hit\n% [{'none'} | any vertex number besides the u]; this is ignored if\n% a visitor is set.\n% options.edge_weight: a double array over the edges with an edge\n% weight for each node, see EDGE_INDEX and EXAMPLES/REWEIGHTED_GRAPHS\n% for information on how to use this option correctly\n% [{'matrix'} | length(nnz(A)) double vector]\n% \n% Note: You can specify a visitor for this algorithm. The visitor has the\n% following optional functions.\n% vis.initialize_vertex(u)\n% vis.discover_vertex(u)\n% vis.examine_vertex(u)\n% vis.examine_edge(ei,u,v)\n% vis.edge_relaxed(ei,u,v)\n% vis.edge_not_relaxed(ei,u,v)\n% vis.black_target(ei,u,v)\n% vis.finish_vertex(u)\n% Each visitor parameter should be a function pointer, which returns 0\n% if the search should stop. (If the function does not return anything, \n% the algorithm continues.)\n%\n% Example:\n% load graphs/bgl_cities.mat\n% goal = 11; % Binghamton\n% start = 9; % Buffalo\n% % Use the euclidean distance to the goal as the heuristic\n% h = @(u) norm(xy(u,:) - xy(goal,:));\n% % Setup a routine to stop when we find the goal\n% ev = @(u) (u ~= goal);\n% [d pred f] = astar_search(A, start, h, ...\n% struct('visitor', struct('examine_vertex', ev)));\n\n% David Gleich\n% Copyright, Stanford University, 2006-2008\n\n%% History \n% 2007-04-20: Added edge weight option\n% 2007-07-12: Fixed edge_weight documentation.\n% 2008-10-07: Changed options parsing\n%%\n\n[trans check full2sparse] = get_matlab_bgl_options(varargin{:});\nif full2sparse && ~issparse(A), A = sparse(A); end\n\noptions = struct('inf', Inf, 'edge_weight', 'matrix', 'target', 'none');\noptions = merge_options(options,varargin{:});\n\nedge_weight_opt = 'matrix';\n\nif strcmp(options.edge_weight, 'matrix')\n % do nothing if we are using the matrix weights\nelse\n edge_weight_opt = options.edge_weight;\nend\n\nif strcmp(options.target,'none')\n target = 0; % a flag used to denote \"no target\" to the mex\nelseif isa(options.target, 'double')\n target = options.target;\nelse\n error('matlab_bgl:invalidParameter', ...\n 'options.target is not ''none'' or a vertex number.');\nend\n\nif check, check_matlab_bgl(A,struct()); end\nif trans, A = A'; end\n\nfunction hi=vec2func(u)\n hi = h(u);\nend\n\nif isa(h,'function_handle')\n hfunc = h;\nelse\n hfunc = @vec2func;\nend\n\nif isfield(options,'visitor')\n [d pred f] = astar_search_mex(A,s,target,hfunc,options.inf,edge_weight_opt,options.visitor);\nelse\n [d pred f] = astar_search_mex(A,s,target,h,options.inf,edge_weight_opt);\nend\n\n\n% end the main function\nend\n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/External/matlab_bgl/astar_search.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6297746213017459, "lm_q2_score": 0.5350984286266116, "lm_q1q2_score": 0.33699141024748364}} {"text": "function cS = corundum\n \ncs_Crn = crystalSymmetry('-32/m',[1 1 2.729]);\nN = Miller({0,0,1},{1,0,2},{1,1,3},{2,-1,-1},{1,1,-1},{7,-14,-3},cs_Crn);\ndist = [0.5, 1.49, 2.35, 1.53, 9.95, 9.95];\ncS = crystalShape(N./dist);", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/geometry/+crystalShape/corundum.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7690802264851919, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.3367213958592896}} {"text": "classdef dm_converter_mpc2_legacy < mp.dm_converter_mpc2\n%MP.DM_CONVERTER_MPC2_LEGACY MATPOWER data model converter for MATPOWER case v2.\n\n% MATPOWER\n% Copyright (c) 2021-2022, Power Systems Engineering Research Center (PSERC)\n% by Ray Zimmerman, PSERC Cornell\n%\n% This file is part of MATPOWER.\n% Covered by the 3-clause BSD License (see LICENSE file for details).\n% See https://matpower.org for more info.\n\n% properties\n% end %% properties\n\n methods\n function dm = legacy_user_mod_inputs(obj, dm, mpopt, dc)\n %% pre-process input related to user vars, constraints, costs\n\n %% create (read-only) copies of individual fields for convenience\n mpc = dm.source;\n [~, bus, gen, ~, ~, A, l, u, mpopt, ...\n N, fparm, H, Cw, z0, zl, zu, ~] = opf_args(mpc, mpopt);\n\n %% data dimensions\n nb = size(bus, 1); %% number of buses\n ng = size(gen, 1); %% number of dispatchable injections\n nlin = size(A, 1); %% number of linear user constraints\n nw = size(N, 1); %% number of general cost vars, w\n if dc\n %% reduce A and/or N from AC dimensions to DC dimensions, if needed\n if nlin || nw\n acc = [nb+(1:nb) 2*nb+ng+(1:ng)]; %% Vm and Qg columns\n if nlin && size(A, 2) >= 2*nb + 2*ng\n %% make sure there aren't any constraints on Vm or Qg\n if any(any(A(:, acc)))\n error('mp.dm_converter_mpc2_legacy/legacy_user_mod_inputs: attempting to solve DC OPF with user constraints on Vm or Qg');\n end\n A(:, acc) = []; %% delete Vm and Qg columns\n end\n if nw && size(N, 2) >= 2*nb + 2*ng\n %% make sure there aren't any costs on Vm or Qg\n if any(any(N(:, acc)))\n [ii, jj] = find(N(:, acc));\n ii = unique(ii); %% indices of w with potential non-zero cost terms from Vm or Qg\n if any(Cw(ii)) || (~isempty(H) && any(any(H(:, ii))))\n error('mp.dm_converter_mpc2_legacy/legacy_user_mod_inputs: attempting to solve DC OPF with user costs on Vm or Qg');\n end\n end\n N(:, acc) = []; %% delete Vm and Qg columns\n end\n end\n nv = 0;\n nq = 0;\n else\n nv = nb;\n nq = ng;\n end\n\n %% get number of user vars, check consistency\n nx = nb+nv + ng+nq; %% number of standard OPF control variables\n if nlin\n nz = size(A, 2) - nx; %% number of user z variables\n if nz < 0\n error('mp.dm_converter_mpc2_legacy/legacy_user_mod_inputs: user supplied A matrix must have at least %d columns.', nx);\n end\n else\n nz = 0; %% number of user z variables\n if nw %% still need to check number of columns of N\n if size(mpc.N, 2) ~= nx;\n error('mp.dm_converter_mpc2_legacy/legacy_user_mod_inputs: user supplied N matrix must have %d columns.', nx);\n end\n end\n end\n\n %% package up parameters\n z = struct( 'nz', nz, ... %% num user variables\n 'z0', z0, ...\n 'zl', zl, ...\n 'zu', zu );\n lin = struct( 'nlin', nlin, ... %% num user linear constraints\n 'A', A, ...\n 'l', l, ...\n 'u', u );\n cost = struct( 'nw', nw, ... %% num user cost rows\n 'N', N, ...\n 'Cw', Cw );\n nlc = obj.legacy_user_nln_constraints(dm, mpopt);\n\n if ~isempty(H)\n cost.H = H;\n end\n if ~isempty(fparm)\n cost.dd = fparm(:, 1);\n cost.rh = fparm(:, 2);\n cost.kk = fparm(:, 3);\n cost.mm = fparm(:, 4);\n end\n dm.userdata.legacy_opf_user_mods = struct( ...\n 'z', z, ...\n 'lin', lin, ...\n 'nlc', {nlc}, ...\n 'cost', cost );\n end\n\n function uc = legacy_user_nln_constraints(obj, dm, mpopt)\n mpc = dm.source;\n\n %% check for user-defined nonlinear constraints\n nnle = 0; %% number of nonlinear user-defined equality cons\n nnli = 0; %% number of nonlinear user-defined inequality cons\n if isfield(mpc, 'user_constraints')\n if isfield(mpc.user_constraints, 'nle')\n for k = 1:length(mpc.user_constraints.nle)\n nnle = nnle + mpc.user_constraints.nle{k}{2};\n end\n end\n if isfield(mpc.user_constraints, 'nli')\n for k = 1:length(mpc.user_constraints.nli)\n nnli = nnli + mpc.user_constraints.nli{k}{2};\n end\n end\n end\n\n %% initialize cell array for add_nln_constraint() args\n uc = cell(nnle+nnli, 1);\n\n %% user-defined nonlinear equalities\n if nnle\n for k = 1:length(mpc.user_constraints.nle)\n nlc = mpc.user_constraints.nle{k};\n fcn = eval(['@(x)' nlc{3} '(x, nlc{6}{:})']);\n hess = eval(['@(x, lam)' nlc{4} '(x, lam, nlc{6}{:})']);\n uc{k} = {nlc{1:2}, 1, fcn, hess, nlc{5}};\n end\n end\n\n %% user-defined nonlinear inequalities\n if nnli\n for k = 1:length(mpc.user_constraints.nli)\n nlc = mpc.user_constraints.nli{k};\n fcn = eval(['@(x)' nlc{3} '(x, nlc{6}{:})'])\n hess = eval(['@(x, lam)' nlc{4} '(x, lam, nlc{6}{:})'])\n uc{nnle+k} = {nlc{1:2}, 0, fcn, hess, nlc{5}};\n end\n end\n end\n end %% methods\nend %% classdef\n", "meta": {"author": "MATPOWER", "repo": "matpower", "sha": "7da926d978824bf675a71e0a5cb91f8967f97007", "save_path": "github-repos/MATLAB/MATPOWER-matpower", "path": "github-repos/MATLAB/MATPOWER-matpower/matpower-7da926d978824bf675a71e0a5cb91f8967f97007/lib/+mp/dm_converter_mpc2_legacy.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6893056295505783, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.33657649319348915}} {"text": "function cx = csscal ( n, sa, cx, incx )\n\n%*****************************************************************************80\n%\n%% CSSCAL scales a complex vector by a real constant.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 April 2006\n%\n% Author:\n%\n% MATLAB version by John Burkardt\n%\n% Reference:\n%\n% Jack Dongarra, Jim Bunch, Cleve Moler, Pete Stewart,\n% LINPACK User's Guide,\n% SIAM, 1979,\n% ISBN13: 978-0-898711-72-1,\n% LC: QA214.L56.\n%\n% Charles Lawson, Richard Hanson, David Kincaid, Fred Krogh,\n% Basic Linear Algebra Subprograms for Fortran Usage,\n% 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 vector.\n%\n% Input, real SA, the multiplier.\n%\n% Input, complex CX(*), the vector to be scaled.\n%\n% Input, integer INCX, the increment between successive entries of\n% the vector CX.\n%\n% Output, complex CX(*), the scaled vector.\n%\n cx(1:incx:1+(n-1)*incx) = sa * cx(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_c/csscal.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.615087848460224, "lm_q1q2_score": 0.33629199357533507}} {"text": "function [p_, sdp_, c_, sdc_, dk_, sdk_, aa_, bb_]=mypval2(var1, mati)\n\n % clpvla.m A.Allmann\n % function to calculate the parameters of the modified Omori Law\n %\n %\n %\n % this function is a modification of a program by Paul Raesenberg\n % that is based on Programs by Carl Kisslinger and Yoshi Ogata\n %\n % function finds the maximum liklihood estimates of p,c and k, the\n % parameters of the modifies Omori equation\n % it also finds the standard deviations of these parameters\n %\n % Input: Earthquake Catalog of an Cluster Sequence\n %\n % Output: p c k values of the modified Omori Law with respective\n % standard deviations\n % A and B values of the Gutenberg Relation based on k\n %\n % Create an input window for magnitude thresholds and\n % plot cumulative number versus time to allow input of start and end\n % time\n\n\n\n global backcat ttcat\n global clu1 pyy tmp1 tmp2 tmp3 tmp4 difp\n global xt cumu cumu2\n global p c dk tt pc loop nn pp nit t err1x err2x ieflag isflag\n global cstep pstep tmpcat ts tend eps1 eps2\n global sdc sdk sdp aa bb pcheck loopcheck\n global autop tmeqtime tmvar\n %if var1 == 3\n tmvar=[];\n %input of parameters(Magnitude,Time)\n ZG.newt2=ttcat; %function operates with single cluster\n autop=0;\n if var1==4\n autop=1;\n end\n %calculate start -end time of overall catalog\n t0b = min(ZG.newt2.Date);\n teb = max(ZG.newt2.Date);\n tdiff=days(teb-t0b); %time difference in days\n\n par3=tdiff/100;\n\n par5=par3;\n if par5>.5\n par5=par5/5;\n end\n\n % calculate cumulative number versus time and bin it\n %\n n = ZG.newt2.Count; \n [cumu, xt] = hist(ZG.newt2.Date,(t0b:days(par3):teb));\n [cumu, xt] = hist(days(ZG.newt2.Date-ZG.newt2.Date(1)),(0:par5:tdiff)); %WHY BOTH?\n difp= [0 diff(cumu)];\n cumu2 = cumsum(cumu);\n\n % find start time of time series\n %\n nn=find(cumu==max(cumu));\n nnn=nn(1,1)-2;\n tmvar=1; %temperal variable\n if par3>=1\n tmp3=t0b+nnn*days(par3);\n else\n tmp3=nnn*par5;\n end\n tmp3 = mati;\n tmp2=min(ttcat.Magnitude);\n tmp1=max(ttcat.Magnitude);\n\n tmp3=max(0,tmp3);\n\n tmp4=teb;\n\n %%end\n\n\n %cumputation part after parameter input\n %elseif var1==8 | var1==6 | var1==7\n %set the error test values\n eps1=.0005;\n eps2=.0005;\n\n %set the parameter starting values\n PO=1.1;\n CO=0.1;\n\n %set the initial step size\n pstep=.05;\n cstep=.05;\n pp=PO;\n pc=CO;\n nit=0;\n ieflag=0;\n isflag=0;\n pcheck=false;\n err1x=0;\n err2x=0;\n ts=0.0000001;\n if autop ~= 1 %input was manual\n\n %Build timecatalog\n\n mains=find(ttcat.Magnitude == max(ttcat.Magnitude),1);\n mains=ttcat.subset(mains); %biggest shock in sequence (first one only!)\n assert(mains.Count == 1); \n if par3<0.001\n daycriteria1= ttcat.Date>=days(tmp3)+ttcat.Date(1);\n daycriteria2= ttcat.Date<=days(tmp4)+ttcat.Date(1);\n tmpcat = ttcat.subset(daycriteria1&daycriteria2);\n tmp6=days(tmp3)+ttcat.Date(1);\n else\n tmpcat=ttcat.subset(tmp3<=ttcat.Date & ttcat.Date<=tmp4);\n tmp6=tmp3;\n end\n tmpcat=tmpcat.subset(tmp2<=tmpcat.Magnitude & tmpcat.Magnitude<=tmp1);\n if var1 ==6 || var1==7\n tmpcat=tmpcat.subset(tmpcat.Date>mains.Date);\n tmpcat=[mains; tmpcat];\n ts=(tmp6-mains.Date); %# days\n ts=max(0.0000001,ts)\n end\n tmeqtime=clustime(tmpcat);\n tmeqtime=tmeqtime-tmeqtime(1); %time in days relative to first eq\n tmeqtime=tmeqtime(2:length(tmeqtime));\n\n %automatic estimate works with whole sequence\n else\n tmeqtime=clustime(ttcat);\n tmeqtime=tmeqtime-tmeqtime(1);\n tmeqtime=tmeqtime(2:length(tmeqtime));\n\n end\n\n tp1 = input('tp1= ');\n tp2 = input('tp2= ');\n ts = tp1;\n l = tmeqtime >= tp1 & tmeqtime <= tp2;\n tmeqtime = tmeqtime(l);\n\n\n tend=tmeqtime(length(tmeqtime)); %end time\n\n\n %Loop begins here\n nn=length(tmeqtime);\n loop=0;\n loopcheck=0;\n tt=tmeqtime(nn)+1;\n t=tmeqtime;\n if pc < 0 ; pc = 0.0; end\n if pc <= ts; pc = ts + 0.05;end\n \n MIN_CSTEP = 0.000001;\n MIN_PSTEP = 0.00001;\n \n ploop_c_and_p_calcs(MIN_CSTEP, MIN_PSTEP, true,'kpc'); %call of function who calculates parameters\n\n if loopcheck<500\n %round values on two digits\n p=round(p, -2);\n sdp=round(sdp, -2);\n c=round(c, -3);\n sdc=round(sdc, -3);\n dk=round(dk, -2);\n sdk= round(sdk, -2);\n aa=round(aa, -2);\n bb=round(bb, -2);\n\n\n disp(['p = ' num2str(p) ' +/- ' num2str(sdp)]);\n disp(['c = ' num2str(c) ' +/- ' num2str(sdc)]);\n disp(['k = ' num2str(dk) ' +/- ' num2str(sdk)]);\n disp(['b = ' num2str(bb) ' +/- ' num2str(sdp)]);\n disp(['a = ' num2str(aa) ' +/- ' num2str(sdp)]);\n else\n disp('No result');\n %p = nan;\n %c = nan;\n %k = nan;\n %bb = nan;\n %aa = nan;\n\n % p = nan; sdp = nan;\n end\n if autop~=1\n if par3>=1\n tdiff = round(tmpcat(length(tmpcat(:,1)),3)-tmpcat(1,3));\n else\n tdiff = (tmpcat(length(tmpcat(:,1)),3)-tmpcat(1,3))*365;\n end\n % set arrays to zero\n %\n if par3>=1\n cumu = 0:1:(tdiff/days(par3))+1;\n cumu2 = 0:1:(tdiff/days(par3))-1;\n else\n par5=par3/5;\n cumu = 0:par5:tdiff+2*par3;\n cumu2 = 0:par5:tdiff-1;\n end\n cumu = zeros(size(cumu));\n cumu2 = zeros(size(cumu2));\n %\n end\n tmvar=[];\n %end;\n\n\n p_=p;\n sdp_=sdp;\n c_=c;\n sdc_=sdc;\n dk_=dk;\n sdk_=sdk;\n aa_=aa;\n bb_=bb;\nend\n", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/zmap_deprecated/mypval2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6723316860482763, "lm_q2_score": 0.5, "lm_q1q2_score": 0.33616584302413816}} {"text": "%-------------------------------------------------------------------------------------------------------------------%\n%\n% IB2d is an Immersed Boundary Code (IB) for solving fully coupled non-linear \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: nick.battista@unc.edu\n% Date Created: May 27th, 2015\n% Institution: UNC-CH\n%\n% This code is capable of creating Lagrangian Structures using:\n% \t1. Springs\n% \t2. Beams (*torsional springs)\n% \t3. Target Points\n%\t4. Muscle-Model (combined Force-Length-Velocity model, \"Hill+(Length-Tension)\")\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 (nick.battista@unc.edu) know.\n%\n%--------------------------------------------------------------------------------------------------------------------%\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: updates the target point positions\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction targets = update_Target_Point_Positions(dt,current_time,targets)\n\n\nIDs = targets(:,1); % Stores Lag-Pt IDs in col vector\n%xPts= targets(:,2); % Original x-Values of x-Target Pts.\nyPts= targets(:,3); % Original y-Values of y-Target Pts.\n%kStiffs = targets(:,4); % Stores Target Stiffnesses \n\nN_target = length(targets(:,1)); %Gives total number of target pts!\n\n% NEEDED FOR UPDATE FILE FROM CORAL GEOMETRY! %\nN_half = 90; % # of pts. on ONE tentacle\n\n %frames per second in data\n F = 30.0; \n %pixels per dm in data \n S = 1733.333333333333333333;\n %time in frames (mod one pulse)\n t = F*mod(current_time,2.30);\n tp = F*2.25; \n tend = F*2.30; \n %initial offset from center of the domain in dm\n xoffset = 0.019; \n yoffset = 0.25; \n xoffset2grid1 = 0.2;\n xoffset2grid2 = 0.4;\n\n qc11 = -8.018203211249667e-13;\n qc12 = 1.706310971452060e-10;\n qc13 = -1.371526883228119e-8;\n qc14 = 5.116506115621489e-7;\n qc15 = -8.613944795521634e-6;\n qc16 = 4.951095471423292e-5;\n qc17 = -1.237254488643602e-4;\n qc21 = -1.093988700839764e-10;\n qc22 = 2.370737151797367e-8;\n qc23 = -1.946684756263760e-6;\n qc24 = 7.447999061932255e-5;\n qc25 = -1.285757196003425e-3;\n qc26 = 7.184871148722453e-3;\n qc27 = -2.357284935085283e-2; \n qc31 = -3.111491615328405e-9;\n qc32 = 6.922752279229525e-7; \n qc33 = -5.951659336196739e-5; \n qc34 = 2.461541908755476e-3; \n qc35 = -4.830999119980220e-2; \n qc36 = 3.293063238297988e-1;\n qc37 = -1.893567487439901;\n qc41 = 2.028150369106308e-8;\n qc42 = -4.188949936239104e-6; \n qc43 = 3.237380275082298e-4;\n qc44 = -1.158763275070524e-2; \n qc45 = 1.908244836752949e-1;\n qc46 = -1.142372536532416; \n qc47 = 3.584246435337805;\n\n \n if (t<=tp)\n\n qpoly1=qc17+qc16*t+qc15*t*t+qc14*t*t*t+qc13*t*t*t*t+qc12*t*t*t*t*t+qc11*t*t*t*t*t*t; \n qpoly2=qc27+qc26*t+qc25*t*t+qc24*t*t*t+qc23*t*t*t*t+qc22*t*t*t*t*t+qc21*t*t*t*t*t*t;\n qpoly3=qc37+qc36*t+qc35*t*t+qc34*t*t*t+qc33*t*t*t*t+qc32*t*t*t*t*t+qc31*t*t*t*t*t*t;\n qpoly4=qc47+qc46*t+qc45*t*t+qc44*t*t*t+qc43*t*t*t*t+qc42*t*t*t*t*t+qc41*t*t*t*t*t*t;\n\t\n else \n qpolytf1=qc17+qc16*tp+qc15*tp*tp+qc14*tp*tp*tp+qc13*tp*tp*tp*tp+qc12*tp*tp*tp*tp*tp+qc11*tp*tp*tp*tp*tp*tp;\n qpolytf2=qc27+qc26*tp+qc25*tp*tp+qc24*tp*tp*tp+qc23*tp*tp*tp*tp+qc22*tp*tp*tp*tp*tp+qc21*tp*tp*tp*tp*tp*tp;\n qpolytf3=qc37+qc36*tp+qc35*tp*tp+qc34*tp*tp*tp+qc33*tp*tp*tp*tp+qc32*tp*tp*tp*tp*tp+qc31*tp*tp*tp*tp*tp*tp;\n qpolytf4=qc47+qc46*tp+qc45*tp*tp+qc44*tp*tp*tp+qc43*tp*tp*tp*tp+qc42*tp*tp*tp*tp*tp+qc41*tp*tp*tp*tp*tp*tp;\n\n qpoly1 = qpolytf1*((tend-tp)-(t-tp))/(tend-tp)+qc17*(t-tp)/(tend-tp); \n qpoly2 = qpolytf2*((tend-tp)-(t-tp))/(tend-tp)+qc27*(t-tp)/(tend-tp);\n qpoly3 = qpolytf3*((tend-tp)-(t-tp))/(tend-tp)+qc37*(t-tp)/(tend-tp);\n qpoly4 = qpolytf4*((tend-tp)-(t-tp))/(tend-tp)+qc47*(t-tp)/(tend-tp);\n end\n \n \n \nfor i=1:N_target % Loops over all target points!\n \n shifted_Xt1 = yPts(i)-yoffset;\n \n X_target = xoffset+qpoly4/S-qpoly3*shifted_Xt1+qpoly2*S*shifted_Xt1*shifted_Xt1-qpoly1*S*S*shifted_Xt1*shifted_Xt1*shifted_Xt1;\n \n if i<= N_target/2\n if i<=N_half\n X_target = -X_target+ xoffset2grid1;\n else\n X_target = X_target + xoffset2grid1;\n end\n else\n if i<=N_target/2+N_half\n X_target = -X_target+ xoffset2grid2;\n else\n X_target = X_target + xoffset2grid2;\n end\n end\n targets(IDs(i),2) = X_target; % Store new xVals\n %targets(IDs(i),3) = yPts(IDs(i)); % Store new yVals\n\nend\n\n", "meta": {"author": "nickabattista", "repo": "IB2d", "sha": "392d99c228cc801ff65766889c72e2e1492fe747", "save_path": "github-repos/MATLAB/nickabattista-IB2d", "path": "github-repos/MATLAB/nickabattista-IB2d/IB2d-392d99c228cc801ff65766889c72e2e1492fe747/matIB2d/Examples/Example_Corals/Two_Corals/update_Target_Point_Positions.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7745833945721304, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.3361548361891893}} {"text": "function [x,info] = mgfracLapP1P2(A,b,elem,option,varargin)\n%% MGFRACLAPP1P2 multigrid solvers for fractional Laplacian\n%\n%\n% See also mg\n%\n% Documentation in Help browser ifem mgdoc\n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details.\n\ntic;\n\n%% Size of systems\nNdof = length(b); % number of dof\nN = max(elem(:)); % number of nodes\nNydof = Ndof/N; % number of dof in the extend direction\nNy = (Nydof + 1)/2; % number of nodes in the extend direction\n% NT = size(elem,1); % number of elements\ndim = size(elem,2)-1;\n\n%% Options\n% Assign default values to unspecified parameters\nif ~exist('option','var'), \n option = []; \nend\noption = mgoptions(option,Ndof); % parameters\nx0 = option.x0; \nN0 = option.N0/5; \ntol = option.tol;\nmaxIt = option.solvermaxit; \nmu = option.smoothingstep; \nsolver = option.solver; \n% preconditioner = option.preconditioner;\npreconditioner = 'none';\ncoarsegridsolver = option.coarsegridsolver; \nprintlevel = option.printlevel; \noption.smoother = 'LINE';\n\n%% Fixed dof\nisFixDof = [];\nif isfield(option,'freeDof') % freeDof is given\n isFreeDof = false(N,1); \n isFreeDof(option.freeDof) = true;\n NA = size(A,1);\n if NA > length(option.freeDof)\n isFixDof = true(NA,1);\n isFixDof(isFreeDof) = false;\n end\nelse % Find free dof and eliminate isolated dof\n deg = sum(spones(A)); % degree \n isFreeDof = false(Ndof,1);\n isFreeDof(deg>1) = true;\n isFixDof = ~isFreeDof;\n isFixDof(deg == 0) = false;\nend\nif any(isFixDof) % a bigger matrix is given\n xD = zeros(Ndof,1);\n xD(isFixDof) = b(isFixDof)./diag(A(isFixDof,isFixDof));\n A = A(isFreeDof,isFreeDof);\nend\nif length(b) > sum(isFreeDof)\n b = b(isFreeDof);\nend\nif length(x0) > sum(isFreeDof)\n x0 = x0(isFreeDof);\n option.x0 = x0;\nend\nisFreeNode = isFreeDof(1:N); % default choice for P1\n\n%% Hierarchical Structure of Mesh\n% hierarchical structure for linear element.\nif dim == 2 % 2-D\n [HB, NL, level] = HBstructure(elem,N0); \nend\nif dim == 3 % 3-D\n if nargin > 4\n HBmesh = varargin{end}; % need HB for bisection refinement\n [HB, NL, level] = HBstructure3(elem,N0,HBmesh);\n else % no HBmesh is given. only work for the red uniform refinement\n [HB, NL, level] = HBstructure3(elem,N0);\n end\nend\n\n%% Transfer operators between multilevel meshes for P1 element\n% standard prolongation and restriction operator for P1 element\n[Pro,Res] = transferoperator(HB,NL,isFreeNode); \nfor j = 1:level-1\n Pro{j} = kron(speye(Nydof-1,Nydof-1),Pro{j}); % for each level in y direction\n Res{j+1} = Pro{j}';\nend\nclear HB\n\n%% Matrices in each level\nAi = cell(level,1);\nAi{level} = A; \nfor j = level:-1:2\n Ai{j-1} = Res{j}*Ai{j}*Pro{j-1}; % Ac = Res*Af*Pro\n switch option.smoother\n case 'GS'\n Bi{j} = tril(Ai{j}); % Forward Gauss-Seidel B = D+L\n BBi{j} = triu(Ai{j}); % Backward Gauss-Seidel BB = D+U \n case 'LINE'\n NxNy = size(Ai{j},1);\n Nx = NxNy/(Nydof-1);\n di = zeros(NxNy,4);\n di(:,1) = full(diag(Ai{j}))/2; % half of the main diagoal\n temp = full(diag(Ai{j},Nx)); % next vertex in the extend direction\n di(1:length(temp),2) = temp;\n temp = full(diag(Ai{j},Nx*(Ny-2))); %\n di(1:length(temp),3) = temp;\n temp = full(diag(Ai{j},Nx*(Ny-1))); % middle point in the extend direction\n di(1:length(temp),4) = temp;\n halfBi = spdiags(di,[0 -Nx -Nx*(Ny-2) -Nx*(Ny-1)],NxNy,NxNy);\n Bi{j} = halfBi + halfBi';\n L{j} = chol(Bi{j},'lower');\n R{j} = L{j}';\n% Bi{j} = spdiags(diag(Ai{j}),0,size(Ai{j},1),size(Ai{j},1)); %\n% BBi{j} = Bi{j}; % Jacobi iteration \n end\nend\n\n%% MG cycles\n% initial set up\nk = 1; \nx = x0;\nr = b - A*x;\nnb = norm(b);\nerr = zeros(maxIt,2);\nif nb > eps % nb is non-zero\n err(1,:) = norm(r)/nb; \nelse\n err(1,:) = norm(r);\nend\nswitch solver\n case 'VCYCLE' \n if printlevel >= 1\n fprintf('Multigrid Vcycle Iteration \\n')\n end\n while (max(err(k,:)) > tol) && (k <= maxIt)\n k = k + 1;\n % Step 2: Compute Br by one Vcylce MG\n Br = vcycle(r);\n % Step 3: Correct the solution\n x = x + Br;\n % Step 1: Form residual r\n r = r - A*Br;\n err(k,1) = sqrt(abs(Br'*r/(x'*b))); % approximate relative error in energy norm\n err(k,2) = norm(r)/nb; % relative error of the residual in L2-norm\n if printlevel >= 2\n fprintf('#dof: %8.0u, #nnz: %8.0u, MG Vcycle iter: %2.0u, err = %8.4e\\n',...\n Ndof, nnz(A), k-1, max(err(k,:)));\n end \n end\n err = err(1:k,:);\n itStep = k-1;\n case 'WCYCLE' \n if printlevel >= 1\n fprintf('Multigrid Wcycle Iteration \\n')\n end\n while (max(err(k,:)) > tol) && (k <= maxIt)\n k = k + 1;\n % Step 2: Compute Br by one Vcylce MG\n Br = wcycle(r);\n % Step 3: Correct the solution\n x = x + Br;\n err(k,1) = sqrt(abs(Br'*r/(x'*b))); % approximate relative error in energy norm\n % Step 1: Form residual r\n r = r - A*Br;\n err(k,2) = norm(r)/nb; % relative error of the residual in L2-norm\n if printlevel >= 2\n fprintf('#dof: %8.0u, #nnz: %8.0u, MG Wcycle iter: %2.0u, err = %8.4e\\n',...\n Ndof, nnz(A), k-1, max(err(k,:)));\n end \n end\n err = err(1:k,:);\n itStep = k-1;\nend\n\n%% Krylov space method\n% set up preconditioner\nswitch preconditioner\n case 'V'\n prefunc = @vcycle;\n if printlevel >= 1\n fprintf('Multigrid V-cycle Preconditioner with ')\n end\n case 'W'\n prefunc = @wcycle;\n if printlevel >= 1\n fprintf('Multigrid W-cycle Preconditioner with ')\n end\nend\nswitch solver\n case 'CG'\n if printlevel >= 1\n fprintf('Conjugate Gradient Method\\n')\n end\n [x,flag,err,itStep] = pcg(A,b,tol,maxIt,prefunc,[],x0); \n case 'MINRES'\n if printlevel >= 1\n fprintf('Minimum Residual Method \\n')\n end\n [x,flag,err,itStep] = minres(A,b,tol,maxIt,prefunc,[],x0); \n case 'GMRES'\n if printlevel >= 1\n fprintf('General Minimum Residual Method\\n')\n end\n if isfield(option,'restart')\n restart = option.restart;\n else\n restart = min(N,10);\n end\n [x,flag,err,itStep] = gmres(A,b,restart,tol,maxIt,prefunc,[],x0);\n itStep = (itStep(1)-1)*restart + itStep(2);\nend\n\n%% Modify x to include fix dof\nif any(isFixDof)\n xD(isFreeDof) = x;\n x = xD;\nend\n\n%% Output\nif k > maxIt\n flag = 1;\nelse\n flag = 0;\nend\ntime = toc;\nif printlevel >= 2\n fprintf('#dof: %8.0u, level: %2.0u, coarse grid %2.0u, #nnz: %8.0u\\n',...\n Ndof, level, size(Ai{1},1), nnz(Ai{1}))\nend\nif printlevel >= 1\n fprintf('#dof: %8.0u, #nnz: %8.0u, smoothing: %2.0u, iter: %2.0u, err = %8.4e, time = %4.2g s\\n',...\n Ndof, nnz(A), mu, itStep, max(err(end,:)), time)\nend\nif (flag == 1) && (printlevel>0)\n fprintf('NOTE: the iterative method does not converge! \\n'); \nend\ninfo = struct('solverTime',time,'itStep',itStep,'error',err,'flag',flag,'stopErr',max(err(end,:)));\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% subfunctions vcycle, wcycle, fcycle, bpx\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% Vcycle MG\n function Br = vcycle(r,J) % solve equations Ae = r in each level \n if nargin<=1\n J = level;\n end\n ri = cell(J,1); % record residual in each level\n ei = cell(J,1); % record err in each level\n ri{J} = r;\n for i = J:-1:2\n ei{i} = linesmoother(ri{i},i); % pre-smoothing\n for s = 1:mu-1 % extra mu-1 steps smoothing\n ei{i} = ei{i} + linesmoother(ri{i}-Ai{i}*ei{i},i); \n end\n ri{i-1} = Res{i}*(ri{i} - Ai{i}*ei{i});\n end\n if strcmp(coarsegridsolver,'direct')\n ei{1} = Ai{1}\\ri{1}; % direct solver in the coarest level\n else % iterative solver in the coarest level\n D = spdiags(diag(Ai{1}),0,size(Ai{1},1),size(Ai{1},1));\n [ei{1},flag] = pcg(Ai{1},ri{1},1/size(Ai{1},1),1000,D);\n end\n for i = 2:J\n ei{i} = ei{i} + Pro{i-1}*ei{i-1};\n ei{i} = ei{i} + linesmoother(ri{i}-Ai{i}*ei{i},i);\n for s = 1:mu-1\n ei{i} = ei{i} + linesmoother(ri{i}-Ai{i}*ei{i},i); % post-smoothing\n end\n end\n Br = ei{J};\n end\n\n%% Wcycle MG\n function e = wcycle(r,J) % solve equations Ae = r in each level \n if nargin<=1\n J = level;\n end\n if J == 1\n e = Ai{J}\\r; % exact solver in the coaresest grid\n return\n end\n % fine grid pre-smoothing\n e = Bi{J}\\r; % pre-smoothing\n for s = 1:mu-1 % extra mu-1 steps smoothing\n e = e + Bi{J}\\(r-Ai{J}*e); \n end\n % coarse grid correction twice\n rc = Res{J}*(r - Ai{J}*e);\n ec = wcycle(rc,J-1);\n ec = ec + wcycle(rc - Ai{J-1}*ec,J-1);\n e = e + Pro{J-1}*ec;\n % fine grid post-smoothing\n e = e + BBi{J}\\(r-Ai{J}*e);\n for s = 1:mu-1\n e = e + BBi{J}\\(r-Ai{J}*e); % post-smoothing\n end\n end\n\n%% Line smoother\n function e = linesmoother(r,J)\n% NxNy = length(r);\n% Nx = NxNy/(Ny-1);\n% e = zeros(NxNy,1);\n% for vi = 1:Nx\n% linedof = vi + 0:Nx:NxNy-1;\n% e(linedof) = Ai{J}(linedof,linedof)\\r(linedof);\n% end \n% e = Bi{J}\\r;\n e = R{J}\\(L{J}\\r);\n e = 0.75*e;\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/fracLaplacian/mgfracLapP1P2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.665410572017153, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.3353044931747285}} {"text": "function A11 = synA11Qmax(A00, sizeA11, cmin)\n%-----------------------------------------------------------------------------\n%\n% For each point of colour 11 this function assigns the maximum value at the\n% neighbouring gridpoints of colour 00.\n%\n% Design and implementation by:\n% Dr. Paul M. de Zeeuw http://homepages.cwi.nl/~pauldz/\n% Last Revision: December 12, 2001.\n% (c) 1998-2002 Stichting CWI, Amsterdam\n%-----------------------------------------------------------------------------\n[n00, m00]=size(A00);\nif nargin == 3\n o=[0 0];\n if ~all(size(o) == size(sizeA11))\n error(' synA11Qmax - unexpected dimensions of sizeA11 ')\n else\n clear o;\n n11=sizeA11(1);\n m11=sizeA11(2); \n end\nelseif nargin == 2\n n11=n00-1;\n m11=m00-1;\nelse\n error(' synA11Qmax - number of arguments should be either 2 or 3 ')\nend\n%[n11, m11]=size(A11);\nif m11 == m00-1\n if n11 == n00-1\n S = max(stripL(A00), stripR(A00));\n A11=max(stripD(S), stripU(S));\n elseif n11 == n00\n S = max(stripL(A00), stripR(A00));\n A11=max(S, stripU(extD(S, cmin))); \n else\n disp([' size A00 = ' int2str(size(A00)) ' size A11 = ' int2str([n11 m11])]);\n error(' synA11Qmax - A00 and target A11 do not match ');\n end\nelseif m11 == m00\n if n11 == n00-1\n S = max(stripL(extR(A00, cmin)), A00);\n A11=max(stripD(S), stripU(S));\n elseif n11 == n00\n S = max(stripL(extR(A00, cmin)), A00);\n A11=max(S, stripU(extD(S, cmin))); \n else\n disp([' size A00 = ' int2str(size(A00)) ' size A11 = ' int2str([n11 m11])]);\n error(' synA11Qmax - A00 and target A11 do not match ');\n end\nelse\n disp([' size A00 = ' int2str(size(A00)) ' size A11 = ' int2str([n11 m11])]);\n error(' synA11Qmax - A00 and target A11 do not match ');\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/synA11Qmax.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5964331606115021, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.33530070724483146}} {"text": "% OP_FDOTN_V: assemble the vector r = [r(i)], with r(i) = (f * n, v), with n the normal exterior vector.\n% v should be a scalar-valued function.\n%\n% rhs = op_fdotn_v (spv, msh, coeff);\n%\n% INPUT:\n% \n% spv: structure representing the function space (see sp_vector/sp_eval_boundary_side)\n% msh: structure containing the domain partition and the quadrature rule (see msh_cartesian/msh_eval_boundary_side)\n% coeff: source function evaluated at the quadrature points\n%\n% OUTPUT:\n%\n% rhs: assembled right-hand side\n% \n% Copyright (C) 2009, 2010 Carlo de Falco, Rafael Vazquez\n% Copyright (C) 2011, 2014, 2017 Rafael Vazquez\n%\n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n\n\nfunction rhs = op_fdotn_v (spv, msh, coeff)\n \n coeff = reshape (coeff, [], msh.nqn, msh.nel);\n shpv = reshape (spv.shape_functions, spv.ncomp, msh.nqn, spv.nsh_max, msh.nel);\n\n rhs = zeros (spv.ndof, 1);\n\n for iel = 1:msh.nel\n if (all (msh.jacdet(:,iel)))\n jacdet_weights = reshape (msh.jacdet(:, iel) .* msh.quad_weights(:, iel), 1, msh.nqn);\n\n shpv_iel = reshape (shpv(:, :, :, iel), spv.ncomp, msh.nqn, spv.nsh_max);\n coeff_dot_n = sum (bsxfun (@times, coeff(:,:,iel), msh.normal(:,:,iel)), 1);\n\n coeff_times_jw = bsxfun (@times, jacdet_weights, coeff_dot_n);\n\n aux_val = bsxfun (@times, coeff_times_jw, shpv_iel);\n rhs_loc = sum (sum (aux_val, 1), 2);\n\n indices = find (spv.connectivity(:,iel));\n rhs_loc = rhs_loc(indices); conn_iel = spv.connectivity(indices,iel);\n rhs(conn_iel) = rhs(conn_iel) + rhs_loc(:); \n else\n warning ('geopdes:jacdet_zero_at_quad_node', 'op_fdotn_v: singular map in element number %d', iel)\n end\n end\n\nend\n", "meta": {"author": "rafavzqz", "repo": "geopdes", "sha": "3bfa57b1a38bd4da3148536c9f67cce81afce701", "save_path": "github-repos/MATLAB/rafavzqz-geopdes", "path": "github-repos/MATLAB/rafavzqz-geopdes/geopdes-3bfa57b1a38bd4da3148536c9f67cce81afce701/geopdes/inst/operators/op_fdotn_v.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.3351013626608302}} {"text": "function [mCatDecluster, mCatAfter, vCluster, vCl, vMainCluster] = calc_decluster_ver1(mCatalog,nMethod)\n% function [mCatDecluster, mCatAfter, vCluster, vCl, vMainCluster] = calc_decluster_ver1(mCatalog,nMethod)\n% ----------------------------------------------------------------------------------------------------------\n%\n% Function to decluster earthquake catalog using the windowing technique in space and time by\n% Knopoff & Gardner, GJR astr. Soc, 28, 311-313, 1972\n% Gardner & Knopoff, BSSA, 64,5, 1363-1367, 1974\n% using different windows\n%\n% Incoming variables\n% mCatalog : Incoming earthquake catalog (ZMAP format)\n% nMethod : Window length for declustering (see calc_windows.m)\n% 1: Gardener & Knopoff, 1974\n% 2: Gruenthal pers. communication\n% 3: Urhammer, 1986\n%\n% Outgoing variables:\n% mCatDecluster : Declustered earthquake catalog\n% mCatAfter : Catalog of aftershocks (foreshocks)\n% vCluster : Vector indicating only aftershocks/foreshocls in cluster using a cluster number\n% vCl : Vector indicating all events in clusters using a cluster number\n% vMainCluster : Vector indicating mainshocks of clusters using a cluster number\n%\n% J. Woessner, woessner@seismo.ifg.ethz.ch\n% last update: 31.07.02\n\n%% Added:\n% 31.07.02 Correction for problem of mainshocks with a cluster number as aftershocks belong to two sequences\n% 31.07.02 Corrected fMaxClusterMag(nMagCount) to fMaxClusterMag, since counting variable not needed\n\n%%% Remember: Improve zero length cluster problem, no waitbars yet, time difference mainshock-original event not implemented\n%% This is the version before calc_decluster.m\n\n%% Initialize Vectors and Matrices\nmCatDecluster = [];\nmCatAfter = [];\nvCluster = zeros(length(mCatalog),1); % Initialize all events as mainshock\nvCl = zeros(length(mCatalog),1); % Initialize all events as mainshock\nvSel = zeros(length(mCatalog),1); % Initialize all events as mainshock\nvMainCluster = zeros(length(mCatalog),1); % Initialize\n\n[nXSize, nYsize] = size(mCatalog);\nif nXSize == 0\n disp('Load new catalog');\n return\nend\n\nvDecDate = mCatalog(:,3);\nnCount = 0; % Variable of cluster number\n\nfMagThreshold = min(mCatalog(:,6)); % Set Threshold to minimum magnitude of catalog\nfor nEvent=1:length(mCatalog(:,6))\n %nEvent\n if vCluster(nEvent) == 0\n fMagnitude(nEvent) = mCatalog(nEvent, 6);\n if fMagnitude(nEvent) >= fMagThreshold\n %% Define first aftershock zone and determine magnitude of strongest aftershock\n fMag = fMagnitude(nEvent);\n [fSpace, fTime] = calc_windows(fMagnitude(nEvent), nMethod);\n fSpaceDeg = km2deg(fSpace);\n %% This first if is for events with no location given\n if isnan(mCatalog(nEvent,1))\n %vSel = (vDecDate(:,1)-vDecDate(nEvent,1) >= 0) & (vDecDate(:,1)-vDecDate(nEvent,1) <= fTime & vCluster(nEvent) == 0);\n vSel = (mCatalog(:,3) == mCatalog(nEvent,3));\n else\n vSel = (abs(mCatalog(:,1) - mCatalog(nEvent,1)) <= fSpaceDeg) & (abs(mCatalog(:,2) - mCatalog(nEvent,2)) <= fSpaceDeg)...\n & (vDecDate(:,1)-vDecDate(nEvent,1) >= 0) & (vDecDate(:,1)-vDecDate(nEvent,1) <= fTime & vCluster(nEvent) == 0);\n end\n mTmp = mCatalog(vSel,:);\n %nMagCount = 1; % Variable to determine max. magnitude in a cluster\n if length(mTmp(:,1)) == 1 % Only one event thus no cluster\n fMaxClusterMag = fMag;\n else\n fMaxClusterMag = max(mTmp(:,6));\n % Search for event with bigger magnitude in cluster and resize windows if necessary\n while fMaxClusterMag-fMag > 0\n [fSpace, fTime] = calc_windows(fMaxClusterMag, nMethod);\n fSpaceDeg = km2deg(fSpace);\n vSel = (abs(mCatalog(:,1) - mCatalog(nEvent,1)) <= fSpaceDeg) &...\n (abs(mCatalog(:,2) - mCatalog(nEvent,2)) <= fSpaceDeg)...\n & (vDecDate(:,1)-vDecDate(nEvent,1) >= 0) & (vDecDate(:,1)-vDecDate(nEvent,1) <= fTime & vSel == 1);\n mTmp = mCatalog(vSel,:);\n if isempty(mTmp) % no events in aftershock zone\n break;\n end\n fMag = fMaxClusterMag;\n %nMagCount = nMagCount+1;\n fMaxClusterMag = max(mTmp(:,6));\n if fMaxClusterMag - fMag == 0 % no bigger event in aftershock zone\n break;\n end\n end % End of while\n nCount = nCount + 1; % Set cluster number\n end % End of if\n % Define final aftershock zone if different from original one\n if fMaxClusterMag > fMagnitude(nEvent)\n [fSpace, fTime] = calc_windows(fMaxClusterMag, nMethod);\n fSpaceDeg = km2deg(fSpace);\n % Select events with the Event having the number nEvent, since it is a foreshock (time condition)\n vSel = (abs(mCatalog(:,1) - mCatalog(nEvent,1)) <= fSpaceDeg) & (abs(mCatalog(:,2) - mCatalog(nEvent,2)) <= fSpaceDeg)...\n & (vDecDate(:,1)-vDecDate(nEvent,1) >= 0) & (vDecDate(:,1)-vDecDate(nEvent,1) <= fTime & vCluster(nEvent) == 0);\n end\n [vIndice]=find(vSel); % Vector of indices with Clusters\n vTmpCluster(vIndice,:) = nCount;\n length(vTmpCluster(vIndice,:));\n nI=1; % Variable counting the length of the cluster\n % Select the right numbers for the cluster using the indice vector vIndice\n % First: Insert cluster number after check for length\n % Second: Check if it's a mainshock\n % Third: Keep the former cluster indice;\n while nI <= length(vIndice)\n if (~isempty(vTmpCluster(vIndice(nI))) & length(vTmpCluster(vIndice,:)) > 1 & vCluster(vIndice(nI)) == 0)\n vCluster(vIndice(nI)) = vTmpCluster(vIndice(nI));\n %vEventnr(vIndice,:) = nEvent;\n elseif (~isempty(vTmpCluster(vIndice(nI))) && length(vTmpCluster(vIndice,:)) == 1 && vCluster(vIndice(nI)) == 0)\n vCluster(vIndice(nI)) = 0;\n else\n vCluster(vIndice(nI)) = vCluster(vIndice(nI));\n end\n nI=nI+1;\n end %End of while nI\n %%% Check if the Cluster is not just one event which can happen in case of keeping the former\n %%% cluster number in preceeding while-Loop\n vSelSingle = (vCluster == nCount);\n [vIndiceSingle] = find(vSelSingle);\n %vTmpSingle(vIndiceSingle,:);\n if length(vIndiceSingle) == 1\n nCount\n vIndiceSingle\n vCluster(vIndiceSingle)=0; % Set the event as mainsock\n nCount = nCount-1; % Correct the cluster number down by one\n end\n end % End of if checking magnitude threshold fMagThreshold\n end % End of if chekcing if vCluster == 0\nend % End of FOR over mCatalog\n%nCount\n%% vCL Cluster vector with mainshocks in it; vCluster is now modified to get rid of mainshocks\nvCl = vCluster;\n\n%% Matrix with cluster indice, magnitude and time\nmTmpCat = [vCluster mCatalog(:,6) mCatalog(:,3)];\n%% Delete largest event from cluster series and add to mainshock catalog\nfor nCevent = 1:nCount\n %nCevent\n vSel4 = (mTmpCat(:,1) == nCevent); % Select cluster\n mTmpCat2 = mCatalog(vSel4,:);\n fTmpMaxMag = max(mTmpCat2(:,6)); % Select max magnitude of cluster\n vSelMag = (mTmpCat2(:,6) == fTmpMaxMag);\n [nMag] = find(vSelMag);\n if length(nMag) == 1\n vSel5 = (mTmpCat(:,1) == nCevent & mTmpCat(:,2) == fTmpMaxMag); % Select the event\n [vIndiceMag] = find(vSel5); % Find indice\n vCluster(vIndiceMag) = 0; % Set cluster value to zero, so it is a mainshock\n vMainCluster(vIndiceMag) = nCevent; % Set mainshock vector to cluster number\n elseif isempty(nMag)\n disp('Nothing in ')\n nCevent\n else\n vSel = (mTmpCat(:,1) == nCevent & mTmpCat(:,2) == fTmpMaxMag);\n mTmpCat3 = mCatalog(vSel,:);\n [vIndiceMag] = min(find(vSel)); % Find minimum indice of event with max magnitude in cluster\n vCluster(vIndiceMag) = 0; % Set cluster value to zero, so it is a mainshock\n vMainCluster(vIndiceMag) = nCevent; % Set mainshock vector to cluster number\n end\nend % End of For nCevent\n\n%% Create a catalog of aftershocks (mCatAfter) and of declustered catalog (mCatDecluster)\nvSel = (vCluster(:,1) > 0);\nmCatDecluster=mCatalog(~vSel,:);\nmCatAfter = mCatalog(vSel,:);\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_decluster_ver1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.3342711328762203}} {"text": "%-fanDTasia ToolBox------------------------------------------------------------------\n% This Matlab script is part of the fanDTasia ToolBox: a Matlab library for Diffusion \n% Weighted MRI (DW-MRI) Processing, Diffusion Tensor (DTI) Estimation, High-order \n% Diffusion Tensor Analysis, Tensor ODF estimation, Visualization and more.\n%\n% A Matlab Tutorial on DW-MRI can be found in:\n% http://www.cise.ufl.edu/~abarmpou/lab/fanDTasia/tutorial.php\n%\n%----------------------------------------------\n%openFDT\n%This function opens an image volume in fanDTasia(FDT) file format.\n%fanDTasia is an on-line tool for DTI DW-MRI processing.\n%\n%example 1: A=openFDT('DTI.fdt')\n%A is a 4-dimensional matrix that contains a set of volume images.\n%\n%example 2: [A,B]=openFDT('DTI.fdt')\n%A is a 4-dimensional matrix that contains a set of volume images.\n%B is a Nx4 matrix that contains the gradient orientations and bvalues.\n%B is read from a .txt file with the same name as the fdt file. (In example2: DTI.txt)\n%\n%----------------------------------------------\n%\n%Downloaded from Angelos Barmpoutis' web-page.\n%\n%This program is freely distributable without \n%licensing fees and is provided without guarantee \n%or warrantee expressed or implied. \n%\n%Copyright (c) 2007 Angelos Barmpoutis. \n%\n%VERSION : 20110611\n%\n%-----------------------------------------------\n\nfunction [data,bval]=openFDT(name)\n\nfid=fopen(name,'r','b');\n\nfor i=1:4\n sz(i)=fread(fid,1,'int');\nend\n\n\tdata=zeros(sz(1),sz(2),sz(3),sz(4));\n\tfor c=1:sz(4)\n for z=1:sz(3)\n for y=1:sz(2)\n data(:,y,z,c)=fread(fid,sz(1),'float');\n end\n end\n\tend\n\nfclose(fid);\n\nif nargout==2\n bname=name;\n bname(length(name))='t';\n bname(length(name)-1)='x';\n bname(length(name)-2)='t';\n bval=open_TXT(bname);\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction bval=open_TXT(fnm)\n%this simple function opens a txt file that contain 4 columns of numbers\n%An example of such a text file is here:\n%0.1 100.23 24.3 0.334\n%10.345 0.2 1.23 123.4\n%... as many lines you want.\n\n\nfid=fopen(fnm,'r');\n\nif fid==-1\n fprintf(1,'ERROR: FILE CANNOT BE OPENED\\n');\n return;\nend\n\nbval=[];\nb=zeros(1,4);\nwhile feof(fid)==0\n b=fscanf(fid,'%f',4)';\n bval=[bval;b];\nend\n\nfclose(fid);", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/27462-diffusion-tensor-field-dti-visualization/plotDTI/openFDT.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6334102636778403, "lm_q2_score": 0.5273165233795672, "lm_q1q2_score": 0.3340076981155337}} {"text": "%-------------------------------------------------------------------------------------------------------------------%\n%\n% IB2d is an Immersed Boundary Code (IB) for solving fully coupled non-linear \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: nick.battista@unc.edu\n% Date Created: September 9th, 2016\n% Institution: UNC-CH\n%\n% This code is capable of creating Lagrangian Structures using:\n% \t1. Springs\n% \t2. Beams (*torsional springs)\n% \t3. Target Points\n%\t4. Muscle-Model (combined Force-Length-Velocity model, \"HIll+(Length-Tension)\")\n%\n% One is able to update those Lagrangian Structure parameters, e.g., spring constants, resting %%\tlengths, 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 (nick.battista@unc.edu) know.\n%\n%--------------------------------------------------------------------------------------------------------------------%\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: creates the geometry and prints associated input files\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction Make_Your_Geometry_and_Input_Files()\n\n%\n% Grid Parameters (MAKE SURE MATCHES IN input2d !!!)\n%\nNx = 1024; % # of Eulerian Grid Pts. in x-Direction (MUST BE EVEN!!!)\nLx = 5.0; % Length of Eulerian Grid in x-Direction\ndx = Lx/Nx; % Grid spatial resolution\n\n%\n% Immersed Structure Geometric / Dynamic Parameters %\n%\nds = 0.45*dx; % Lagrangian Pt. Spacing (2x resolution of Eulerian grid)\nstruct_name = 'insect_HT'; % Name for .vertex, .spring, etc files. (must match what's in 'input2d')\n\n\n% Call function to construct geometry\n[xLag,yLag] = give_Me_Immsersed_Boundary_Geometry(ds,Nx,Lx);\nyLag = yLag - 2+0.125;\n\n% Plot Geometry to test\nplot(xLag,yLag,'r-'); hold on;\nplot(xLag,yLag,'*'); hold on;\nxlabel('x'); ylabel('y');\naxis([0 Lx 0 Lx]);\n\n\n\n% Prints .vertex file!\nprint_Lagrangian_Vertices(xLag,yLag,struct_name);\n\n\n% Prints .spring file!\n%k_Spring = 2.5e4; % Spring stiffness (does not need to be equal for all springs)\n%ds_Rest = 0.0; % Spring resting length (does not need to be equal for all springs)\n%print_Lagrangian_Springs(xLag,yLag,k_Spring,ds_Rest,struct_name);\n\n\n% Prints .beam file!\n% k_Beam = 0.5; % Beam Stiffness (does not need to be equal for all beams)\n% C = compute_Curvatures(xLag,yLag) % Computes curvature of initial configuration\n%print_Lagrangian_Beams(xLag,yLag,k_Beam,C,struct_name);\n\n\n% Prints .target file!\nk_Target = 2e5;\nprint_Lagrangian_Target_Pts(xLag,k_Target,struct_name);\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: prints VERTEX points to a file called 'struct_name'.vertex\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction print_Lagrangian_Vertices(xLag,yLag,struct_name)\n\n N = length(xLag); % Total # of Lag. Pts\n\n vertex_fid = fopen([struct_name '.vertex'], 'w');\n\n fprintf(vertex_fid, '%d\\n', N );\n\n %Loops over all Lagrangian Pts.\n for s = 1:N\n X_v = xLag(s);\n Y_v = yLag(s);\n fprintf(vertex_fid, '%1.16e %1.16e\\n', X_v, Y_v);\n end\n\n fclose(vertex_fid);\n\n \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: prints TARGET points to a file called 'struct_name'.target\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction print_Lagrangian_Target_Pts(xLag,k_Target,struct_name)\n\n N = length(xLag);\n\n target_fid = fopen([struct_name '.target'], 'w');\n\n fprintf(target_fid, '%d\\n', N );\n\n %Loops over all Lagrangian Pts.\n for s = 1:N\n fprintf(target_fid, '%d %1.16e\\n', s, k_Target);\n end\n\n fclose(target_fid); \n \n \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: prints SPRING points to a file called 'struct_name'.spring\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction print_Lagrangian_Springs(xLag,yLag,k_Spring,ds_Rest,struct_name)\n\n N = length(xLag);\n\n spring_fid = fopen([struct_name '.spring'], 'w');\n\n fprintf(spring_fid, '%d\\n', N ); % Print # of springs \n\n %SPRINGS BETWEEN VERTICES\n for s = 1:N\n if s < N \n fprintf(spring_fid, '%d %d %1.16e %1.16e\\n', s, s+1, k_Spring, ds_Rest); \n else\n %Case s=N\n fprintf(spring_fid, '%d %d %1.16e %1.16e\\n', s, 1, k_Spring, ds_Rest); \n end\n end\n fclose(spring_fid); \n\n \n \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: prints BEAM (Torsional Spring) points to a file called 'struct_name'.beam\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction print_Lagrangian_Beams(xLag,yLag,k_Beam,C,struct_name)\n\n % k_Beam: beam stiffness\n % C: beam curvature\n \n N = length(xLag); % NOTE: Total number of beams = Number of Total Lag Pts. - 2\n\n beam_fid = fopen([struct_name '.beam'], 'w');\n\n fprintf(beam_fid, '%d\\n', N );\n\n %spring_force = kappa_spring*ds/(ds^2);\n\n %BEAMS BETWEEN VERTICES\n for s = 2:N-1\n if s <= N-1 \n fprintf(beam_fid, '%d %d %d %1.16e %1.16e\\n',s-1, s, s+1, k_Beam, C(s) ); \n else\n %Case s=N\n fprintf(beam_fid, '%d %d %d %1.16e %1.16e\\n',s-1, s, 1, k_Beam, C(s) ); \n end\n end\n fclose(beam_fid); \n \n \n \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: computes \"curvature\" of starting configuration\n% \n% NOTE: not curvature in the traditional geometric sense, in the 'discrete'\n% sense through cross product.\n%\n% NOTE: assumes a CLOSED structure\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction C = compute_Curvatures(xLag,yLag)\n\nN = length(xLag);\nC = zeros( N );\n\n%Note: needs to be done same order as you print .beam file!\nfor i=1:N\n \n % Pts Xp -> Xq -> Xr (same as beam force calc.)\n \n if ( (i > 1) && (i < N) )\n \n Xp = xLag(i-1); Xq = xLag(i); Xr = xLag(i+1);\n Yp = yLag(i-1); Yq = yLag(i); Yr = yLag(i+1);\n \n elseif (i==1)\n \n Xp = xLag(N); Xq = xLag(i); Xr = xLag(i+1);\n Yp = yLag(N); Yq = yLag(i); Yr = yLag(i+1);\n \n elseif (i==N)\n \n Xp = xLag(N-1); Xq = xLag(N); Xr = xLag(1);\n Yp = yLag(N-1); Yq = yLag(N); Yr = yLag(1);\n \n end\n \n C(i) = (Xr-Xq)*(Yq-Yp) - (Yr-Yq)*(Xq-Xp); %Cross product btwn vectors\n \nend\n \n \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: creates the Lagrangian structure geometry\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n \nfunction [xLag,yLag] = give_Me_Immsersed_Boundary_Geometry(ds,Nx,Lx)\n \n% ds: Lagrangian pt. spacing\n% Nx: Eulerian grid resolution\n\n% Gives elliptical subset for tube side\na = 0.5; % semi-major axis (horizontal)\nb = 0.45; % semi-minor axis (vertical) \nang = pi/6; % angle start/cuttoff for ellipse\n[xE,yE] = give_Me_Elliptical_Geometry(ds,a,b,ang);\nxOff = 2*xE(1);\n\n% Gives top and bottom portion of one section of tube\nd = 0.2; % separation distance\nxTube = [xE+3*xOff xE+3*xOff xE+2*xOff xE+2*xOff xE+xOff xE+xOff xE xE]; % top first, then bottom\nxTube = xTube + 1;\nxTube = xTube(end:-1:1); % reverse it!\nyTube = [yE+d/2 -yE-d/2 yE+d/2 -yE-d/2 yE+d/2 -yE-d/2 yE+d/2 -yE-d/2]; % top first, then bottom \nyTube = yTube + Lx/2;\n\n% Give indices for to attach valves\nind_Top = 1; % node index for first point on top (on RHS)\nind_Bot = length(xTube)/8+1; % node index for first point on bottom (on RHS)\n\nxFlat = xTube(ind_Top)-Lx/20:ds:xTube(ind_Top); \nyFlatTop = yTube(ind_Top)*ones(1,length(xFlat));\nyFlatBot = yTube(ind_Bot)*ones(1,length(xFlat)); \n\nxLag = [xTube xFlat xFlat];\nyLag = [yTube yFlatTop yFlatBot];\n\n% Gives valve geometry\n[xV,yV] = give_Valve_Geometry(d,ds);\n\n% TESTING (i.e., PLOT IT, yo!)\n%plot(xTube,yTube,'b*'); hold on\n%len = length(xTube);\n%plot(xTube(len/8+1),yTube(len/8+1),'r*'); hold on\n%plot(xTube(1),yTube(1),'k*'); hold on;\n%axis([0 5 0 5]);\n%pause();\n\n%plot(xV,yV,'g*'); hold on;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: gives valve geometry inside a distance, d, between the edges of\n% the tube\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [xV,yV] = give_Valve_Geometry(d,ds)\n\n% for A*x^2 geometry -> 2 eqns and 2 unknowns\n%y(0) = 0 = 0\n%y(0.9d/2) = A(0.9/2)^2*d^2 = 1.5*d\n%\n% ----> A = 1.5 / ( (0.45)^2 * d )\n%\nA = 1.0 / ( (0.45)^2 * d );\n\nyV = -0:ds/2:0.9/2*d;\nxV = -A*yV.^2;\n\n\n%figure(2)\n%plot(xV,yV,'b*'); hold on;\n%pause();\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: gives elliptical geometry\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [xE,yE] = give_Me_Elliptical_Geometry(ds,a,b,ang)\n\ndtheta = ds/max(a,b); % use minimum of axis lengths\n\nn = 1;\nxE(n) = a*cos(ang); yE(n) = b*sin(ang);\nang_n = ang + dtheta;\n\nwhile ang_n < (pi/2)\n \n n = n+1; % update counter\n xE(n) = a*cos(ang_n); % next xVal along ellipse\n yE(n) = b*sin(ang_n); % next yVal along ellipse\n ang_n = ang_n + dtheta; % update angle\n \nend\nxE(n+1) = a*cos(pi/2);\nyE(n+1) = b*sin(pi/2);\n\nxE = [xE -xE(end-1:-1:1)];\nyE = [yE yE(end-1:-1:1)];\n\nyE = yE - yE(1); % Translate down\n\n%plot(xE,yE,'*'); hold on;\n%axis([-a a -a a]);\n\nxLength = abs( 2*xE(1) );\nfprintf('\\nThe x-Length of the tube section is: %d\\n',xLength);\n\n\n", "meta": {"author": "nickabattista", "repo": "IB2d", "sha": "392d99c228cc801ff65766889c72e2e1492fe747", "save_path": "github-repos/MATLAB/nickabattista-IB2d", "path": "github-repos/MATLAB/nickabattista-IB2d/IB2d-392d99c228cc801ff65766889c72e2e1492fe747/matIB2d/Examples/Example_HeartTube/Insect_Heart/Valveless_Model/Make_Your_Geometry_and_Input_Files.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.661922862511608, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.33354701483387145}} {"text": "function adjList = meshFaceAdjacency(vertices, edges, faces)\n%MESHFACEADJACENCY Compute adjacency list of face around each face.\n%\n%\n% Example\n% % Create a sample 3D mesh\n% [v, e, f] = createDodecahedron;\n% adjList = meshFaceAdjacency(v, e, f);\n% figure; hold on; axis equal; view([100 40]);\n% drawMesh(v, f);\n% % draw sample face in a different color\n% drawMesh(v, f(1, :), 'faceColor', 'b');\n% % draw the neighbors of a sample face\n% drawMesh(v, f(adjList{1}, :), 'faceColor', 'g')\n% \n% \n\n% ------\n% Author: David Legland\n% e-mail: david.legland@grignon.inra.fr\n% Created: 2010-10-04, using Matlab 7.9.0.529 (R2009b)\n% Copyright 2010 INRA - Cepia Software Platform.\n\n\nedgeFaceList = meshEdgeFaces(vertices, edges, faces);\n\n% allocate memory for adjacency list\nnFaces = max(edgeFaceList(:));\nadjList = cell(1, nFaces);\n\n% iterate over edges to populate adjacency list\nfor iEdge = 1:size(edgeFaceList)\n f1 = edgeFaceList(iEdge, 1);\n f2 = edgeFaceList(iEdge, 2);\n adjList{f1} = [adjList{f1} f2];\n adjList{f2} = [adjList{f2} f1];\nend\n", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/z_geom3d/meshes3d/meshFaceAdjacency.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.6187804267137442, "lm_q1q2_score": 0.33351226728867334}} {"text": "% @Author: amishkin\n% @Date: 2018-07-10T13:36:34-07:00\n% @Email: amishkin@cs.ubc.ca\n% @Last modified by: aaronmishkin\n% @Last modified time: 2018-07-25T13:18:48-07:00\n\n% #################################################\n% ############# Reproduce Figure 2(c) #############\n% #################################################\n\n% Load the dataset with a fixed seed.\naddpath(genpath('.'))\n\noutput_dir = './breast_cancer_experiment_data'\nmkdir(output_dir)\n\ndataset_name = 'breast_cancer_scale';\n[y, X, y_te, X_te] = get_data_log_reg(dataset_name, 1);\n[N,D] = size(X);\n\n% Set initial conditions. These will be the same for all methods and restarts.\nmu_start = zeros(D,1);\ns = 1.*ones(D,1);\nsigma_start = diag(1./s);\n\n% Use the same split of the dataset for each random restart.\nrandom_split = 0;\n\n% Run MF_Exact.\nmethod = 'mf_exact'\nnum_restarts = 1;\n\n% List batch sizes and epochs for each batch size.\n% In the case of mf-exact (which is a batch method), the number of epochs controls the number of function\n% evaluations L-BFGS is allowed.\nepoch_list = [500];\n% M_list does not matter for mf-exact because it is a batch method.\nM_list = [1]\n\nrun_experiment(dataset_name, method, M_list, epoch_list, 0, 0, 0, 0, num_restarts, mu_start, sigma_start, random_split, output_dir)\n\n\n% Run Vadam with different minibatch sizes:\nmethod = 'Vadam'\n\n% Define the experiment parameters:\nnum_samples = 1\nbeta = 0.01;\nalpha = 0.01;\ndecay_rate = 0.55 % controls the rate at which alpha and beta decay during training.\n\nnum_restarts = 20;\n\n% List batch sizes and epochs for each batch size.\nM_list = [1,8,16,32,64];\nepoch_list = [10000, 10000, 10000, 10000, 10000];\n\nrun_experiment(dataset_name, method, M_list, epoch_list, alpha, beta, decay_rate, num_samples, num_restarts, mu_start, sigma_start, random_split, output_dir);\n\n% Run VOGN with a minibatch size of one:\nmethod = 'VOGN'\nnum_samples = 1\nbeta = 0.0005;\nalpha = 0.0005;\ndecay_rate = 0;\n\nnum_restarts = 20;\n\n% List batch sizes and epochs for each batch size.\nM_list = [1];\nepoch_list = [2000];\n\nrun_experiment(dataset_name, method, M_list, epoch_list, alpha, beta, decay_rate, num_samples, num_restarts, mu_start, sigma_start, random_split, output_dir);\n\n% generate figure 2(c) using the data from this experiment:\nmake_fig_two_c\n", "meta": {"author": "emtiyaz", "repo": "vadam", "sha": "d8ea6bdc82ac8765b873578660e1d9ba95c701d4", "save_path": "github-repos/MATLAB/emtiyaz-vadam", "path": "github-repos/MATLAB/emtiyaz-vadam/vadam-d8ea6bdc82ac8765b873578660e1d9ba95c701d4/matlab/breast_cancer_experiment.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.3333221631901137}} {"text": "function DCM = spm_dcm_nvc(P)\n% Specify and estimate a DCM for multimodal fMRI and M/EEG\n% FORMAT [DCM] = spm_dcm_nvc(P)\n%\n% Input:\n% -------------------------------------------------------------------------\n% P{1} - SPM structure or location of SPM.mat\n% P{2} - Cell array of VOI filenames (the same order as sources in EEG DCM)\n% P{3} - Location of DCM for M/EEG .mat file or DCM structure\n% P{4} - Model specification for neurovascular coupling (NVC) mechanisms\n% P{5} - Which neuronal populations should drive haemodynamics \n% P{6} - Which fMRI experimental conditions to include\n% P{7} - DCM options\n%\n% Where:\n%\n% P{4} - A cell array of strings with three elements:\n% \n% P{4}{1} - 'pre', 'post' or decomposed ('de') neuronal signals excite \n% NVC. Decomposed means activity is grouped into intrinsic-\n% inhibitory, intrinisic-excitatory and extrinsic-excitatory.\n% P{4}{2} - NVC has the same ('s') or different ('d') parameters for all\n% regions. \n% P{4}{3} - extrinsic and intrinsic ('ext') or only intrinsic ('int') \n% neuronal activity contributes to regional BOLD \n% (for 'post', this should be 'na').\n% \n% Supported options:\n% {'pre','d','int'},{'pre','s','int'}, {'pre','d','ext'},{'pre','s','ext'},\n% {'de','d', 'int'},{'de','d','exc'}, {'de','s','int'}, {'de','s','exc'},\n% {'post','d','na'},{'post','s','na'};\n%\n% Example: P{4} = {'pre', 's', 'int'} means presynaptic neuronal drive\n% (from intrinsic connections only) inputs to a model of neurovascular\n% coupling that has the same parameters for all regions.\n%\n% P{5} - Which neuronal populations should drive haemodynamics, by setting\n% ones or zeros in a vector ordered:\n% [superficial pyramidal, inhibitory, excitatory, deep pyramidal]\n% (default is [1 1 1 1]).\n%\n% Example: [1 0 1 1] means no NVC drive from inhibitory populations.\n%\n% P{6} - Binary vector indicating which experimental conditions to include.\n%\n% P{7} - options structure for DCM for fMRI: \n% options.name % name for the DCM\n% options.maxit % maximum number of iterations\n% options.hE % expected precision of the noise\n% options.hC % variance of noise expectation\n% options.TE % echo time (default: 0.04)\n%\n% Evaluates:\n% -------------------------------------------------------------------------\n% DCM.M % Model structure\n% DCM.Ep % Condition means (parameter structure)\n% DCM.Cp % Conditional covariances\n% DCM.Vp % Conditional variances\n% DCM.Pp % Conditional probabilities\n% DCM.H1 % 1st order hemodynamic kernels\n% DCM.H2 % 2nd order hemodynamic kernels\n% DCM.K1 % 1st order neuronal kernels\n% DCM.K2 % 2nd order neuronal kernels\n% DCM.R % residuals\n% DCM.y % predicted data\n% DCM.T % Threshold for Posterior inference\n% DCM.Ce % Error variance for each region\n% DCM.F % Free-energy bound on log evidence\n% DCM.ID % Data ID\n% DCM.AIC % Akaike Information criterion\n% DCM.BIC % Bayesian Information criterion\n%\n% Notes on parameters:\n% -------------------------------------------------------------------------\n% This scheme estimates DCM.H (haemodynamic parameters) and DCM.J\n% (neurovascular coupling parameters):\n% \n% DCM.Ep.H.transit - transit time (t0)\n% DCM.Ep.H.decay - signal decay d(ds/dt)/ds)\n% DCM.Ep.H.epsilon - ratio of intra- to extra-vascular components of the\n% gradient echo signal\n%\n% DCM.Ep.J - neurovascular coupling parameters. The dimension depends upon \n% the requested model specification. For p populations and n regions:\n%\n% P{7} (DCM.model) dim(J) notes\n% =========================================\n% {'pre' 'd' 'int'} [p n] \n% {'pre' 's' 'int'} [p 1]\n% {'pre' 'd' 'ext'} [p n]\n% {'pre' 's' 'ext'} [p 1]\n% {'de' 's' 'int} [p 2] dim2: intrinsic inhibitory, excitatory\n% {'de' 's' 'ext'} [p 3] dim2: intrinsic inhibitory, excitatory, extrinsic \n% {'de' 'd' 'int} [p 2 n] dim2: intrinsic inhibitory, excitatory\n% {'de' 'd' 'ext'} [p 3 n] dim2: intrinsic inhibitory, excitatory, extrinsic \n% {'post' 's' 'na'} [p 1]\n% {'post' 'd' 'na'} [p n]\n%\n%__________________________________________________________________________\n% Jafarian, A., Litvak, V., Cagnan, H., Friston, K.J. and Zeidman, P., 2019.\n% Neurovascular coupling: insights from multi-modal dynamic causal modelling\n% of fMRI and MEG. arXiv preprint arXiv:1903.07478.\n%\n% Friston, K.J., Preller, K.H., Mathys, C., Cagnan, H., Heinzle, J., Razi, A.\n% and Zeidman, P., 2017. Dynamic causal modelling revisited. Neuroimage.\n%__________________________________________________________________________\n% Copyright (C) 2019 Wellcome Trust Centre for Neuroimaging\n \n% Amirhossein Jafarian\n% $Id: spm_dcm_nvc.m 7735 2019-12-02 09:15:27Z peter $\n\n% Prepare input\n%--------------------------------------------------------------------------\nSPM = P{1};\nxY = P{2};\nMEEG = P{3};\ntry model = P{4}; catch, model = {'pre','d','int'}; end\ntry n_exclude = P{5}; catch, n_exclude = ones(1,4) ; end\ntry sess_exclude = P{6}; catch, sess_exclude = 'not defined' ; end\ntry options = P{7}; catch, options = struct() ; end \n\ntry options.centre; catch, options.centre = 1; end\ntry options.hE; catch, options.hE = 6; end\ntry options.hC; catch, options.hC = 1/128; end\ntry options.maxit; catch, options.maxit = 128; end\ntry options.TE; catch, options.TE = 0.04; end\ntry name=options.name; catch, name = sprintf('DCM_%s',date); end\n\n% Set defaults\n%--------------------------------------------------------------------------\nif (length(n_exclude) < 4 || isempty(n_exclude))\n n_exclude = ones(1,4);\nend\nif isempty(sess_exclude)\n sess_exclude = 'not defined';\nend\n\n% Specify haemodynamic model\n%--------------------------------------------------------------------------\nDCM = spm_dcm_nvc_specify(SPM,xY,MEEG,model,n_exclude,sess_exclude,options);\nn = DCM.n; \nv = DCM.v; \nU.dt = DCM.U.dt; \nU.u = [];\n \n% Prepare fMRI signals \n%--------------------------------------------------------------------------\nY = DCM.Y; \nY.y = spm_detrend(Y.y);\nscale = max(max(Y.y)) - min(min(Y.y));\nscale = 4/max(scale,4);\nY.y = Y.y*scale;\nY.scale = scale;\nif ~isfield(Y,'X0'),Y.X0 = ones(v,1); end\nif ~size(Y.X0,2), Y.X0 = ones(v,1); end\n\n% Set fMRI slice time sampling and echo time\n%--------------------------------------------------------------------------\ntry M.delays = DCM.delays; catch, M.delays = ones(n,1); end\nM.TE = options.TE;\n\n% Set priors\n%--------------------------------------------------------------------------\n[pE,pC,x] = spm_dcm_nvc_priors(DCM);\n\n% Prepare neuronal drive functions\n%--------------------------------------------------------------------------\ninput = spm_dcm_nvc_nd(DCM);\n\n% Set hyperpriors over precision - expectation and covariance\n%--------------------------------------------------------------------------\nhE = sparse(n,1) + DCM.options.hE;\nhC = speye(n,n) * DCM.options.hC;\n\n% Prepare model structure\n%--------------------------------------------------------------------------\nM.IS = @spm_nvc_gen; \nM.x = x; \nM.pE = pE; \nM.pC = pC; \nM.hE = hE; \nM.hC = hC; \nM.m = n; \nM.n = size(spm_vec(x),1);\nM.l = n;\nM.ns = v;\nM.Nmax = options.maxit ;\nM.TE = DCM.TE;\nM.input = input;\nM.Model = model;\nM.nograph = spm('CmdLine');\n\n% Model Identification methods\n% =========================================================================\n[Ep,Cp,Eh,F] = spm_nlsi_GN(M,U,Y);\n\n% Compute the prediction, residuals and error variance\n%--------------------------------------------------------------------------\nyhat = feval(M.IS,Ep,M,U);\nR = Y.y - yhat;\nR = R - Y.X0*spm_inv(Y.X0'*Y.X0)*(Y.X0'*R);\nCe = exp(-Eh);\n\n% Compute variance that is captured by the data\n%--------------------------------------------------------------------------\nPSS = sum(yhat.^2);\nRSS = sum(R.^2);\nD = 100.*PSS./(PSS + RSS);\n\n% Compute kernels\n%--------------------------------------------------------------------------\nH.f = @spm_fx_hdm;\nH.g = @spm_gx_hdm;\nH.x = M.x;\nH.m = n; \n[H0,H1] = spm_kernels(H,Ep.H,64,1/2);\n\n% Compute posterior probabilities per parameter\n%--------------------------------------------------------------------------\nT = full(spm_vec(pE));\nsw = warning('off','SPM:negativeVariance');\nPp = spm_unvec(1 - spm_Ncdf(T,abs(spm_vec(Ep)),diag(Cp)),Ep);\nVp = spm_unvec(full(diag(Cp)),Ep);\nwarning(sw);\ntry M = rmfield(M,'nograph'); end\n\n% Store parameter estimates\n%--------------------------------------------------------------------------\nDCM.M = M;\nDCM.Y = Y;\nDCM.U = U;\nDCM.Ce = Ce;\nDCM.Ep = Ep;\nDCM.Cp = Cp;\nDCM.Pp = Pp;\nDCM.Vp = Vp;\nDCM.H1 = H1;\nDCM.D = D;\nDCM.R = R;\nDCM.y = yhat;\nDCM.t = (1:size(yhat,1))*DCM.Y.dt;\n\n% Compute data ID\n%--------------------------------------------------------------------------\nif isfield(M,'FS')\n try\n ID = spm_data_id(feval(M.FS,Y.y,M));\n catch\n ID = spm_data_id(feval(M.FS,Y.y));\n end\nelse\n ID = spm_data_id(Y.y);\nend\n \n% Store evidence\n%--------------------------------------------------------------------------\nDCM.F = F;\nDCM.ID = ID;\n\n%-Save DCM\n%--------------------------------------------------------------------------\nDCM.name = name; \nsave(DCM.name, 'DCM', spm_get_defaults('mat.format'));\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/toolbox/NVC/spm_dcm_nvc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7341195152660687, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.33274836815365777}} {"text": "function [g1, g2] = simwhiteXsimwhiteKernGradient(simKern1, simKern2, t1, varargin)\n\n% SIMWHITEXSIMWHITEKERNGRADIENT Compute a cross gradient between two\n% SIM-WHITE kernels.\n% FORMAT\n% DESC computes cross gradient of parameters of a cross kernel\n% between two SIM-WHITE kernels for the multiple output kernel. \n% ARG simKern1 : the kernel structure associated with the first SIM-WHITE\n% kernel.\n% ARG simKern2 : the kernel structure associated with the second SIM-WHITE\n% kernel.\n% ARG t1 : inputs for which kernel is to be computed.\n% ARG covGrad : gradient of the objective function with respect to\n% the elements of the cross kernel matrix.\n% RETURN g1 : gradient of the parameters of the first kernel, for\n% ordering see simwhiteKernExtractParam.\n% RETURN g2 : gradient of the parameters of the second kernel, for\n% ordering see simwhiteKernExtractParam.\n%\n% FORMAT\n% DESC computes cross kernel terms between two SIM-WHITE kernels for\n% the multiple output kernel. \n% ARG simKern1 : the kernel structure associated with the first SIM-WHITE\n% kernel.\n% ARG simKern2 : the kernel structure associated with the second SIM-WHITE\n% kernel.\n% ARG t1 : row inputs for which kernel is to be computed.\n% ARG t2 : column inputs for which kernel is to be computed.\n% ARG covGrad : gradient of the objective function with respect to\n% the elements of the cross kernel matrix.\n% RETURN g1 : gradient of the parameters of the first kernel, for\n% ordering see simwhiteKernExtractParam.\n% RETURN g2 : gradient of the parameters of the second kernel, for\n% ordering see simwhiteKernExtractParam.\n%\n% SEEALSO : multiKernParamInit, multiKernCompute, simwhiteKernParamInit,\n% simwhiteKernExtractParam\n%\n% COPYRIGHT : David Luengo, 2009\n\n% KERN\n\n\nif nargin < 5\n t2 = t1;\nelse\n t2 = varargin{1};\nend\ncovGrad = varargin{end};\n\nif size(t1, 2) > 1 | size(t2, 2) > 1\n error('Input can only have one column');\nend\nif simKern1.variance ~= simKern2.variance\n error('Kernels cannot be cross combined if they have different variances.')\nend\n\n% Parameters of the kernels required in the computation\nvariance = simKern1.variance;\nsensitivity1 = simKern1.sensitivity;\nsensitivity2 = simKern2.sensitivity;\ndecay1 = simKern1.decay;\ndecay2 = simKern2.decay;\n\nisStationary = (simKern1.isStationary == true) & (simKern2.isStationary == true);\n\n% Auxiliary constants, vectors and matrices\ng1 = zeros(1,3);\ng2 = zeros(1,3);\n\nT1 = repmat(t1, 1, size(t2, 1));\nT2 = repmat(t2.', size(t1, 1), 1);\nind1 = (T1 < T2);\nind2 = ~ind1;\nDv = decay2 .* ind1 + decay1 .* ind2;\nK1 = exp(-Dv.*abs(T1-T2));\nif (isStationary == false)\n K2 = exp(-(decay1 * T1 + decay2 * T2));\nend\n\nif (isStationary == false)\n % Gradient w.r.t. the decays (D_p and D_q)\n g1(1) = (variance * sensitivity1 * sensitivity2 / (decay1 + decay2)) ...\n * sum(sum((-(K1 - K2)/(decay1 + decay2) ...\n - abs(T1 - T2) .* K1 .* ind2 + T1 .* K2) .* covGrad));\n g2(1) = (variance * sensitivity1 * sensitivity2 / (decay1 + decay2)) ...\n * sum(sum((-(K1 - K2)/(decay1 + decay2) ...\n - abs(T1 - T2) .* K1 .* ind1 + T2 .* K2) .* covGrad));\n % Gradient w.r.t. the variance of the driving process\n g1(2) = (sensitivity1 * sensitivity2 / (decay1 + decay2)) ...\n * sum(sum((K1-K2) .* covGrad));\n g2(2) = 0; % Otherwise it is counted twice\n % Gradient w.r.t. the sensitivities\n g1(3) = (variance * sensitivity2 / (decay1 + decay2)) ...\n * sum(sum((K1-K2) .* covGrad));\n g2(3) = (variance * sensitivity1 / (decay1 + decay2)) ...\n * sum(sum((K1-K2) .* covGrad));\nelse\n % Gradient w.r.t. the decays (D_p and D_q)\n g1(1) = - (variance * sensitivity1 * sensitivity2 / (decay1 + decay2)) ...\n * sum(sum((K1/(decay1 + decay2) + abs(T1 - T2) .* K1 .* ind2) .* covGrad));\n g2(1) = - (variance * sensitivity1 * sensitivity2 / (decay1 + decay2)) ...\n * sum(sum((K1/(decay1 + decay2) + abs(T1 - T2) .* K1 .* ind1) .* covGrad));\n % Gradient w.r.t. the variance of the driving process\n g1(2) = (sensitivity1 * sensitivity2 / (decay1 + decay2)) ...\n * sum(sum(K1 .* covGrad));\n g2(2) = 0; % Otherwise it is counted twice\n % Gradient w.r.t. the sensitivities\n g1(3) = (variance * sensitivity2 / (decay1 + decay2)) ...\n * sum(sum(K1 .* covGrad));\n g2(3) = (variance * sensitivity1 / (decay1 + decay2)) ...\n * sum(sum(K1 .* covGrad));\nend\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/kern/simwhiteXsimwhiteKernGradient.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.33262890651998633}} {"text": " function st = nufft_table_init(om, Nd, Jd, Kd, n_shift, Ld, varargin)\n%function st = nufft_table_init(om, Nd, Jd, Kd, n_shift, Ld, ...)\n%|\n%| Initialize structure for d-dimension NUFFT using table-based interpolator,\n%| This should be called only by nufft_init with its 'table' argument!\n%| (So this m-file belongs in the private directory.)\n%|\n%| in\n%|\tom, Nd, Jd, Kd, n_shift\t\tsee nufft_init.m\n%|\tLd [d]\t\t\t\ttable over-sampling factor(s)\n%|\n%| optional arguments (same as nufft_init.m, to specify interp type)\n%| out\n%|\tst.interp_table\t\tfunction: X = st.interp_table(st, Xk);\n%|\tst.interp_table_adj\tfunction: Xk = st.interp_table_adj(st, Xk);\n%|\tst.phase_shift\t\tphase shift due to n_shift\n%|\tst.*\t\t\tsame as in nufft_init.m\n%|\n%| Copyright 2004-3-30, Jeff Fessler and Yingying Zhang, University of Michigan\n\nif nargin < 5, help(mfilename), error args, end\n\n% dimensionality of input space (usually 2 or 3)\ndd = length(Nd);\nif dd > 1 && length(Ld) == 1\n\tLd = Ld * ones(1,dd); % allow scalar L to be used for all dimensions\nend\nif dd ~= length(Jd) || dd ~= length(Kd) || dd ~= length(Ld)\n\tprintm('dd:'), disp(dd)\n\tprintm('Jd:'), disp(Jd)\n\tprintm('Kd:'), disp(Kd)\n\tprintm('Ld:'), disp(Ld)\n\terror 'inconsistent dim'\nend\nif dd ~= size(om,2), error('omega needs %d columns', dd), end\n\n% D-dim NUFFT structure with desired scaling factors, using fake omega=0\nst = nufft_init(zeros(size(Nd)), Nd, Jd, Kd, 0*n_shift, varargin{:});\nst.p = [];\nst.om = om;\nst.Ld = Ld;\nst.M = size(om,1);\nst.n_shift = n_shift; % trick: store it in structure for history\n\n% phase shift associated with indexing n_shift\n% trick: because we put this phase shift here, we use \"0\" for n_shift below\n% when building the tables. in fact, n_shift definitely cannot be in table.\nif any(n_shift ~= 0)\n\tst.phase_shift = exp(1i * (om * n_shift(:))); % [M 1]\nend\n\n% 1D tables for each dimension\nfor id = 1:dd\n\tJ = Jd(id);\n\tL = Ld(id);\n\tK = Kd(id);\n\n\t% This is a slow and inefficient way to get the table\n\t% since it builds a huge sparse matrix but only uses 1 column!\n\tt0 = [-J*L/2:J*L/2]' / L; % [J*L+1]\n\tif 0\n\t\tom0 = t0 * 2*pi/K; % gam(id)\n\t\ts1 = nufft_init(om0, Nd(id), J, K, ...\n\t\t\t0*n_shift(id), varargin{:}); % user's interpolator\n\t\th0 = full(s1.p(:,1));\n\tend\n\n\t% This efficient way uses only \"J\" columns of sparse matrix!\n\t% The trick to this is to use fake small values for N and K,\n\t% which works for interpolators that depend only on the ratio K/N.\n\tktype = varargin{1};\n\tif 0 && (streq(ktype, 'minmax:kb') || streq(ktype, 'kaiser'))\n\n\t\tif streq(ktype, 'minmax:kb')\n\t\t\targs = {'minmax:user', {st.alpha{id}}, {st.beta{id}}};\n\t\telseif streq(ktype, 'kaiser')\n\t\t\targs = {'kaiser'};\n\t\t\tif length(varargin) > 1, warning 'bug?', end\n\t\telse\n\t\t\terror 'bug'\n\t\tend\n\n\t\tNfake = J;\n\t\tKfake = Nfake * K/Nd(id);\n\t\tt1 = J/2-1 + [0:(L-1)]' / L;\t% [L]\n\t\tom1 = t1 * 2*pi/Kfake;\t\t% \"gam\"\n\t\ts1 = nufft_init(om1, Nfake, J, Kfake, 0, args{:});\n\n\t\th = [];\n\t\tfor jj=J:-1:1\n\t\t\th = [h; full(s1.p(:,jj))]; % stack up pieces\n\t\tend\n\t\th = [h; 0]; % finally J*L+1 long.\n\t\th = h .* exp(1i * pi * t0 * (1/K - 1/Kfake)); % fix phase\n\n\t\tif 0\t% testing\n\t\t\tclf, subplot(211)\n\t\t\tplot(t0, real(h0), 'c-', t0, real(h), 'y.')\n\t\t\tplot(t0, real(h0-h), 'y.')\n\t\t\tsubplot(212)\n\t\t\tplot(t0, imag(h0), 'c-', t0, imag(h), 'y.')\n\t\t\tplot(t0, imag(h0-h), 'y.')\n\t\t\tprintf('diff=%g', max_percent_diff(h0, h))\n\t\t\tkeyboard\n\t\tend\n\t\tst.h{id} = double(h); % table mex files want double\n\n\n\t% This way is \"J times faster\" than the slow way, but still not ideal.\n\t% It works for any user-specified interpolator.\n\telse\n\t\tt1 = J/2-1 + [0:(L-1)]' / L; % [L]\n\t\tom1 = t1 * 2*pi/K; % gam(id)\n\n\t\t% trick: handle {'kaiser', [kb_alf], [kb_m]} in multidim case\n\t\tif streq(varargin{1}, 'kaiser') && length(varargin) == 3\n\t\t\tkb_alf = varargin{2};\n\t\t\tkb_m = varargin{3};\n\t\t\tif any(kb_alf ~= kb_alf(1)) || any(kb_m ~= kb_m(1))\n\t\t\t\terror 'table based needs identical interpolator for each dimension'\n\t\t\tend\n\t\t\tvarargin{2} = kb_alf(1);\n\t\t\tvarargin{3} = kb_m(1);\n\t\tend\n\n\t\ts1 = nufft_init(om1, Nd(id), J, K, 0*n_shift(id), varargin{:});\n\n\t\th = [];\n\t\tfor jj=J:-1:1\n\t\t\th = [h; full(s1.p(:,jj))];\n\t\tend\n\t\th = [h; 0];\n\n\t\tst.h{id} = double(h); % table mex files want double\n\t\tif 0\t% testing\n\t\t\tclf, subplot(211)\n\t\t\tplot(t0, real(h0), 'c-', t0, real(h), 'y.')\n\t\t\tsubplot(212)\n\t\t\tplot(t0, imag(h0), 'c-', t0, imag(h), 'y.')\n\t\t\tprintf('diff=%g', max_percent_diff(h0, h))\n\t\t\tkeyboard\n\t\tend\n\tend\n\n\tif isreal(st.h{id})\n\t\tif J == 1\n\t\t\tst.h{id} = complex(st.h{id});\n\t\telse\n\t\t\twhos\n\t\t\twarning 'real kernel?'\n\t\t\tkeyboard\n\t\tend\n\tend\n\nend\n\n% interface routines\n% st.interp_table = inline('nufft_table_interp(st, Xk)', 'st', 'Xk');\nst.interp_table\t\t= @nufft_table_interp;\nst.interp_table_adj\t= @nufft_table_adj;\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/nufft/nufft_table_init.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6757645879592641, "lm_q2_score": 0.4921881357207955, "lm_q1q2_score": 0.3326033127338017}} {"text": "classdef linop\n%linop A class for linear operators\n \n% written by M. Storath\n% $Date: 2015-10-15 15:07:43 +0200 (Do, 15. Okt 2015) $\t$Revision: 132 $\n\n \n properties\n % function handle for evaluation A * x\n eval;\n % function handle for evaluation A' * x\n ctrans;\n % A'A\n normalOp;\n % true if A'A positive definite\n posdef;\n % true if A'A positive definite\n lseSolver;\n end\n \n methods\n % constructor\n function A = linop(eval, ctrans, varargin)\n % if it is a matrix\n if ~isa(eval, 'function_handle') \n A.eval = @(x) eval * x;\n A.ctrans = @(x) eval' * x;\n M = eval' * eval;\n A.normalOp = @(x) M * x;\n else\n A.eval = eval;\n A.ctrans = ctrans;\n A.normalOp = @(x) A.ctrans(A.eval(x));\n end\n ip = inputParser;\n addParamValue(ip, 'posdef', false);\n addParamValue(ip, 'lseSolver', []);\n parse(ip, varargin{:});\n par = ip.Results;\n A.posdef = par.posdef;\n A.lseSolver = par.lseSolver;\n end\n \n % ctranspose (')\n function C = ctranspose(A)\n C = linop(A.ctrans, A.eval);\n end\n \n % mtimes (*)\n function C = mtimes( A, B )\n if isa(B, 'linop')\n C = linop( @(x) A.eval(B.eval(x)), @(x) B.ctrans(A.ctrans(x)));\n else\n C = A.eval(B);\n end\n end\n \n % size\n function s = size(A)\n %warning('Size is deprecated for class linop');\n s = [1 1];\n end\n \n end\nend\n\n", "meta": {"author": "mstorath", "repo": "Pottslab", "sha": "53571378ef2f60b1104fc8dacc1d8f03427987a9", "save_path": "github-repos/MATLAB/mstorath-Pottslab", "path": "github-repos/MATLAB/mstorath-Pottslab/Pottslab-53571378ef2f60b1104fc8dacc1d8f03427987a9/Auxiliary/Operators/linop.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6261241632752915, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.33260302442763506}} {"text": "%% Copyright (C) 2006 Sylvain Pelissier \n%% Copyright (C) 2015-2016 Colin B. Macdonald \n%%\n%% This program is free software; you can redistribute it and/or modify it under\n%% the terms of the GNU General Public License as published by the Free Software\n%% Foundation; either version 3 of the License, or (at your option) any later\n%% version.\n%%\n%% This program is distributed in the hope that it will be useful, but WITHOUT\n%% ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n%% FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more\n%% details.\n%%\n%% You should have received a copy of the GNU General Public License along with\n%% this program; if not, see .\n\n%% -*- texinfo -*-\n%% @documentencoding UTF-8\n%% @defun dirac (@var{x})\n%% Compute the Dirac delta (generalized) function.\n%%\n%% The Dirac delta ``function'' is a generalized function (or distribution)\n%% which is zero almost everywhere, except at the origin where it is\n%% infinite.\n%%\n%% Examples:\n%% @example\n%% @group\n%% dirac (0)\n%% @result{} Inf\n%% dirac (1)\n%% @result{} 0\n%% dirac ([-10 -1 0 1 inf])\n%% @result{} 0 0 Inf 0 0\n%% @end group\n%% @end example\n%% @seealso{heaviside, @@sym/dirac}\n%% @end defun\n\nfunction y = dirac(x)\n if (nargin ~= 1)\n print_usage ();\n end\n\n if (~isreal (x))\n error ('dirac: X must not contain complex values');\n end\n\n y = zeros (size (x), class (x));\n y(x == 0) = Inf;\n\n y(isnan (x)) = NaN;\nend\n\n\n%!assert (isinf (dirac (0)))\n%!assert (dirac (1) == 0)\n%!assert (isnan (dirac (nan)))\n%!assert (isequaln (dirac ([-1 1 0 eps inf -inf nan]), [0 0 inf 0 0 0 nan]))\n%!error dirac (1i)\n%!assert (isa (dirac (single (0)), 'single'))\n", "meta": {"author": "cbm755", "repo": "octsympy", "sha": "c1ecd1e08f027d5101d0f4250dfc496aa98c8bcd", "save_path": "github-repos/MATLAB/cbm755-octsympy", "path": "github-repos/MATLAB/cbm755-octsympy/octsympy-c1ecd1e08f027d5101d0f4250dfc496aa98c8bcd/inst/dirac.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.3325293159307167}} {"text": "function hmm = updateOmega(hmm,Gamma,residuals,XX,XXGXX,XW,Tfactor,rangeK)\n\nis_gaussian = hmm.train.order == 0; % true if Gaussian observation model is being used\nK = hmm.K; ndim = hmm.train.ndim;\nif nargin < 8 || isempty(rangeK), rangeK = 1:K; end\nif nargin < 7, Tfactor = 1; end\nsetstateoptions\nT = size(residuals,1);\nif isfield(hmm.train,'B'), Q = size(hmm.train.B,2);\nelse Q = ndim; end\n\nif (strcmp(hmm.train.covtype,'uniquediag') || strcmp(hmm.train.covtype,'shareddiag')) ...\n && hmm.train.uniqueAR\n % all are AR and there's a single covariance matrix\n hmm.Omega.Gam_rate = hmm.prior.Omega.Gam_rate;\n for k = rangeK\n if ~isempty(XW)\n XWk = XW(:,:,k);\n else\n XWk = zeros(size(residuals));\n end\n e = (residuals - XWk).^2;\n swx2 = zeros(T,ndim);\n for n=1:ndim\n ind = n:ndim:size(XX,2);\n tmp = XX(:,ind) * hmm.state(k).W.S_W;\n swx2(:,n) = sum(tmp .* XX(:,ind),2);\n end\n hmm.Omega.Gam_rate = hmm.Omega.Gam_rate + ...\n 0.5 * Tfactor * sum( bsxfun(@times, e + swx2, Gamma(:,k)) );\n end\n hmm.Omega.Gam_shape = hmm.prior.Omega.Gam_shape + 0.5 * Tfactor * T;\n \nelseif strcmp(hmm.train.covtype,'uniquediag') || strcmp(hmm.train.covtype,'shareddiag')\n hmm.Omega.Gam_rate(regressed) = hmm.prior.Omega.Gam_rate(regressed);\n for k = rangeK\n if ~isempty(XW)\n XWk = XW(:,:,k);\n else\n XWk = zeros(size(residuals));\n end\n e = (residuals(:,regressed) - XWk(:,regressed)).^2;\n swx2 = zeros(T,ndim);\n if ~isempty(hmm.state(k).W.Mu_W)\n for n = 1:ndim\n if ~regressed(n), continue; end\n if ndim==1\n tmp = XX(:,Sind(:,n)) * hmm.state(k).W.S_W;\n else\n tmp = XX(:,Sind(:,n)) * permute(hmm.state(k).W.S_W(n,Sind(:,n),Sind(:,n)),[2 3 1]);\n end\n swx2(:,n) = sum(tmp .* XX(:,Sind(:,n)),2);\n end\n end\n hmm.Omega.Gam_rate(regressed) = hmm.Omega.Gam_rate(regressed) + ...\n 0.5 * Tfactor * sum( bsxfun(@times, e + swx2(:,regressed), Gamma(:,k)));\n end\n hmm.Omega.Gam_shape = hmm.prior.Omega.Gam_shape + 0.5 * Tfactor * T;\n \nelseif strcmp(hmm.train.covtype,'uniquefull') || strcmp(hmm.train.covtype,'sharedfull')\n hmm.Omega.Gam_rate(regressed,regressed) = hmm.prior.Omega.Gam_rate(regressed,regressed);\n for k = rangeK\n if ~isempty(XW)\n XWk = XW(:,:,k);\n else\n XWk = zeros(size(residuals));\n end\n e = (residuals(:,regressed) - XWk(:,regressed));\n e = (bsxfun(@times,e,Gamma(:,k)))' * e;\n if all(S(:)==1)\n swx2 = zeros(ndim,ndim);\n if ~isempty(hmm.state(k).W.Mu_W)\n for n1=find(regressed)\n for n2=find(regressed)\n if n20\n index1 = (0:hmm.train.pcapred+(~hmm.train.zeromean)-1) * ndim + n1;\n index2 = (0:hmm.train.pcapred+(~hmm.train.zeromean)-1) * ndim + n2;\n else\n index1 = (0:length(orders)*Q+(~hmm.train.zeromean)-1) * ndim + n1;\n index2 = (0:length(orders)*Q+(~hmm.train.zeromean)-1) * ndim + n2;\n index1 = index1(Sind(:,n1)); index2 = index2(Sind(:,n2));\n end\n swx2(n1,n2) = sum(sum(hmm.state(k).W.S_W(index1,index2) .* XXGXX{k}(Sind(:,n1),Sind(:,n2))));\n swx2(n2,n1) = swx2(n1,n2);\n end\n end\n end\n hmm.Omega.Gam_rate(regressed,regressed) = hmm.Omega.Gam_rate(regressed,regressed) ...\n + Tfactor * (e + swx2(regressed,regressed));\n else % multivariate regression model\n index_iv = sum(S,2)>0; % the independent variables\n xdim = sum(index_iv);\n ydim = sum(regressed);\n S_W = hmm.state(k).W.S_W(logical(S(:)),logical(S(:)));\n L = chol(S_W)';\n XGX = (bsxfun(@times,residuals(:,index_iv),Gamma(:,k)))' * residuals(:,index_iv);\n tracesum = zeros(ydim,ydim);\n for iL = 1:xdim*ydim\n vecinvL = reshape(L(:,iL),xdim,ydim);\n tracesum = tracesum + vecinvL'*XGX*vecinvL;\n end\n hmm.Omega.Gam_rate(regressed,regressed) = hmm.Omega.Gam_rate(regressed,regressed) + tracesum + e;\n end\n end\n hmm.Omega.Gam_rate(regressed,regressed) = (hmm.Omega.Gam_rate(regressed,regressed) + ...\n hmm.Omega.Gam_rate(regressed,regressed)') / 2;\n hmm.Omega.Gam_irate(regressed,regressed) = inv(hmm.Omega.Gam_rate(regressed,regressed));\n hmm.Omega.Gam_shape = hmm.prior.Omega.Gam_shape + Tfactor * T;\n \nelse % state dependent\n \n Gammasum = sum(Gamma);\n for k = rangeK\n if ~hmm.train.active, continue; end\n if ~isempty(XW)\n XWk = XW(:,:,k);\n else\n XWk = zeros(size(residuals));\n end\n if train.uniqueAR\n e = (residuals - XWk).^2;\n swx2 = zeros(T,ndim);\n for n = 1:ndim\n ind = n:ndim:size(XX,2);\n swx2(:,n) = sum(XX(:,ind) * hmm.state(k).W.S_W .* XX(:,ind),2);\n end\n hmm.state(k).Omega.Gam_rate = hmm.state(k).prior.Omega.Gam_rate + ...\n 0.5 * Tfactor * sum( bsxfun(@times, e + swx2, Gamma(:,k)) );\n hmm.state(k).Omega.Gam_shape = hmm.state(k).prior.Omega.Gam_shape ...\n + 0.5 * Tfactor * Gammasum(k);\n \n elseif strcmp(train.covtype,'diag')\n e = (residuals(:,regressed) - XWk(:,regressed)).^2;\n swx2 = zeros(T,ndim);\n if ~isempty(hmm.state(k).W.Mu_W)\n for n=1:ndim\n if ~regressed(n), continue; end\n if ndim==1\n swx2(:,n) = sum(XX(:,Sind(:,n)) * hmm.state(k).W.S_W(Sind(:,n),Sind(:,n)) ...\n .* XX(:,Sind(:,n)),2);\n else\n swx2(:,n) = sum(XX(:,Sind(:,n)) * permute(hmm.state(k).W.S_W(n,Sind(:,n),Sind(:,n)),[2 3 1]) ...\n .* XX(:,Sind(:,n)),2);\n end\n end\n end\n hmm.state(k).Omega.Gam_rate(regressed) = hmm.state(k).prior.Omega.Gam_rate(regressed) + ...\n 0.5 * Tfactor * sum( bsxfun(@times, e + swx2(:,regressed), Gamma(:,k)) );\n hmm.state(k).Omega.Gam_shape = hmm.state(k).prior.Omega.Gam_shape + 0.5 * Tfactor * Gammasum(k);\n \n else % full\n if is_gaussian\n if hmm.train.zeromean % If zeromean == 1 for Gaussian model, then XWk=0 and we don't need to subtract at all\n e = residuals(:,regressed);\n else % If zeromean == 0 for Gaussian model, then XWk has all the same rows, and bsxfun() is a fair bit faster\n e = bsxfun(@minus,residuals(:,regressed),XWk(1,regressed));\n end\n else\n e = (residuals(:,regressed) - XWk(:,regressed));\n end\n e = (bsxfun(@times,e,Gamma(:,k)))' * e;\n if all(S(:)==1)\n swx2 = zeros(ndim,ndim);\n if ~isempty(hmm.state(k).W.Mu_W)\n orders = formorders(train.order,train.orderoffset,train.timelag,train.exptimelag);\n if isempty(orders)\n swx2 = hmm.state(k).W.S_W * XXGXX{k};\n else\n for n1=find(regressed)\n for n2=find(regressed)\n if n20\n index1 = (0:hmm.train.pcapred+(~train.zeromean)-1) * ndim + n1;\n index2 = (0:hmm.train.pcapred+(~train.zeromean)-1) * ndim + n2;\n else\n index1 = (0:length(orders)*Q+(~train.zeromean)-1) * ndim + n1;\n index2 = (0:length(orders)*Q+(~train.zeromean)-1) * ndim + n2;\n index1 = index1(Sind(:,n1)); index2 = index2(Sind(:,n2));\n end\n swx2(n1,n2) = sum(sum(hmm.state(k).W.S_W(index1,index2) .* XXGXX{k}(Sind(:,n1),Sind(:,n2))));\n swx2(n2,n1) = swx2(n1,n2);\n end\n end\n end\n end\n hmm.state(k).Omega.Gam_rate(regressed,regressed) = hmm.state(k).prior.Omega.Gam_rate(regressed,regressed) + ...\n Tfactor * (e + swx2(regressed,regressed));\n else % multivariate regression model\n index_iv = sum(S,2)>0; % the independent variables\n xdim = sum(index_iv);\n ydim = sum(regressed);\n S_W = hmm.state(k).W.S_W(logical(S(:)),logical(S(:)));\n L = chol(S_W)';\n XGX = (bsxfun(@times,residuals(:,index_iv),Gamma(:,k)))' * residuals(:,index_iv);\n tracesum = zeros(ydim,ydim);\n for iL = 1:xdim*ydim\n vecinvL = reshape(L(:,iL),xdim,ydim);\n tracesum = tracesum + vecinvL'*XGX*vecinvL;\n end\n \n hmm.state(k).Omega.Gam_rate(regressed,regressed) = tracesum + e + ...\n hmm.state(k).prior.Omega.Gam_rate(regressed,regressed);\n end\n \n hmm.state(k).Omega.Gam_shape = hmm.state(k).prior.Omega.Gam_shape + Tfactor * Gammasum(k);\n hmm.state(k).Omega.Gam_irate(regressed,regressed) = inv(hmm.state(k).Omega.Gam_rate(regressed,regressed));\n \n %if train.FC\n % C0 = hmm.state(k).Omega.Gam_rate(regressed,regressed) / hmm.state(k).Omega.Gam_shape;\n % C = hmm.train.A' * corrcov(hmm.train.A * C0 * hmm.train.A',1) * hmm.train.A;\n % %iC = hmm.train.A' * pinv(corrcov(hmm.train.A * C0 * hmm.train.A'),1e-10) * hmm.train.A;\n % iC = hmm.train.A' * ( (corrcov(hmm.train.A * C0 * hmm.train.A',1)+1e-4*eye(size(hmm.train.A,1))) ... \n % \\ hmm.train.A);\n % hmm.state(k).Omega.Gam_rate(regressed,regressed) = C * hmm.state(k).Omega.Gam_shape;\n % hmm.state(k).Omega.Gam_irate(regressed,regressed) = iC / hmm.state(k).Omega.Gam_shape;\n %end\n \n % ensuring symmetry\n hmm.state(k).Omega.Gam_rate(regressed,regressed) = (hmm.state(k).Omega.Gam_rate(regressed,regressed) + ...\n hmm.state(k).Omega.Gam_rate(regressed,regressed)') / 2;\n hmm.state(k).Omega.Gam_irate(regressed,regressed) = (hmm.state(k).Omega.Gam_irate(regressed,regressed) + ...\n hmm.state(k).Omega.Gam_irate(regressed,regressed)') / 2;\n \n end\n end\n \nend\n\nend\n", "meta": {"author": "OHBA-analysis", "repo": "HMM-MAR", "sha": "bb0433b75482e473980791a2b30afe2012cf6578", "save_path": "github-repos/MATLAB/OHBA-analysis-HMM-MAR", "path": "github-repos/MATLAB/OHBA-analysis-HMM-MAR/HMM-MAR-bb0433b75482e473980791a2b30afe2012cf6578/train/obs/updateOmega.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7090191337850933, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.33238152401711046}} {"text": "function [f, energ, diagn] = scaled_mh(f, opt, gp, x, y, z)\n%SCALED_MH A scaled Metropolis-Hastings sampling for latent values\n%\n% Description\n% [F, ENERG, DIAG] = SCALED_MH(F, OPT, GP, X, Y) takes the\n% current latent values F, options structure OPT, Gaussian\n% process structure GP, inputs X and outputs Y. Samples new\n% latent values and returns also energies ENERG and diagnostics\n% DIAG. The latent values are sampled from their conditional\n% posterior p(f|y,th).\n%\n% The latent values are whitened with the prior covariance\n% before the sampling. This reduces the autocorrelation and\n% speeds up the mixing of the sampler. See (Neal, 1998) for\n% details on implementation.\n%\n% The options structure should include the following fields:\n% repeat - the number of MH-steps before \n% returning a single sample (default 10)\n% sample_latent_scale - the scale for the MH-step (default 0.5)\n%\n% OPT = SCALED_MH() Returns default options\n%\n% OPT = SCALED_MH(OPT) Returns default options for fields not\n% yet set in OPT\n%\n% Reference:\n% \n% Neal, R. M. (1998) Regression and classification using\n% Gaussian process priors (with discussion), in J. M. Bernardo,\n% et al (editors) Bayesian Statistics 6, Oxford University\n% Press, pp. 475-501:\n% \n% See also\n% GP_MC\n%\n% Copyright (c) 1999,2011 Aki Vehtari\n% Copyright (c) 2006-2010 Jarno Vanhatalo\n\n% This software is distributed under the GNU General Public \n% License (version 3 or later); please refer to the file \n% License.txt, included with the software, for details.\n\n% set default options using hmc2_opt\n if nargin<=1\n if nargin==0\n f=scaled_mh_opt();\n else\n f=scaled_mh_opt(f);\n end\n return\n end\n \n [n,nout] = size(y);\n if isfield(gp.lik, 'nondiagW')\n switch gp.lik.type\n case {'LGP', 'LGPC'}\n % Do nothing\n case {'Softmax', 'Multinom'}\n % Do nothing\n otherwise\n nout=length(gp.comp_cf); \n end\n if isfield(gp, 'comp_cf') % own covariance for each ouput component\n multicf = true;\n if length(gp.comp_cf) ~= nout\n error('SCALED_MH: the number of component vectors in gp.comp_cf must be the same as number of outputs.')\n end\n else\n multicf = false;\n end\n end\n f = reshape(f,n,nout);\n\n \n maxcut = -log(eps);\n mincut = -log(1/realmin - 1);\n lvs=opt.sample_latent_scale;\n a = max(min(f, maxcut),mincut);\n \n switch gp.type\n case {'FULL'}\n \n if ~isfield(gp.lik, 'nondiagW') || ismember(gp.lik.type, {'LGP' 'LGPC'})\n [K,C]=gp_trcov(gp, x); \n if isfield(gp,'meanf')\n [H_m,b_m,B_m]=mean_prep(gp,x,[]);\n C = C + H_m'*B_m*H_m;\n end\n L=chol(C)';\n else\n L = zeros(n,n,nout);\n if multicf\n for i1=1:nout\n [tmp, C] = gp_trcov(gp, x, gp.comp_cf{i1});\n L(:,:,i1)=chol(C, 'lower');\n end\n else\n for i1=1:nout\n [tmp, C] = gp_trcov(gp, x);\n L(:,:,i1)=chol(C, 'lower');\n end\n end\n end\n e = -gp.lik.fh.ll(gp.lik, y, f, z);\n ft = zeros(size(y));\n \n % Adaptive control algorithm to find such a value for lvs \n % that the rejection rate of Metropolis is optimal. \n slrej = 0;\n for li=1:100\n for i1 =1:nout\n ft(:,i1)=sqrt(1-lvs.^2).*f(:,i1)+lvs.*L(:,:,i1)*randn(n,1);\n end\n ed = -gp.lik.fh.ll(gp.lik, y, ft, z);\n a=e-ed;\n if exp(a) > rand(1)\n f=ft;\n e=ed;\n lvs=min(1,lvs*1.1);\n else\n lvs=max(1e-8,lvs/1.05);\n end\n end\n opt.sample_latent_scale=lvs;\n % Do the actual sampling \n for li=1:(opt.repeat)\n for i1 =1:nout\n ft(:,i1)=sqrt(1-lvs.^2).*f(:,i1)+lvs.*L(:,:,i1)*randn(n,1);\n end\n ed = -gp.lik.fh.ll(gp.lik, y, ft, z);\n a=e-ed;\n if exp(a) > rand(1)\n f=ft;\n e=ed;\n else\n slrej=slrej+1;\n end\n end\n diagn.rej = slrej/opt.repeat;\n diagn.lvs = lvs;\n diagn.opt=opt;\n energ=[];\n f = f(:)';\n \n case 'FIC'\n u = gp.X_u;\n m = size(u,1);\n % Turn the inducing vector on right direction\n if size(u,2) ~= size(x,2)\n u=u';\n end\n % Calculate some help matrices\n [Kv_ff, Cv_ff] = gp_trvar(gp, x);\n K_fu = gp_cov(gp, x, u);\n K_uu = gp_trcov(gp, u);\n Luu = chol(K_uu)';\n\n % Evaluate the Lambda (La) \n B=Luu\\(K_fu');\n Qv_ff=sum(B.^2)';\n Lav = Cv_ff-Qv_ff;\n sLav = sqrt(Lav);\n \n n=length(y);\n e = -gp.lik.fh.ll(gp.lik, y, f, z);\n\n % Adaptive control algorithm to find such a value for lvs \n % so that the rejection rate of Metropolis is optimal. \n slrej = 0;\n for li=1:100\n ft=sqrt(1-lvs.^2).*f + lvs.*(sLav.*randn(n,1) + B'*randn(m,1));\n ed = -gp.lik.fh.ll(gp.lik, y, ft, z);\n a=e-ed;\n if exp(a) > rand(1)\n f=ft;\n e=ed;\n lvs=min(1,lvs*1.1);\n else\n lvs=max(1e-8,lvs/1.05);\n end\n end\n opt.sample_latent_scale=lvs;\n % Do the actual sampling \n for li=1:(opt.repeat)\n ft=sqrt(1-lvs.^2).*f + lvs.*(sLav.*randn(n,1) + B'*randn(m,1));\n ed = -gp.lik.fh.ll(gp.lik, y, ft, z);\n a=e-ed;\n if exp(a) > rand(1)\n f=ft;\n e=ed;\n else\n slrej=slrej+1;\n end\n end\n diagn.rej = slrej/opt.repeat;\n diagn.lvs = lvs;\n diagn.opt=opt;\n energ=[];\n f = f'; \n \n case 'PIC'\n u = gp.X_u;\n m = size(u,1);\n ind = gp.tr_index;\n if size(u,2) ~= size(x,2)\n u=u';\n end\n \n % Calculate some help matrices\n [Kv_ff, Cv_ff] = gp_trvar(gp, x); % 1 x f vector\n K_fu = gp_cov(gp, x, u); % f x u\n K_uu = gp_trcov(gp, u); % u x u, noiseles covariance K_uu\n Luu = chol(K_uu)';\n \n % Evaluate the Lambda (La) for specific model\n % Q_ff = K_fu*inv(K_uu)*K_fu'\n % Here we need only the diag(Q_ff), which is evaluated below\n B=Luu\\K_fu';\n iLaKfu = zeros(size(K_fu)); % f x u\n for i=1:length(ind)\n Qbl_ff = B(:,ind{i})'*B(:,ind{i});\n [Kbl_ff, Cbl_ff] = gp_trcov(gp, x(ind{i},:));\n La{i} = Cbl_ff - Qbl_ff;\n CLa{i} = chol(La{i})' ;\n end\n \n n=length(y);\n e = -gp.lik.fh.ll(gp.lik, y, f, z);\n\n % Adaptive control algorithm to find such a value for lvs \n % so that the rejection rate of Metropolis is optimal. \n slrej = 0;\n for li=1:100\n sampf = randn(size(f));\n for i=1:length(ind)\n sampf(ind{i},:) = CLa{i}*sampf(ind{i},:);\n end\n ft=sqrt(1-lvs.^2).*f + lvs.*(sampf + B'*randn(m,1));\n at = max(min(ft, maxcut),mincut);\n ed = -gp.lik.fh.ll(gp.lik, y, ft, z);\n a=e-ed;\n if exp(a) > rand(1)\n f=ft;\n e=ed;\n lvs=min(1,lvs*1.1);\n else\n lvs=max(1e-8,lvs/1.05);\n end\n end\n opt.sample_latent_scale=lvs;\n % Do the actual sampling \n for li=1:(opt.repeat)\n sampf = randn(size(f));\n for i=1:length(ind)\n sampf(ind{i},:) = CLa{i}*sampf(ind{i},:);\n end\n ft=sqrt(1-lvs.^2).*f + lvs.*(sampf + B'*randn(m,1));\n at = max(min(ft, maxcut),mincut);\n ed = -gp.lik.fh.ll(gp.lik, y, ft, z);\n a=e-ed;\n if exp(a) > rand(1)\n f=ft;\n e=ed;\n else\n slrej=slrej+1;\n end\n end\n diagn.rej = slrej/opt.repeat;\n diagn.lvs = lvs;\n diagn.opt=opt;\n energ=[];\n f = f'; \n \n case 'CS+FIC'\n u = gp.X_u;\n cf_orig = gp.cf;\n ncf = length(gp.cf);\n n = size(x,1); m = size(u,1);\n\n cf1 = {};\n cf2 = {};\n j = 1;\n k = 1;\n for i = 1:ncf\n if ~isfield(gp.cf{i},'cs')\n cf1{j} = gp.cf{i};\n j = j + 1;\n else\n cf2{k} = gp.cf{i};\n k = k + 1;\n end\n end\n gp.cf = cf1;\n \n % First evaluate the needed covariance matrices\n % if they are not in the memory\n % v defines that parameter is a vector\n [Kv_ff, Cv_ff] = gp_trvar(gp, x); % 1 x f vector\n K_fu = gp_cov(gp, x, u); % f x u\n K_uu = gp_trcov(gp, u); % u x u, noiseles covariance K_uu\n K_uu = (K_uu+K_uu')./2; % ensure the symmetry of K_uu\n Luu = chol(K_uu)';\n\n B=Luu\\(K_fu');\n Qv_ff=sum(B.^2)';\n Lav = Cv_ff-Qv_ff; % 1 x f, Vector of diagonal elements \n gp.cf = cf2;\n K_cs = gp_trcov(gp,x);\n La = sparse(1:n,1:n,Lav,n,n) + K_cs;\n gp.cf = cf_orig;\n \n LD = ldlchol(La);\n sLa = chol(La)';\n \n n=length(y);\n e = -gp.lik.fh.ll(gp.lik, y, f, z);\n\n % Adaptive control algorithm to find such a value for lvs \n % so that the rejection rate of Metropolis is optimal. \n slrej = 0;\n for li=1:100\n ft=sqrt(1-lvs.^2).*f + lvs.*(sLa*randn(n,1) + B'*randn(m,1));\n ed = -gp.lik.fh.ll(gp.lik, y, ft, z);\n a=e-ed;\n if exp(a) > rand(1)\n f=ft;\n e=ed;\n lvs=min(1,lvs*1.1);\n else\n lvs=max(1e-8,lvs/1.05);\n end\n end\n opt.sample_latent_scale=lvs;\n % Do the actual sampling \n for li=1:(opt.repeat)\n ft=sqrt(1-lvs.^2).*f + lvs.*(sLa*randn(n,1) + B'*randn(m,1));\n ed = -gp.lik.fh.ll(gp.lik, y, ft, z);\n a=e-ed;\n if exp(a) > rand(1)\n f=ft;\n e=ed;\n else\n slrej=slrej+1;\n end\n end\n diagn.rej = slrej/opt.repeat;\n diagn.lvs = lvs;\n diagn.opt=opt;\n energ=[];\n f = f';\n \n end\nend\n\nfunction opt = scaled_mh_opt(opt)\n%SCALED_MH_OPT Default options for scaled Metropolis-Hastings sampling\n%\n% Description\n% OPT = SCALED_MH_OPT\n% return default options\n% OPT = SCALED_MH_OPT(OPT)\n% fill empty options with default values\n%\n% The options and defaults are\n% repeat - the number of MH-steps before \n% returning a single sample (default 10)\n% sample_latent_scale - the scale for the MH-step (default 0.5)\n\n if nargin < 1\n opt=[];\n end\n\n if ~isfield(opt,'repeat')\n opt.repeat=10;\n end\n if ~isfield(opt,'sample_latent_scale')\n opt.sample_latent_scale=0.5;\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/scaled_mh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6859494550081926, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.3322602548266198}} {"text": "function [qrs_pos,sign,en_thres] = qrs_detect2(ecg,varargin)\n% QRS detector based on the P&T method. This is an offline implementation\n% of the detector.\n%\n% inputs\n% ecg: one ecg channel on which to run the detector (required)\n% in [mV]\n% varargin\n% THRES: energy threshold of the detector (default: 0.6) \n% [arbitrary units]\n% REF_PERIOD: refractory period in sec between two R-peaks (default: 0.250)\n% in [ms]\n% fs: sampling frequency (default: 1KHz) [Hz]\n% fid_vec: if some subsegments should not be used for finding the\n% optimal threshold of the P&Tthen input the indices of\n% the corresponding points here\n% SIGN_FORCE: force sign of peaks (positive value/negative value).\n% Particularly usefull if we do window by window detection and want to\n% unsure the sign of the peaks to be the same accross\n% windows (which is necessary to build an FECG template)\n% debug: 1: plot to bebug, 0: do not plot\n%\n% outputs\n% qrs_pos: indexes of detected peaks (in samples)\n% sign: sign of the peaks (a pos or neg number)\n% en_thres: energy threshold used\n%\n%\n%\n% Physionet Challenge 2014, version 1.0\n% Released under the GNU General Public License\n%\n% Copyright (C) 2014 Joachim Behar\n% Oxford university, Intelligent Patient Monitoring Group\n% joachim.behar@gmail.com\n%\n% Last updates:\n%\n% 13-09-2014\n% Joachim Behar\n% - bug on refrac period fixed\n% - code a bit more tidy\n% - condition added on flatline detection for overall segment (if flatline \n% then returns empty matrices rather than some random stuff)\n%\n% 15-09-2014\n% Julien Oster\n% Sombrero hat instead of band-pass filter as the prefiltering step.\n%\n% \n% When using this code, please reference the following papers:\n%\n% [1] Behar Joachim, Jonhson Alistair, Clifford Gari D., Oster Julien A\n% Comparison of Single Channel Foetal ECG Extraction Methods. \n% Annals of Biomedical Engineering. 42(6), 1340-53. 2014\n% \n% [2] Johnson Alistair E W, Behar Joachim, Oster Julien and Clifford Gari\n% D. R-Peak Estimation using Multimodal Lead Switching. \n% Accepted for Computing in Cardiology conference 2014.\n%\n%\n% This program is free software; you can redistribute it and/or modify it\n% under the terms of the GNU General Public License as published by the\n% Free Software Foundation; either version 2 of the License, or (at your\n% option) any later version.\n% This program is distributed in the hope that it will be useful, but\n% WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General\n% Public License for more details.\n\n% == managing inputs\nREF_PERIOD = 0.250; \nTHRES = 0.6; \nfs = 1000; \nfid_vec = [];\nSIGN_FORCE = [];\ndebug = 0;\n\nswitch nargin\n case 2\n REF_PERIOD=varargin{1};\n case 3\n REF_PERIOD=varargin{1}; \n THRES=varargin{2};\n case 4\n REF_PERIOD=varargin{1}; \n THRES=varargin{2};\n fs=varargin{3}; \n case 5\n REF_PERIOD=varargin{1}; \n THRES=varargin{2}; \n fs=varargin{3}; \n fid_vec=varargin{4};\n case 6\n REF_PERIOD=varargin{1}; \n THRES=varargin{2}; \n fs=varargin{3};\n fid_vec=varargin{4}; \n SIGN_FORCE=varargin{5};\n case 7\n REF_PERIOD=varargin{1}; \n THRES=varargin{2}; \n fs=varargin{3};\n fid_vec=varargin{4};\n SIGN_FORCE=varargin{5}; \n debug=varargin{6};\n otherwise\n error('qrs_detect: wrong number of input arguments \\n');\nend\n\n\n[a b] = size(ecg);\nif(a>b); NB_SAMP=a; elseif(b>a); NB_SAMP=b; ecg=ecg'; end;\ntm = 1/fs:1/fs:ceil(NB_SAMP/fs);\n\n% == constants\nMED_SMOOTH_NB_COEFF = round(fs/100);\nINT_NB_COEFF = round(7*fs/256); % length is 7 for fs=256Hz\nSEARCH_BACK = 1; % perform search back (FIXME: should be in function param)\nMAX_FORCE = []; % if you want to force the energy threshold value (FIXME: should be in function param)\nMIN_AMP = 0.1; % if the median of the filtered ECG is inferior to MINAMP then it is likely to be a flatline\n % note the importance of the units here for the ECG (mV) \nNB_SAMP = length(ecg); % number of input samples\n\ntry\n % == Bandpass filtering for ECG signal\n % this sombrero hat has shown to give slightly better results than a\n % standard band-pass filter. Plot the frequency response to convince\n % yourself of what it does\n b1 = [-7.757327341237223e-05 -2.357742589814283e-04 -6.689305101192819e-04 -0.001770119249103 ...\n -0.004364327211358 -0.010013251577232 -0.021344241245400 -0.042182820580118 -0.077080889653194...\n -0.129740392318591 -0.200064921294891 -0.280328573340852 -0.352139052257134 -0.386867664739069 ...\n -0.351974030208595 -0.223363323458050 0 0.286427448595213 0.574058766243311 ...\n 0.788100265785590 0.867325070584078 0.788100265785590 0.574058766243311 0.286427448595213 0 ...\n -0.223363323458050 -0.351974030208595 -0.386867664739069 -0.352139052257134...\n -0.280328573340852 -0.200064921294891 -0.129740392318591 -0.077080889653194 -0.042182820580118 ...\n -0.021344241245400 -0.010013251577232 -0.004364327211358 -0.001770119249103 -6.689305101192819e-04...\n -2.357742589814283e-04 -7.757327341237223e-05];\n\n b1 = resample(b1,fs,250);\n bpfecg = filtfilt(b1,1,ecg)';\n \n if (length(find(abs(bpfecg)>MIN_AMP))/NB_SAMP)>0.20\n % if 20% of the samples have an absolute amplitude which is higher\n % than MIN_AMP then we are good to go.\n \n % == P&T operations\n dffecg = diff(bpfecg'); % (4) differentiate (one datum shorter)\n sqrecg = dffecg.*dffecg; % (5) square ecg\n intecg = filter(ones(1,INT_NB_COEFF),1,sqrecg); % (6) integrate\n mdfint = medfilt1(intecg,MED_SMOOTH_NB_COEFF); % (7) smooth\n delay = ceil(INT_NB_COEFF/2); \n mdfint = circshift(mdfint,-delay); % remove filter delay for scanning back through ECG\n\n % look for some measure of signal quality with signal fid_vec? (FIXME)\n if isempty(fid_vec); mdfintFidel = mdfint; else mdfintFidel(fid_vec>2) = 0; end;\n\n % == P&T threshold\n if NB_SAMP/fs>90; xs=sort(mdfintFidel(fs:fs*90)); else xs = sort(mdfintFidel(fs:end)); end;\n\n if isempty(MAX_FORCE)\n if NB_SAMP/fs>10\n ind_xs = ceil(98/100*length(xs)); \n en_thres = xs(ind_xs); % if more than ten seconds of ecg then 98% CI\n else\n ind_xs = ceil(99/100*length(xs)); \n en_thres = xs(ind_xs); % else 99% CI \n end \n else\n en_thres = MAX_FORCE;\n end\n\n % build an array of segments to look into\n poss_reg = mdfint>(THRES*en_thres); \n\n % in case empty because force threshold and crap in the signal\n if isempty(poss_reg); poss_reg(10) = 1; end;\n\n % == P&T QRS detection & search back\n if SEARCH_BACK\n indAboveThreshold = find(poss_reg); % ind of samples above threshold\n RRv = diff(tm(indAboveThreshold)); % compute RRv\n medRRv = median(RRv(RRv>0.01));\n indMissedBeat = find(RRv>1.5*medRRv); % missed a peak?\n % find interval onto which a beat might have been missed\n indStart = indAboveThreshold(indMissedBeat);\n indEnd = indAboveThreshold(indMissedBeat+1);\n\n for i=1:length(indStart)\n % look for a peak on this interval by lowering the energy threshold\n poss_reg(indStart(i):indEnd(i)) = mdfint(indStart(i):indEnd(i))>(0.5*THRES*en_thres);\n end\n end\n\n % find indices into boudaries of each segment\n left = find(diff([0 poss_reg'])==1); % remember to zero pad at start\n right = find(diff([poss_reg' 0])==-1); % remember to zero pad at end\n\n % looking for max/min?\n if SIGN_FORCE\n sign = SIGN_FORCE;\n else\n nb_s = length(left<30*fs);\n loc = zeros(1,nb_s);\n for j=1:nb_s\n [~,loc(j)] = max(abs(bpfecg(left(j):right(j))));\n loc(j) = loc(j)-1+left(j);\n end\n sign = mean(ecg(loc)); % FIXME: change to median? \n end\n\n % loop through all possibilities \n compt=1;\n NB_PEAKS = length(left);\n maxval = zeros(1,NB_PEAKS);\n maxloc = zeros(1,NB_PEAKS);\n%%%%%%%% add two lines\n max_inv_val = zeros(1,NB_PEAKS);\n max_inv_loc = zeros(1,NB_PEAKS);\n for i=1:NB_PEAKS\n if sign>0\n % if sign is positive then look for positive peaks\n [maxval(compt) maxloc(compt)] = max(ecg(left(i):right(i)));\n%%%%%%%%%%%%%%%% add 1 line\n [max_inv_val(compt) max_inv_loc(compt)] = min(ecg(left(i):right(i))); \n else\n % if sign is negative then look for negative peaks\n [maxval(compt) maxloc(compt)] = min(ecg(left(i):right(i)));\n%%%%%%%%%%%%%%%% add 1 line\n [max_inv_val(compt) max_inv_loc(compt)] = max(ecg(left(i):right(i))); \n end\n maxloc(compt) = maxloc(compt)-1+left(i); % add offset of present location\n%%%%%%%%%%%% add 1 line \n max_inv_loc(compt) = max_inv_loc(compt)-1+left(i); % add offset of present location\n\n % refractory period - has proved to improve results\n if compt>1\n%%%%%%%%%%%%%%%% if maxloc(compt)-maxloc(compt-1)=abs(maxval(compt-1))\n elseif maxloc(compt)-maxloc(compt-1)=max(abs(maxval(compt-1)),abs(max_inv_val(compt-1)))\n%%%%%%%%%%%%%%%% add 4 lines and modify the next one \n if abs(maxval(compt)) d )\n error('Invalid number of indices specified: given %d, need no more than %d \\n',mn,d); \n end\n \n idxs=[];\n vals=[];\n for i=1:mn\n if isnumeric(pp{i})\n idxs=[idxs,i];\n vals=[vals,pp{i}];\n end\n end\n \n mn=numel(idxs);\n if(mn < d)\n elem=tt_subtensor(tt,idxs,vals);\n else\n\n % if ( mn == 1 ) %Special case\n % ind=pp{1};\n % if ( is_array(ind) )\n % for i=1:d\n % pp{i}=ind(i);\n % end\n % else\n % pp=ind; %Supposedly it was a cell array of index subsets \n % end\n % end\n\n elem=tt_tensor;\n elem.r=r; \n elem.d=d;\n n0=zeros(d,1);\n for i=1:d\n ind=pp{i};\n if ( strcmp(ind, ':'))\n pp{i}=1:n(i);\n ind=pp{i};\n end\n n0(i)=numel(ind);\n end\n ps1=cumsum([1;n0.*r(1:d).*r(2:d+1)]);\n cr1=zeros(ps1(d+1)-1,1);\n \n for i=1:d\n ind=pp{i}; \n crx=cr(ps(i):ps(i+1)-1);\n crx=reshape(crx,[r(i),n(i),r(i+1)]);\n crx=crx(:,ind,:);\n cr1(ps1(i):ps1(i+1)-1)=crx(:); \n end\n \n if ( prod(n0) == 1 ) %single element\n v=1;\n for i=1:d\n crx=cr1(ps1(i):ps1(i+1)-1); crx=reshape(crx,[r(i),r(i+1)]);\n v=v*crx;\n end\n elem=v;\n else\n elem.n=n0;\n elem.core=cr1;\n elem.ps=ps1;\n end\n \n end\n\n case '.'\n switch s(1).subs\n case 'r'\n elem = tt.r;\n if (numel(s)>1)\n s = s(2:end);\n elem = subsref(elem, s);\n end;\n% if (numel(s)>1)&&(strcmp(s(2).type,'()'))\n% elem = tt.r(s(2).subs{1});\n% else\n% elem=tt.r;\n% end;\n case 'over'\n elem = tt.over;\n if (numel(s)>1)\n s = s(2:end);\n elem = subsref(elem, s);\n end;\n case 'core'\n if (numel(s)>1)&&(strcmp(s(2).type,'()'))\n elem = tt.core(s(2).subs{1});\n else\n elem=tt.core;\n end;\n case 'd'\n elem=tt.d;\n case 'ps'\n elem = tt.ps;\n if (numel(s)>1)\n s = s(2:end);\n elem = subsref(elem, s);\n end;\n\n% if (numel(s)>1)&&(strcmp(s(2).type,'()'))\n% elem = tt.ps(s(2).subs{1});\n% else\n% elem=tt.ps;\n% end;\n case 'n'\n elem = tt.n;\n if (numel(s)>1)\n s = s(2:end);\n elem = subsref(elem, s);\n end;\n\n% if (numel(s)>1)&&(strcmp(s(2).type,'()'))\n% elem = tt.n(s(2).subs{1});\n% else\n% elem=tt.n;\n% end;\n otherwise\n error(['No field ', s.subs, ' is here.']);\n end\n \n case '{}'\n %Return the core in the old (not exactly!!! r1-n-r2 here) format\n pp=s.subs;\n mn=numel(pp);\n if ( mn > 1 )\n error('Invalid number of cores asked');\n end\n elem=core(tt,pp{1});\n \n if (numel(s)>1)\n s = s(2:end);\n elem = subsref(elem, s);\n end;\n% if (pp{1}~=1)\n% elem=permute(elem,[2,1,3]);\n% end;\n \n otherwise\n error('Invalid subsref.');\nend\nend\n", "meta": {"author": "oseledets", "repo": "TT-Toolbox", "sha": "1b87616b1e84de89699697fe196eba814aabe954", "save_path": "github-repos/MATLAB/oseledets-TT-Toolbox", "path": "github-repos/MATLAB/oseledets-TT-Toolbox/TT-Toolbox-1b87616b1e84de89699697fe196eba814aabe954/@tt_tensor/subsref.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6113819591324416, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.3318968176070757}} {"text": "function [ClusterID,EventType,AlgoInfo] = clusterSLIDERmag(ShortCat,MainMag,BackTime,ForeTime,MinRad,MagRadScale,MagRadConst)\n\n\t% Example [mCatclus] = clusterSTEPmag(mCatalog, 1.95, 1.95, 1984, 1, 1);\n\t\n\t% code to cluster catalog with spatial windows according to STEP forecasting model \n\t% with sliding windows of t1 backwards in time and t2 forward in time\n\t% starting with the largest earthquake in the catalog\n\t\n\t%\n\t% Input parameters:\n\t% mCatalog Earthquake catalog\n\t% Mainmag minimum mainmag magnitude\n\t% Mc Completeness magnitude\n\t% startyear\n\t% t1 time before an earthquake in days\n\t% t2 time window following an earthquake in days\n\t%\n\t% Output parameters:\n\t% fBValue mCatclus: The clustered catalog for further anaysis\n\t%\n\t% Annemarie Christophersen, 31. January 2008\n\t\n\t\n\t% Code written for catalogue under zmap, thus the input\n\t% catalogue is in the variable a, where\n\t% column 1: longitude\n\t% column 2: latitude\n\t% column 3: year (decimal year, including seconds)\n\t% column 4: month\n\t% column 5: day\n\t% column 6: magnitude\n\t% column 7: depth\n\t% column 8: hour\n\t% column 9: minute\n\t% column 10: seconds\n\t% column 11-23 not important for clustering and cluster analysis\n\t% column 24: SCSN flag for event type (l=local, r=regional, q=quarry)\n\t\n\t% variables used\n\t% mc completeness magnitude\n\t% twindow duration in time in which to look for related events\n\t\n\t\n\t%Converted for MapSeis by DE 21.6.2012\n\t\n\t%may make this switchable if needed\n\tRounding=true;\n\t\n\n\t%init work arrays\n\tnumEvents = length(ShortCat);\n\tWorkArray=zeros(numEvents,4);\n\tWorkArray(:,1)= (1:numEvents)'; %introduce column 11 with row number\n\t\n\t%init output\n\tClusterID=nan(numEvents,1);\n\t%EventType=ones(numEvents,1);\n\tEventType = categorical(ones(numEvents,1),...\n\t\t[0 1 2 3],...\n {'unclassified','single event','mainshock','aftershock'}); \n\tInitEvent=false(numEvents,1);\n\tAlgoInfo=[];\n\t\n\t%InitEvent is currently not directly supported by mapseis, but will be \n\t%added to AlgoInfo, so it can be used by specialiced algorithms\n\n\tclusterno = 1;\n\n\n\t%Dtafter = t2/365; %30 days in decimal years\n\t%Dtbefore = t1/365; %2 days in decimal years\n\tclusterno = 1;\n\t\n\n\t\n\t\n\twhile any(WorkArray(:,2)==0)\n\t\tnotClustered=WorkArray(:,2)==0;\n\t \n\t\t[maxmag IDX]=max(ShortCat(notClustered,5)); %the magnitude of the largest earthquake not yet clustered\n\t\tmaxmag=maxmag(1); %could have mor than one maximum afterall\n\t\tNrInGame=WorkArray(notClustered,1);\n\t\tActualIndex=NrInGame(IDX(1));\n\t\t\n\t \tlino = ActualIndex;\n\t \tWorkArray(lino,2)=clusterno; %write cluster number into column 12\n\t \tsearchradius=max(MinRad, 10^(MagRadScale*maxmag-MagRadConst)); %calculate search radius\n\t \n\t\t%get data of the new event\n\t\ttref = ShortCat(lino,4); %set reference time\n\t\tlatref = ShortCat(lino,2); %set reference latitude\n\t\tlonref = ShortCat(lino,1); %set reference longitude\n\t\t\n\t\t%search for earthquakes before, extend by sliding time windows of t1\n\t\teventsDtbefore=(ShortCat(:,4) > tref-BackTime & ShortCat(:,4) < tref);\n\t\teventsbefore = sum(eventsDtbefore);\n\t\tlinobefore = lino-eventsbefore;\n\t\t \n\t\t \n\t\t \n\t\t%%That did not work like it was intended\n\t\t%%--------------------------------------\n\t\t \n\t\t% for i=linobefore:lino\n\t\t\t% if (b(i,12) == 0) % don't bother if event already clustered\n\t\t\t % edist = deg2km(distance(latref,lonref,ShortCat(i,2),ShortCat(i,1))); %calculate distance to mainshock\n\t\t\t % if (edist <= searchradius)\n\t\t\t\t% WorkArray(i,2)=clusterno;\n\t\t\t\t% %make this event new tref and search for events before\n\t\t\t\t% tref=ShortCat(i,4);\n\t\t\t\t% eventsDtbefore=(ShortCat(:,4) > tref-BackTime & ShortCat(:,4) < tref);\n\t\t\t\t% eventsbefore = length(b(eventsDtbefore,1));\n\t\t\t\t% linobefore = max(1, i-eventsbefore);\n\t\t\t\t% i=linobefore; %is this the right way to restart loop at linobefore?\n\t\t\t % end\n\t\t\t% end\n\t\t% end %this could now have an earlier linebefore and will loop up to lino \n\t\t% % where lino remains the number of mainshoc\n\t\t% % now look for later earthquakes\n\t\t \n\t\t%old version whould not work, for \"borders\" once set, will stay as the are;\n\t\ti=linobefore;\n\t\twhile i<=lino\n\t\t\tif WorkArray(i,2)==0\n\t\t\t\tedist = deg2km(distance(latref,lonref,ShortCat(i,2),ShortCat(i,1))); %calculate distance to mainshock\n\t\t\t\tif (edist <= searchradius)\n\t\t\t\t\tWorkArray(i,2)=clusterno;\n\t\t\t\t\t%make this event new tref and search for events before\n\t\t\t\t\ttref=ShortCat(i,4);\n\t\t\t\t\teventsDtbefore=(ShortCat(:,4) > tref-BackTime & ShortCat(:,4) < tref);\n\t\t\t\t\teventsbefore = sum(eventsDtbefore);\n\t\t\t\t\tlinobefore = max(1, i-eventsbefore);\n\t\t\t\t\ti=linobefore; %Now it does restart \n\t\t\t\t\t\n\t\t\t\telse\n\t\t\t\t\ti=i+1;\n\t\t\t\tend\n\t\t\telse\n\t\t\t\ti=i+1;\n\t\t\tend\n\t\t\t\n\t\tend\n\t \n\t \n\t\n\t\ttref=ShortCat(lino,4); %reset reference time to mainshock\n\t\t\n\t\twhile (lino < numEvents+1) && ShortCat(lino,4) < (tref+ForeTime) \n\t\t\tif WorkArray(lino,2) == 0\n\t\t\t\tedist = deg2km(distance(latref,lonref,ShortCat(lino,2),ShortCat(lino,1)));\n\t\t\t\tif (edist <= searchradius)\n\t\t\t\t\tWorkArray(lino,2)=clusterno;\n\t\t\t\n\t\t\t\t\t%Not needed already cutted\n\t\t\t\t\t%if (ShortCat(lino,6) > Mc)\n\t\t\t\t\ttref=ShortCat(lino,4); %set reference time to new earthquake in cluster\n\t\t\n\t\t\t\tend\n\t\t\t\tlino=lino+1;\n\t\t\tend\n\t\tend\n\t\t\n\t\t\n\t\t\n\t\tclusterno=clusterno+1;\n\t\t\n\t\t\n\tend\n\t\n\t%Output clustered matrix\n\t% column 1: longitude\n\t% column 2: latitude\n\t% column 3: year (decimal year, including seconds)\n\t% column 4: month\n\t% column 5: day\n\t% column 6: magnitude\n\t% column 7: depth\n\t% column 8: hour\n\t% column 9: minute\n\t% column 10: seconds\n\t% column 11: line number\n\t% column 12: cluster number\n\t% column 13: mainshock with its cluster number\n\t% column 14: initiating event cluster number\n\t\n\tif Rounding\n\t\tShortCat(:,5)=round(ShortCat(:,5)*10)/10;% round magnitudes to 0.1\n\tend\n\t\n\t%may not be needed anymore -> it is needed\n\tWorkArray(:,1)= 1:length(ShortCat)'; %introduce column 1 with row number\n\n\t%WorkArray(WorkArray(:,2)==0,2)=nan;\n\tUsedCluster=unique(WorkArray(~isnan(WorkArray(:,2))&WorkArray(:,2)~=0,2));\n\tclusterno=1;\n\t\n\t\n\tdisp(numel(UsedCluster));\n\t\n\tfor i=UsedCluster'\n\t\tinCluster = WorkArray(:,2)==i;\n\t\t\n\t\tif sum(inCluster) >1\n\t\t\t%A real cluster\n\t\t\t\n\t\t\t%First mark all as Events of the cluster and as Aftershocks\n\t\t\tClusterID(inCluster)=clusterno;\n\t\t\tEventType(inCluster)='aftershock';\n\t\t\t\n\t\t\t%find the first of the largest events label it as mainshock\n\t\t\t[MaxMag IDX] = max(ShortCat(inCluster,5));\n\t\t\tavailIndex=WorkArray(inCluster,1);\n\t\t\tMrMaxMag=availIndex(IDX(1));\n\t\t\tEventType(MrMaxMag)='mainshock';\n\t\t\t\n\t\t\t%Mark initial event\n\t\t\t[MinTime IDX] = min(ShortCat(inCluster,4));\n\t\t\tavailIndex=WorkArray(inCluster,1);\n\t\t\tMrInit=availIndex(IDX(1));\n\t\t\tInitEvent(MrInit)=true;\n\t\t\t\n\t\t\tclusterno=clusterno+1;\n\t\t\t\n\t\telseif sum(inCluster)==1\n\t\t\t%only one event\n\t\t\tClusterID(inCluster)=nan;\n\t\t\tEventType(inCluster)='single event';\n\t\t\t\n\t\t\t%clusterno=clusterno+1;\n\t\t\t\n\t\tend\n\t\t\n\t\t\n\t\t\n\tend\n\t\n\t%And set all not assign clusters to NaN and 1\n\tnotInClust=WorkArray(:,2)==0;\n\tClusterID(notInClust)=nan;\n\tEventType(notInClust)='single event'\n\t\n\t\n\t\n\t%And finally the AlgoInfo\n\tParamInput=struct(\t'MainMag',MainMag,...\n\t\t\t\t'BackTime',BackTime,...\n\t\t\t\t'ForeTime',ForeTime,...\n\t\t\t\t'MinRad',MinRad,...\n\t\t\t\t'MagRadScale',MagRadScale,...\n\t\t\t\t'MagRadConst',MagRadConst);\n\t\n\tAlgoInfo.Type='SLIDER-Magnitude-mapseis-v1';\n\tAlgoInfo.UsedConfig=ParamInput;\n\tAlgoInfo.CalculationDate=date;\n\tAlgoInfo.InitialEvents=InitEvent;\n\tAlgoInfo.WorkArray=WorkArray;\n\t\nend\t\n", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/src/+declustering/clusterSLIDERmag.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.8221891218080991, "lm_q2_score": 0.4035668537353746, "lm_q1q2_score": 0.3318082770635452}} {"text": "% Q = vbfa(D, Y, W_module, X_module, noise_module, ...)\n% \n% Variational Bayesian (VB) factor analysis (FA) learning algorithm with\n% changeable modules for the latent variables.\n\nfunction Q = vbfa(D, Y, W_module, X_module, noise_module, varargin)\n\n[M,N] = size(Y);\n\noptions = struct('maxiter', 100, ...\n 'update_x', 1, ...\n 'update_w', 1, ...\n 'update_noise', 1, ...\n 'rotate', 1, ...\n 'rotation_checkgrad', false, ...\n 'rotation_show', false, ...\n 'rotation_maxiter', 10, ...\n 'debug', false, ...\n 'autosave', false,...\n 'autosavefile', 'vbfa_autosave');\n\n[options, errmsg] = argparse(options, varargin{:});\nerror(errmsg);\n\n% Initialize\ndisp('Initializing variables..')\n[Q.v_W,Q.W,Q.CovW] = W_module.initialize();\n[Q.v_X,Q.X,Q.CovX] = X_module.initialize();\n[Q.Tau] = noise_module.initialize();\nQ.W_module = W_module;\nQ.X_module = X_module;\nQ.noise_module = noise_module;\n\n\n% Observed values\nObs = ~isnan(Y);\nMN_obs = sum(Obs(:));\n\n% Replace missing values with zeros for computational reasons\nY(~Obs) = 0;\n\n%%\n%% VB learning\n\nloglikelihood_old = -inf;\nQ.loglikelihood = nan(options.maxiter,1);\n\nQ.Y = Y;\n\nKL_W = -inf;\nKL_X = -inf;\nKL_Tau = -inf;\n\n%f = zeros(4,options.maxiter);\n\ndisp('Starting the VB iteration..')\nfor ind=1:options.maxiter\n \n startitercpu = cputime;\n \n %\n % Update variables\n %\n \n if index_selected(ind, options.update_x)\n if index_selected(ind, options.debug)\n disp('Update X')\n end\n [Q.v_X,Q.X,Q.CovX,KL_X] = X_module.update(ind, Y, Obs, Q.v_W, Q.W, Q.CovW, Q.Tau);\n end\n \n if index_selected(ind, options.update_w)\n if options.debug, disp('Update W'), end\n if index_selected(ind, options.debug)\n disp('Update W')\n end\n [Q.v_W,Q.W,Q.CovW,KL_W] = W_module.update(ind, Y', Obs', Q.v_X, Q.X, Q.CovX, Q.Tau');\n end\n \n % Compute squared errors <(y_mn-w_m*x_n)^2>\n % (used by noise update and loglikelihood)\n E2 = zeros(size(Y));\n Yh = Q.W'*Q.X;\n E2 = Y.*Y;\n E2 = E2 - 2*Y.*Yh;\n if ndims(Q.CovW) == 2 && ndims(Q.CovX) == 2\n E2 = E2 + Yh.^2 + Q.W'.^2*Q.CovX + Q.CovW'*Q.X.^2 + Q.CovW'*Q.CovX;\n elseif ndims(Q.CovW) == 3 && ndims(Q.CovX) == 3\n xx = bsxfun(@times, reshape(Q.X,[D,1,N]), reshape(Q.X,[1,D,N])) + Q.CovX;\n xx = reshape(xx, [D*D,N]);\n ww = bsxfun(@times, reshape(Q.W,[D,1,M]), reshape(Q.W,[1,D,M])) + Q.CovW;\n ww = reshape(ww, [D*D,M]);\n E2 = E2 + ww'*xx;\n else\n % TODO: Optimize this..\n warning('Optimize this..');\n for m=1:M\n for n=1:N\n if Obs(m,n)\n if ndims(Q.CovW) == 2\n ww = Q.W(:,m)*Q.W(:,m)' + diag(Q.CovW(:,m));\n else\n ww = Q.W(:,m)*Q.W(:,m)' + Q.CovW(:,:,m);\n end\n if ndims(Q.CovX) == 2\n xx = Q.X(:,n)*Q.X(:,n)' + diag(Q.CovX(:,n));\n else\n xx = Q.X(:,n)*Q.X(:,n)' + Q.CovX(:,:,n);\n end\n %WX_WX = WX_WX + traceprod(ww, xx);\n E2(m,n) = E2(m,n) + traceprod(ww, xx);\n end\n end\n end\n end\n E2(~Obs) = 0;\n\n if index_selected(ind, options.update_noise)\n if index_selected(ind, options.debug)\n disp('Update Tau')\n end\n \n [Q.Tau,LogTau,KL_Tau] = noise_module.update(ind, E2, Obs);\n% [Tau,lowerbound] = noise_module.update(Y, Obs, v_W, W, CovW, v_X, X, CovX);\n end\n \n\n %\n % Rotate\n %\n \n if index_selected(ind, options.rotate)\n \n % TODO: You could optimize the hyperparameters at the same time?\n disp('Rotating..')\n A = eye(D);\n \n if index_selected(ind, options.rotation_checkgrad)\n mycheckgrad(@rotation_cost, A(:) + 0.5*randn(D^2,1), 1e-3, W_module, ...\n X_module);\n end\n A = minimize(A(:), @rotation_cost, options.rotation_maxiter, W_module, ...\n X_module);\n A = reshape(A, [D D]);\n if index_selected(ind, options.rotation_show)\n A\n end\n [Q.W, Q.CovW] = W_module.rotate(A);\n [Q.X, Q.CovX] = X_module.rotate(inv(A)');\n\n end\n\n \n %\n % Evaluate VB lower bound\n %\n \n % Likelihood part: \n logpdf_y = gaussian_logpdf(Q.Tau(Obs)'*E2(Obs), ...\n 0, ...\n 0, ...\n -sum(LogTau(Obs)), ...\n MN_obs);\n\n % Lower bound\n Q.loglikelihood(ind) = logpdf_y - KL_W - KL_X - KL_Tau;\n \n% $$$ if ~isreal(Q.loglikelihood(ind))\n% $$$ KL_W\n% $$$ KL_X\n% $$$ KL_Tau\n% $$$ error('Loglikelihood imaginary')\n% $$$ end\n \n if Q.loglikelihood(ind) < loglikelihood_old\n warning(sprintf('Loglikelihood lower bound decreased relatively %e!', ...\n (loglikelihood_old - Q.loglikelihood(ind)) / loglikelihood_old));\n end\n \n fprintf('Iteration step %d: loglikelihood=%e (%.2f seconds)\\n', ind, ...\n Q.loglikelihood(ind), cputime()-startitercpu);\n \n% $$$ f(1,ind) = KL_W;\n% $$$ f(2,ind) = KL_X;\n% $$$ f(3,ind) = KL_Tau;\n% $$$ f(4,ind) = loglikelihood(ind);\n \n loglikelihood_old = Q.loglikelihood(ind);\n \n if index_selected(ind, options.autosave)\n fprintf('Saving results to %s...', options.autosavefile);\n save(options.autosavefile, '-struct', 'Q');\n fprintf(' done.\\n');\n end\n \nend\n\n% $$$ figure\n% $$$ plot(f');\n\n% $$$ if nargout >= 1\n% $$$ \n% $$$ Q.W_module = W_module;\n% $$$ Q.W = W;\n% $$$ Q.CovW = CovW;\n% $$$ \n% $$$ Q.X_module = X_module;\n% $$$ Q.X = X;\n% $$$ Q.CovX = CovX;\n% $$$ \n% $$$ Q.noise_module = noise_module;\n% $$$ Q.Tau = Tau;\n% $$$ \n% $$$ Q.loglikelihood = loglikelihood;\n% $$$ \n% $$$ end\n\n%function rotate(W_module, X_module)\n%end\n\nfunction [c, dc] = rotation_cost(a, W_module, X_module)\nN = sqrt(length(a));\nA = reshape(a, N, N);\n[U,S,V] = svd(A);\ninvS = diag(1./diag(S));\ninvAt = U*invS*V';\n[c_w, dc_w] = W_module.rotation_cost(A, U, S, V);\n[c_x, dc_x] = X_module.rotation_cost(invAt, U, invS, V);\ndc_x = -invAt*dc_x'*invAt;\nc = c_w + c_x;\ndc = dc_w(:) + dc_x(:);\n", "meta": {"author": "jluttine", "repo": "matlab", "sha": "63406c7782b0869948f06e1dbc594460c165d24e", "save_path": "github-repos/MATLAB/jluttine-matlab", "path": "github-repos/MATLAB/jluttine-matlab/matlab-63406c7782b0869948f06e1dbc594460c165d24e/fa/vbfa_old.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.331257107478906}} {"text": "% THIS SOFTWARE AND ANY ACCOMPANYING DOCUMENTATION IS RELEASED \"AS IS.\" THE U.S. GOVERNMENT MAKES NO WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, CONCERNING THIS SOFTWARE AND ANY ACCOMPANYING DOCUMENTATION, INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT WILL THE U.S. GOVERNMENT BE LIABLE FOR ANY DAMAGES, INCLUDING ANY LOST PROFITS, LOST SAVINGS OR OTHER INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE, OR INABILITY TO USE, THIS SOFTWARE OR ANY ACCOMPANYING DOCUMENTATION, EVEN IF INFORMED IN ADVANCE OF THE POSSIBILITY OF SUCH DAMAGES.\n%\n% file: interval_est_r.m\n% computes confidence interval estimates for rates.\n%\n% 022400 tdr created\n% 031600 tdr created rate version from interval_est_p.m\n% 032200 tdr added cs1, cs2, and tl methods.\n% 012601 tdr added input checking.\n% 012901 tdr added 1-sided CIs for CS1 method\n% 031501 tdr added minimum length method\n%\n\nfunction ci = interval_est_r(x,A,alpha,method)\n\n% ------------------------------------------------------------\n% start checking inputs\n\nif nargin ~= 4, \n error('Requires four input arguments (x,A,alpha,method)');\nend\n \n% inputs must all be scalars\nif (max(max([size(x); size(A); size(alpha)])) ~= 1)\n error('Non-scalar input'); \nend;\n\n% x must be integer\nif (round(x) ~= x)\n x = round(x);\n warning('Non-integer input x'); \nend;\n\n% A must be > 0\nif (A <= 0),\n ci = [ NaN NaN NaN];\n warning('A <= 0');\n return;\nend;\n\n% x must be >= 0\nif ( x < 0),\n ci = [ NaN NaN NaN];\n warning('x < 0');\n return;\nend;\n\n% alpha must be > 0.0 and < 1.0\nif ( alpha < 0 | alpha > 1),\n ci = [ NaN NaN NaN];\n warning('alpha < 0 or alpha > 1');\n return;\nend;\n\n% normalize case\nif strcmpi(method,'cs1'), method = 'cs1'; end;\nif strcmpi(method,'cs1_1s'), method = 'cs1_1s'; end;\nif strcmpi(method,'cs2'), method = 'cs2'; end;\nif strcmpi(method,'ibp'), method = 'ibp'; end;\n%if strcmpi(method,'ibp_1s'), method = 'ibp_1s'; end;\nif strcmpi(method,'ml'), method = 'ml'; end;\nif strcmpi(method,'nibp'), method = 'nibp'; end;\n%if strcmpi(method,'nibp_1s'), method = 'nibp_1s'; end;\nif strcmpi(method,'na'), method = 'na'; end;\nif strcmpi(method,'tl'), method = 'tl'; end;\n\n% end checking inputs\n% ------------------------------------------------------------\n\nswitch method\ncase 'cs1',\n ci = get_r_ci_cs1(x,A,alpha);\ncase 'cs1_1s',\n ci = get_r_ci_cs1_1s(x,A,alpha);\ncase 'cs2',\n ci = get_r_ci_cs2(x,A,alpha);\ncase 'ibp',\n ci = get_r_ci_ibp(x,A,alpha);\ncase 'ml',\n ci = get_r_ci_ml(x,A,alpha);\ncase 'na',\n ci = get_r_ci_na(x,A,alpha);\ncase 'tl',\n ci = get_r_ci_tl(x,A,alpha);\notherwise\n error('Method not recognized. Methods Available: cs1/cs2 - COMPASE Standards, ibp - Integration of Bayes Posterior; ml - minimum length; na - Normal Approximation; tl - Table Lookup');\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/3031-accurate-confidence-intervals/ci_tool/interval_est_r.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.331257107478906}} {"text": "function adjList = meshFaceAdjacency(vertices, edges, faces)\n%MESHFACEADJACENCY Compute adjacency list of face around each face.\n%\n%\n% Example\n% % Create a sample 3D mesh\n% [v, e, f] = createDodecahedron;\n% adjList = meshFaceAdjacency(v, e, f);\n% figure; hold on; axis equal; view([100 40]);\n% drawMesh(v, f);\n% % draw sample face in a different color\n% drawMesh(v, f(1, :), 'faceColor', 'b');\n% % draw the neighbors of a sample face\n% drawMesh(v, f(adjList{1}, :), 'faceColor', 'g')\n% \n% \n\n% ------\n% Author: David Legland\n% E-mail: david.legland@grignon.inra.fr\n% Created: 2010-10-04, using Matlab 7.9.0.529 (R2009b)\n% Copyright 2010-2022 INRA - Cepia Software Platform\n\nedgeFaceList = meshEdgeFaces(vertices, edges, faces);\n\n% allocate memory for adjacency list\nnFaces = max(edgeFaceList(:));\nadjList = cell(1, nFaces);\n\n% iterate over edges to populate adjacency list\nfor iEdge = 1:size(edgeFaceList)\n f1 = edgeFaceList(iEdge, 1);\n f2 = edgeFaceList(iEdge, 2);\n adjList{f1} = [adjList{f1} f2];\n adjList{f2} = [adjList{f2} f1];\nend\n", "meta": {"author": "mattools", "repo": "matGeom", "sha": "1fd2c937064be1ee1f4fd09fbfdf96145ebe5271", "save_path": "github-repos/MATLAB/mattools-matGeom", "path": "github-repos/MATLAB/mattools-matGeom/matGeom-1fd2c937064be1ee1f4fd09fbfdf96145ebe5271/matGeom/meshes3d/meshFaceAdjacency.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.3311084377612273}} {"text": "function [xh,pf, P, L] = RBPF(x_true, y, LRS, u, a, pf, Nsamples, resampling_strategy)\n \n % x_true: true position of robot\n % y: True laser scan\n % LRS: laser scan inforamtion\n % u: Movement control\n % a: Odometry parameters found via Motion_Model_Velocity_Test\n % pf: pf class with all particle filter information\n % Nsamples: number of samples for the Particle Filter\n % resampling_startegy: DO NOT CHANGE \n\n %% Variable Initialization\n\n k = pf.k;\n NPC = pf.NPC;\n q_past = pf.q(:,k-1);\n x_past= pf.particles(:,:,k-1);\n \n % Initialise new variables\n x_initial_estimate=zeros(3, NPC); % Initial estimate from previous Xt-1 and Ut\n yh=zeros(2, 361, NPC); % Laser scan estimate from x_initial_estimate\n x_new_sm=zeros(3, NPC); % New position after scan matching (ICP)\n x_sampled=zeros(3,Nsamples, NPC); % Smaple position around every particle position\n p_xt=zeros(Nsamples, NPC); % Density function for odometry (Motion_Model_velocity)\n p_zt=zeros(Nsamples, NPC); % Density function for scans (Scan Matching)\n tau_xt=zeros(Nsamples, NPC); % Optimal Proposal Distribution\n n=zeros(1,NPC); % Sample normalizer\n mu=zeros(3, NPC); % Mean for Gaussian distribution from all particle samples \n cov=zeros(1, NPC); % Covariance for Gaussian distribution from all particle samples \n q=zeros(size(q_past)); % Particle weights\n x_final=zeros(3, NPC); % final estimate particle position after RBPF\n\n %% RBPF for every particle\n for i = 1:NPC\n\n %Estimate particle position from x_(t-1) after Ut\n x_initial_estimate(:,i) = Kinematics(x_past(:,i),u+sqrt(pf.R1)*randn(length(u),1));\n \n if x_initial_estimate(3,i)>2*pi\n x_initial_estimate(3,i)=x_initial_estimate(3,i)-2*pi;\n elseif x_initial_estimate(3,i)<-2*pi\n x_initial_estimate(3,i)=x_initial_estimate(3,i)+2*pi;\n end\n \n %Scan Matcher returns estimate of laser given an initial particle position estimate\n yh(:,:,i) = Measurement_Estimate_From_Grid(x_initial_estimate(:,i),pf.P(:,:, i),LRS.Resolution,LRS.FoV, LRS.MaxDistance, pf.UsableArea);\n \n % Scan pre-processing prior to ICP algortithm\n y_help=y;\n yh_help=yh(:,:,i);\n \n % Use data inside Usable Area only\n y_help(y_help>pf.UsableArea)=nan;\n yh_help(yh_help>pf.UsableArea)=nan;\n \n % Chose data that whose angle is usable in both scans\n find_y_help=isnan(y_help(2,:));\n find_yh_help=isnan(yh_help(2,:));\n del_cols=or(find_y_help, find_yh_help);\n y_help(:,(del_cols(1,:)==1))=[];\n yh_help(:,(del_cols(1,:)==1))=[];\n \n % Transform to Polar coordinates and World frame\n y_help=Polar2Cart(y_help);\n yh_help=Polar2Cart(yh_help);\n y_help=Rotate_Data(y_help, x_true);\n yh_help=Robot2World([x_initial_estimate(1,i); x_initial_estimate(2,i); x_initial_estimate(3,i)], yh_help);\n \n % Add the particles position so that its also transformed \n y_help=horzcat(y_help, x_true(1:2));\n yh_help=horzcat(yh_help, x_initial_estimate(1:2,i));\n \n\n failure=false; % Initialse ICP failure to FALSE\n \n try\n [TR,TT, data] = ICP(y_help, yh_help); % ICP algortithm returns the translational and rotational matrices and the resulting data\n catch\n failure=true;\n end\n % Check if ICP failed\n if abs(TT(1))>50 || abs(TT(2))>50\n failure=true;\n end\n \n if failure\n disp('ICP failed')\n x_final(:,i)=x_initial_estimate(:,i); % If ICP failed used last known position estimate\n q(i)=q_past(i); % do not change particle weights\n else\n \n theta_new_sm=x_initial_estimate(3,i)+asin(TR(2,1)); % Modify theta angle according to the rotation given by ICP\n x_new_sm(:,i)=[data(1:2,end); theta_new_sm]; % Use rotated+translated initila_estimate as new (and better) positon\n \n %Plot grid-map, all positions and all scans (Black: True postion, Blue: Position and scan initial estimates, red:\n %Converged position and laser data\n figure(42)\n set(gcf,'units','normalized','outerposition',[1 0 1 1]);\n clf;\n caxis([0, 1]);\n colormap gray;\n colormap(flipud(colormap));\n hold on;\n imagesc(flipud(pf.P(:,:, i)));\n\n % Plot scans\n plot(y_help(1,:), y_help(2,:), '.g')\n plot(yh_help(1,:), yh_help(2,:), '.b')\n plot(data(1,:), data(2,:), '.r')\n\n % Plot positions\n plot(x_true(1), x_true(2), 'dk')\n plot(x_initial_estimate(1,i), x_initial_estimate(2, i), 'db')\n plot(x_new_sm(1,i), x_new_sm(2,i), 'dr')\n hold off;\n \n % Save each iteration map into as png\n % str=sprintf('path_images/fig%d.png', pf.k);\n % saveas(gcf, str)\n\n % Randomize samples around good estimate (x_new_sm) of particle position \n theta_samples=x_new_sm(3,i);\n if theta_samples > 2*pi\n theta_samples=theta_samples-2*pi;\n elseif theta_samples < -2*pi\n theta_samples=theta_samples-2*pi;\n end \n \n x_sampled(:,:, i) = [ normrnd([x_new_sm(1,i).*ones(1, Nsamples); x_new_sm(2,i).*ones(1, Nsamples)],0.5, [2 Nsamples]); theta_samples.*ones(1, Nsamples)]; \n \n for h=1:Nsamples\n \n % Calculate odometry probability for that sample \n p_xt(h,i)= Motion_Model_Velocity(x_sampled(:,h,i), u, x_past(:,i), a);\n \n % Calculate scan matching probability for that sample \n ytru=y;\n yest = Measurement_Estimate_From_Grid(x_sampled(:,h,i),pf.P(:,:, i),LRS.Resolution,LRS.FoV, LRS.MaxDistance, pf.UsableArea);\n yest(yest>pf.UsableArea)=nan;\n find_yest=isnan(yest(2,:));\n yest(:,(find_yest(1,:)==1))=[];\n ytru(:,(find_yest(1,:)==1))=[];\n p_zt(h,i) = Measurement_Model(ytru,yest,[1 1]);\n\n % Calculate optimal proposal distribution\n tau_xt(h,i)=abs(p_xt(h,i)*p_zt(h,i));\n\n end\n \n n(i)=sum(tau_xt(:,i)); % Calculate sample normalizer\n mu(1, i)=(1/n(i))*(x_sampled(1,:,i)*tau_xt(:,i)); % Calculate mu for gaussian distribution from samples\n mu(2, i)=(1/n(i))*(x_sampled(2,:,i)*tau_xt(:,i));\n mu(3, i)=theta_samples; % Orientation of samples is constant (the one from ICP)\n\n % Calculate covariance for gaussian distribution from samples\n cov_sum=0;\n for h=1:Nsamples\n cov_sum=cov_sum+(x_sampled(1:2,h,i)-mu(1:2,i))'*(x_sampled(1:2,h,i)-mu(1:2,i))*tau_xt(h,i);\n end\n cov(i)=(1/n(i))*cov_sum;\n\n %Calculate new weights\n q(i)=q_past(i)*n(i);\n\n %Sample gaussian for final position of particle\n x_final(:,i)=[normrnd([mu(1,i); mu(2,i)],cov(i), [2 1]); mu(3, i)];\n end \n \n %Update GridMap for taht particle\n [pf.P(:,:,i), pf.L(:,:,i)] = Occupancy_Grid_Mapping(pf.L(:,:,i), x_final(:,i), y, pf.UsableArea, pf.L0, pf.gridsize, LRS);\n \n end\n \n q=q/norm(q,1); % Normalize weights\n Neff = 1/sum(q.^2); % Calcuklate Neff for possible resampling\n \n \n %% Resampling step\n \n resample_percentage = 0.3; % 0.5 is the best resample percentage proposed by Cyrill Stachniss\n Nt = resample_percentage*NPC;\n if Neff < Nt\n disp('Resampling');\n [x_final(:,:), q, idx] = Resample(x_final(:,:), q, resampling_strategy);\n P_save_resamp=pf.P(:,:,:);\n L_save_resamp=pf.L(:,:,:);\n for n=1:NPC\n pf.P(:,:,n)=P_save_resamp(:,:,idx(n));\n pf.L(:,:,n)=L_save_resamp(:,:,idx(n));\n end\n end\n \n pf.q(:,k) = q; % Save particle weights (might have changed during resampling) \n \n %% Calculate estimate of true position (xh) given all weighted particles\n xh = zeros(3,1);\n for i=1:NPC\n xh = xh +(q(i).*x_final(:,i));\n end\n pf.xh(:, k)= xh;\n \n %% Store final position of all particles\n pf.particles(:,:,k) = x_final(:,:);\n \n % Make sure no errors have occured. If so probably becasue of p_xt or p_zt being equal to 0\n if isnan(x_final(1,i)) || isnan(x_final(2,i))\n 1; %debugger\n x_final=x_initial_estimate;\n end\n \n \n %% Visualize results: Plot Particles \n% figure(89)\n% set(gcf,'units','normalized','outerposition',[-1 0 1 1]);\n% clf;\n% hold on;\n% for g = 1:size(map,2)\n% plot([map(1,g) map(3,g)],[map(2,g) map(4,g)],'k')\n% end\n% plot(squeeze(pf.particles(1,:,pf.k-1))',squeeze(pf.particles(2,:,pf.k-1))','bo');\n% plot(squeeze(pf.particles(1,:,pf.k))',squeeze(pf.particles(2,:,pf.k))','k+');\n% plot(squeeze(pf.xh(1,pf.k))',squeeze(pf.xh(2,pf.k))','ro');\n% plot(x_true(1), x_true(2), 'go')\n% hold off;\n\nend\n\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/RBPF.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7431680086124812, "lm_q2_score": 0.44552953503957266, "lm_q1q2_score": 0.3311032973334039}} {"text": "function g = rbfhKernGradient(kern, x1, x2, covGrad)\n\n% RBFHKERNGRADIENT Gradient of RBFH kernel's parameters.\n% FORMAT\n% DESC computes the gradient of functions with respect to the\n% radial basis function heat kernel's parameters. As well as the kernel\n% structure and the input positions, the user provides a matrix PARTIAL\n% which gives the partial derivatives of the function with respect to the\n% relevant elements of the kernel matrix.\n% ARG kern : the kernel structure for which the gradients are being\n% computed.\n% ARG x1 : the input locations for which the gradients are being\n% computed.\n% ARG covGrad : matrix of partial derivatives of the function of\n% interest with respect to the kernel matrix. The argument takes\n% the form of a square matrix of dimension numData, where numData is\n% the number of rows in X.\n% RETURN g : gradients of the function of interest with respect to\n% the kernel parameters. The ordering of the vector should match\n% that provided by the function kernExtractParam.\n%\n% FORMAT\n% DESC computes the derivatives as above, but input locations are\n% now provided in two matrices associated with rows and columns of\n% the kernel matrix.\n% ARG kern : the kernel structure for which the gradients are being\n% computed.\n% ARG x1 : the input locations associated with the rows of the\n% kernel matrix.\n% ARG x2 : the input locations associated with the columns of the\n% kernel matrix.\n% ARG covGrad : matrix of partial derivatives of the function of\n% interest with respect to the kernel matrix. The matrix should\n% have the same number of rows as X1 and the same number of columns\n% as X2 has rows.\n% RETURN g : gradients of the function of interest with respect to\n% the kernel parameters.\n%\n% SEEALSO: rbfhKernParamInit, kernGradient\n%\n% COPYRIGHT : Mauricio A. Alvarez, 2010\n\n% KERN\n\nif nargin < 4\n covGrad = x2;\n x2 = x1;\nend\nif size(x1, 2) ~= 2 || size(x2, 2) ~= 2\n error('Input can only have two columns');\nend\n\n% Split the domain into time domain and spatial domain and account for\n% missing values. If there are no missing values the computation of the\n% kernel is a pointwise prodruct, otherwise it is a kronecker product.\nt1 = x1(x1(:,1)~=Inf,1);\nt2 = x2(x2(:,1)~=Inf,1);\ns1 = x1(x1(:,2)~=Inf,2);\ns2 = x2(x2(:,2)~=Inf,2);\nif (length(t1) == length(s1)) && (length(t2) == length(s2))\n ut1 = unique(t1);\n ut2 = unique(t2);\n us1 = unique(s1);\n us2 = unique(s2);\n if (length(ut1)*length(us1) == length(t1)) && ...\n (length(ut2)*length(us2) == length(t2))\n t1 = ut1; s1 = us1; t2 = ut2; s2 = us2;\n isPointwise = false;\n else\n isPointwise = true;\n end\nelse\n isPointwise = false;\nend\n\nkern.rbf.inverseWidth = kern.inverseWidthTime;\nKt = rbfKernCompute(kern.rbf, t1, t2);\nkern.rbf.inverseWidth = kern.inverseWidthSpace;\nKs = rbfKernCompute(kern.rbf, s1, s2);\n\nif isPointwise\n covGradt = covGrad.*Ks;\n covGrads = covGrad.*Kt;\nelse\n covGradt = zeros(length(t1), length(t2));\n covGrads = zeros(length(s1), length(s2));\n endOne = 0;\n startOne = 1;\n for k=1:length(t1)\n endOne = endOne + length(s1);\n startTwo = 1;\n endTwo = 0;\n for l=1:length(t2)\n endTwo = endTwo + length(s2);\n covGradt(k,l) = sum(sum(covGrad(startOne:endOne, startTwo:endTwo).*Ks));\n startTwo = endTwo + 1;\n end\n startOne = endOne + 1;\n end\n for k=1:length(s1)\n indRows = (k:length(s1):(length(t1)*length(s1)))';\n for l=1:length(s2)\n indCols = l:length(s2):(length(t2)*length(s2));\n covGrads(k,l) = sum(sum(covGrad(indRows, indCols).*Kt));\n end\n end\nend\n\nkern.rbf.inverseWidth = kern.inverseWidthTime;\ngt = rbfKernGradient(kern.rbf, t1, t2, covGradt);\nkern.rbf.inverseWidth = kern.inverseWidthSpace;\ngs = rbfKernGradient(kern.rbf, s1, s2, covGrads);\n\ng = [gt(1) gs(1)];\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/rbfhKernGradient.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.672331699179286, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.3309136856050475}} {"text": "function [rtk,sat_,stat]=estpos(rtk,obs,nav,sv,opt)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%estimate reciever position and clock bias\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nglobal glc\nNX=3+glc.NSYS; MAXITER=10; iter=1;\ntime=obs(1).time; xr0=[rtk.sol.pos';zeros(glc.NSYS,1)];\n\nwhile iter<=MAXITER\n \n % compute residual,measurement model,weight matrix\n [v,H,P,vsat,azel,resp,nv,ns]=rescode(iter,obs,nav,sv,xr0,opt);\n sat_.vsat=vsat; \n sat_.azel=azel;\n sat_.resp=resp;\n \n if nvMAXITER\n stat=0;\n [week,sow]=time2gpst(time);\n fprintf('Warning:GPS week = %d sow = %.3f,SPP iteration divergent!\\n',week,sow);\n return;\nend\n\nreturn\n\n\n\n", "meta": {"author": "kaichen686", "repo": "GINav", "sha": "bc6b3ab6c40db996a4fd8e8ca5b748fe21a23666", "save_path": "github-repos/MATLAB/kaichen686-GINav", "path": "github-repos/MATLAB/kaichen686-GINav/GINav-bc6b3ab6c40db996a4fd8e8ca5b748fe21a23666/src/gnss/spp/estpos.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7745833737577158, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.3302216174611973}} {"text": "function radDepthV = getRadiologicalDepth(xV, yV, zV, gantryAngle, isocenter, isodistance, structNum, scanSet, planC)\n%\"getRadiologicalDepth\"\n% Returns the radiological depth at the points in xV, yV, zV, as\n% determined from scanSet with a point source at sourceV. structNum\n% tells the interpolation routine to only include the densities of \n% points within a certain structure when calculating the radiological\n% depth.\n%\n%JRA 06/16/05\n%\n%Usage:\n% function radDepthV = getRadiologicalDepth(xV, yV, zV, gA, iC, iD, structNum, scanSet, planC)\n%\n% Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team.\n% \n% This file is part of The Computational Environment for Radiotherapy Research (CERR).\n% \n% CERR development has been led by: Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy.\n% \n% CERR has been financially supported by the US National Institutes of Health under multiple grants.\n% \n% CERR is distributed under the terms of the Lesser GNU Public License. \n% \n% This version of CERR is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% CERR is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;\n% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n% See the GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with CERR. If not, see .\n\nif ~exist('planC')\n global planC\nend\nindexS = planC{end};\n\nsiz = size(xV);\n\n%Get mask of requested structure.\nrS = getRasterSegments(structNum, planC);\n[structMask, slicesV] = rasterToMask(rS, scanSet, planC); \n% rS = getRasterSegments(structNum, planC);\n% [structMask, slicesV] = rasterToMask(rS, scanSet, planC); \n% [surfPoints] = getSurfacePoints(structMask);\n\n%Get coordinates of scan voxels inside the structure.\n[xS, yS, zS] = getScanXYZVals(planC{indexS.scan}(scanSet));\n[xM, yM, zM] = meshgrid(xS, yS, zS(slicesV));\nxM = xM(structMask);\nyM = yM(structMask);\nzM = zM(structMask);\n% [xS, yS, zS] = getScanXYZVals(planC{indexS.scan}(scanSet));\n% zS = zS(slicesV);\n% xM = xS(surfPoints(:,1));\n% yM = yS(surfPoints(:,2));\n% zM = zS(surfPoints(:,3));\n% clear surfPoints\n\n%Convert points to collimator coordinates.\ncoll3V = scan2Collimator([xM(:) yM(:) zM(:)], gantryAngle, 0, 0, isocenter, isodistance);\nclear xM yM zM;\n\n%Get distance from source to all points.\ndistsquared = sepsq(coll3V', [0 0 0]');\n\n%Project vector to points to the perpendicular plane at isocenter.\ncoll3V = coll3V./repmat(coll3V(:,3), [1 3]) * -isodistance;\n\n%Find the extents of X,Y,D for the region covering the structure (ie, all\n%nonzero scan numbers since we will set scan densities outside of structure\n%to be 0.\nminExt = min(coll3V);\nmaxExt = max(coll3V);\nclear coll3V;\n\nminProjX = minExt(1);\nmaxProjX = maxExt(1);\n\nminProjY = minExt(2);\nmaxProjY = maxExt(2);\n\nmaxDsq = max(distsquared);\nminDsq = min(distsquared);\nclear distsquared;\n\n%Set points in scanArray outside of structure to 0.\nsA = planC{indexS.scan}(scanSet).scanArray;\nfor i=1:size(sA, 3); \n [ismem, loc] = ismember(i, slicesV);\n if ismem\n slc = sA(:,:,i);\n slc(~structMask(:,:,loc)) = 0;\n sA(:,:,i) = slc;\n else\n sA(:,:,i) = zeros(size(sA(:,:,i))); \n end\nend \nclear structMask;\n\n%Convert requested points to collimator coordinates.\ncoll3V = scan2Collimator([xV(:) yV(:) zV(:)], gantryAngle, 0, 0, isocenter, isodistance);\nclear xM yM zM;\n\n%Get distance from source to all requested points.\ndistsquared = sepsq(coll3V', [0 0 0]');\n\n%Project vector to points to the perpendicular plane at isocenter.\ncoll3V = coll3V./repmat(coll3V(:,3), [1 3]) * -isodistance;\n\nclear xV yV zV\n\n%Find out of bounds points, for which calculation is not necessary,\n%radDepth is zero.\nOOBPoints = coll3V(:,1) < minProjX | coll3V(:,1) > maxProjX | coll3V(:,2) < minProjY | coll3V(:,2) > maxProjY;\n\n%Clip the r values so they take the density of the nearest calculated\n%point (points less than minDsq would take zero, and greater than maxDsq\n%would take the last radDepthV value along that ray.\nr = clip(distsquared, minDsq, maxDsq, 'limits');\n\n%Set the resolution of the radiological depth calculation (at isocenter).\ndX = .5;\ndY = .5;\ndR = .25;\n\n%Mesh the radiological depth calculation grid in collimator coordinates.\nprojXV = minProjX:dX:maxProjX;\nprojYV = minProjY:dY:maxProjY;\ndistV = sqrt(minDsq):dR:sqrt(maxDsq);\n[projXVM, projYVM, distVM] = meshgrid(projXV, projYV, distV);\n\nprojDistV = sqrt(sepsq([projXVM(:) projYVM(:) -isodistance*ones(size(projXVM(:)))]', [0 0 0]'));\nprojXVM = projXVM(:) .* (distVM(:) ./ projDistV);\nprojYVM = projYVM(:) .* (distVM(:) ./ projDistV);\nprojZVM = -isodistance*ones(size(distVM(:))) .* (distVM(:) ./ projDistV);\n\n%Convert the depth calculation grid to rectangular coordinates.\nnewXYZ = collimator2Scan([projXVM(:) projYVM(:) projZVM(:)], gantryAngle, 0, 0, isocenter, isodistance);\n% clear projXVM projYVM distVM\n\n%Get the scan values at each point in the radiological depth grid.\n[xVS, yVS, zVS] = getScanXYZVals(planC{indexS.scan}(scanSet));\n\n%Interpolate to values in xV/yV/zV from the scanarray, 0 if out of bounds.\nscanVals = finterp3(newXYZ(:,1), newXYZ(:,2), newXYZ(:,3), sA, [xVS(1) xVS(2)-xVS(1) xVS(end)], [yVS(1) yVS(2)-yVS(1) yVS(end)], zVS, 0);\n\nscanVals = reshape(scanVals, length(projXV), length(projYV), length(distV));\n\n%Scale values by the resolution of R to get the linear radiological depth.\n%Divide by 1024 to get the radiological depth in units of water.\nscanVals = scanVals .* (dR / 1024);\n\n%Take the cumsum to get the actual radiological depth at each point in the\n%depth calculation grid.\ncumDens = cumsum(scanVals, 3);\nclear scanVals\n\ncumDens = reshape(cumDens, size(distVM));\n\n%Interpolate to values in xV/yV/zV from the scanarray, 0 if out of bounds.\nradDepthV = finterp3(coll3V(:,1), coll3V(:,2), sqrt(distsquared), cumDens, [projXV(1) projXV(2)-projXV(1) projXV(end)], [projYV(1) projYV(2)-projYV(1) projYV(end)], distV, 0);\n\nradDepthV(OOBPoints) = 0;\nradDepthV = reshape(radDepthV, siz);", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/IMRTP/recompDose/FFDC/getRadiologicalDepth.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7606506635289835, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.3301082891623656}} {"text": "%DEMO_MEMORYSAVE Demonstration of memory save option in GPstuff\n%\n% Description\n% GP = GP_SET(..., 'savememory', 'on');\n%\n% This demo consists of various combinations of covariance\n% functions, likelihoods and full/sparse approximations. This demo\n% is intended for showing how to use memory save option in\n% GPstuff. Unfortunately MATLAB doesn't have memory usage\n% monitoring, so the purpose of the demo is only to test that\n% results are the same whether you use memory save or not and to\n% show that the running times with memory saving are little bit\n% longer (more overhead). Memory saving can be enabled with the\n% following command\n%\n% Usually GPstuff computes covariance matrix derivatives with\n% respect to all covariance function parameters at once which\n% avoids repeating computations common to each derivatibe, but\n% requires storage of Q NxN matrices, where Q is the number of\n% covariance function parameters. Q can be large, for example, if\n% there are many covariates each having own lengthsacle\n% parameter. With memory save option on, each matrix derivative is\n% computed separately, increasing the computation time little, but\n% reducing the memory usage. In an application, which motivated the\n% implementation of the option, the memory requirement of GPstuff\n% was reduced from over 60GB to less than 6GB.\n%\n% See also \n% GP_SET\n%\n% Copyright (c) 2012 Ville Tolvanen\n\n% This software is distributed under the GNU General Public \n% License (version 3 or later); please refer to the file \n% License.txt, included with the software, for details.\n\n% Classification data with full GP's\n\nS = which('demo_classific');\nL = strrep(S,'demo_classific.m','demodata/synth.tr');\nx=load(L);\ny=x(:,end);\ny = 2.*y-1;\nx(:,end)=[];\n\nlik = lik_logit();\n\npl = prior_t();\npm = prior_sqrtunif();\n\ngpcf = gpcf_neuralnetwork('weightSigma2', [0.9 0.9], 'biasSigma2', 10);\ngpcf = gpcf_neuralnetwork(gpcf, 'weightSigma2_prior', pl,'biasSigma2_prior', pm); %\n\ngpcf2 = gpcf_sexp('lengthScale', [0.9 0.9], 'magnSigma2', 10);\ngpcf2 = gpcf_sexp(gpcf2, 'lengthScale_prior', pl,'magnSigma2_prior', pm); %\n\n% GP without memory saving\ngp = gp_set('lik', lik, 'cf', gpcf, 'jitterSigma2', 1e-4, 'latent_method', 'EP');\n% GP with memory saving option enabled\ngp2 = gp_set('lik', lik, 'cf', gpcf, 'jitterSigma2', 1e-4, 'latent_method', 'EP', 'savememory', 'on');\n\nfprintf('Classification (EP), Neuralnetwork covariance function without and with memory saving (optimization and prediction)\\n');\nopt=optimset('TolX',1e-3,'TolFun',1e-3, 'Display', 'off');\n\n% Optimization and prediction without memory saving\ntic,gp=gp_optim(gp,x,y,'opt',opt);\n[Eft,Varft, lpyt]=gp_pred(gp,x,y,x, 'yt', y);toc\n\n% Optimization and prediction with memory saving\ntic,gp2=gp_optim(gp2,x,y,'opt',opt);\n[Eft2,Varft2, lpyt2]=gp_pred(gp2,x,y,x, 'yt', y);toc\n\n% Check that predictions (and optimization) with and without memory saving are same\nassert(all(Eft==Eft2)); assert(all(Varft==Varft2)); assert(all(lpyt==lpyt2)); \n\ngp = gp_set('lik', lik, 'cf', gpcf2, 'jitterSigma2', 1e-6, 'latent_method', 'Laplace');\ngp2 = gp_set('lik', lik, 'cf', gpcf2, 'jitterSigma2', 1e-6, 'latent_method', 'Laplace', 'savememory', 'on');\n\nfprintf('Classification (Laplace), Squared-Exponential covariance function without and with memory saving (optimization and prediction)\\n');\n\n% Optimization and prediction without memory saving\ntic,gp=gp_optim(gp,x,y,'opt',opt);\n[Eft,Varft, lpyt]=gp_pred(gp,x,y,x, 'yt', y);toc\n\n% Optimization and prediction with memory saving\ntic,gp2=gp_optim(gp2,x,y,'opt',opt);\n[Eft2,Varft2, lpyt2]=gp_pred(gp2,x,y,x, 'yt', y);toc\n\n% Check that predictions (and optimization) with and without memory saving are same\nassert(all(Eft==Eft2)); assert(all(Varft==Varft2)); assert(all(lpyt==lpyt2)); \n\n% Regression data with sparse approximations\n\nprevstream=setrandstream();\nxx=linspace(1,10,901);\nx1=logspace(0,1,100);\nx1=round(x1*100)-99;\nx=xx(x1)';\ny=2*sin(4*x)+0.2*randn(size(x));\nxt=[1:0.01:14]';\n[n,nin] = size(x);\n\npl = prior_t('s2', 1);\npm = prior_logunif();\npn = prior_logunif();\ngpcfse = gpcf_matern32('lengthScale',0.5,'magnSigma2',1, 'lengthScale_prior', pl, 'magnSigma2_prior', pm);\nlik = lik_gaussian('sigma2', 0.1, 'sigma2_prior', pn);\ngp = gp_set('lik', lik, 'cf', gpcfse, 'jitterSigma2', 1e-6);\nopt=optimset('TolFun',1e-4,'TolX',1e-4);\n\nfprintf('Regression, FIC GP, Matern-3/2 covariance function, without and with memory saving (optimization and prediction)\\n')\nXu=round(10+90*rand(18,1))/10; % Random placement\n\ngp_fic = gp_set(gp, 'type','FIC','X_u',Xu,'infer_params','covariance+likelihood+inducing');\ngp_fic2 = gp_set(gp, 'type','FIC','X_u',Xu,'infer_params','covariance+likelihood+inducing', 'savememory', 'on');\n\nopt=optimset('TolFun',1e-4,'TolX',1e-4, 'Display', 'off');\n\n% Optimization and prediction without memory saving\ntic,gp_fic=gp_optim(gp_fic,x,y,'opt',opt);\n[Eft_fic, Varft_fic] = gp_pred(gp_fic, x, y, xt);\nVarft_fic = Varft_fic + gp_fic.lik.sigma2;toc\n\n% Optimization and prediction with memory saving\ntic,gp_fic2=gp_optim(gp_fic2,x,y,'opt',opt);\n[Eft_fic2, Varft_fic2] = gp_pred(gp_fic2, x, y, xt);\nVarft_fic2 = Varft_fic2 + gp_fic.lik.sigma2;toc\nsetrandstream([],prevstream);\n\n% Check that predictions (and optimization) with and without memory saving are same\nassert(all(Eft_fic==Eft_fic2)); assert(all(Varft_fic==Varft_fic2));\n\ngpcfse = gpcf_sexp('lengthScale',0.5,'magnSigma2',1, 'lengthScale_prior', pl, 'magnSigma2_prior', pm);\ngp = gp_set('lik', lik, 'cf', gpcfse, 'jitterSigma2', 1e-6);\n\ngp_fic = gp_set(gp, 'type','VAR','X_u',Xu,'infer_params','covariance+likelihood+inducing');\ngp_fic2 = gp_set(gp, 'type','VAR','X_u',Xu,'infer_params','covariance+likelihood+inducing', 'savememory', 'on');\n\nfprintf('Regression, VAR GP, Squared-Exponential covariance function, without and with memory saving (optimization and prediction)\\n')\n\n% Optimization and prediction without memory saving\ntic,gp_fic=gp_optim(gp_fic,x,y,'opt',opt);\n[Eft_fic, Varft_fic] = gp_pred(gp_fic, x, y, xt);\nVarft_fic = Varft_fic + gp_fic.lik.sigma2;toc\n\n% Optimization and prediction with memory saving\ntic,gp_fic2=gp_optim(gp_fic2,x,y,'opt',opt);\n[Eft_fic2, Varft_fic2] = gp_pred(gp_fic2, x, y, xt);\nVarft_fic2 = Varft_fic2 + gp_fic.lik.sigma2;toc\nsetrandstream([],prevstream);\n\n% Check that predictions (and optimization) with and without memory saving are same\nassert(all(Eft_fic==Eft_fic2)); assert(all(Varft_fic==Varft_fic2));\n\n\n% Spatial data with sparse approximations\n\nS = which('demo_spatial1');\ndata = load(strrep(S,'demo_spatial1.m','demodata/spatial1.txt'));\nx = data(1:200,1:2);\nye = data(1:200,3);\ny = data(1:200,4);\ndims = [1 60 1 35];\n[trindex, Xu] = set_PIC(x, dims, 5, 'corners', 0);\n[n,nin] = size(x);\n\npl = prior_t('s2',10);\npm = prior_sqrtunif();\n\ngpcf1 = gpcf_ppcs3('nin',nin,'lengthScale', 1, 'magnSigma2', 0.1, 'lengthScale_prior', pl, 'magnSigma2_prior', pm);\ngpcf2 = gpcf_sexp('lengthScale', 5, 'magnSigma2', 0.05, 'lengthScale_prior', pl, 'magnSigma2_prior', pm);\ngpcf3 = gpcf_neuralnetwork('weightSigma2', [1 1], 'biasSigma2', 0.05, 'weightSigma2_prior', pl, 'biasSigma2_prior', pm);\n\nlik = lik_negbin();\n% GP without memory save\ngp = gp_set('type', 'FIC', 'lik', lik, 'cf', gpcf1, 'X_u', Xu, ...\n 'jitterSigma2', 1e-4, 'infer_params', 'covariance+inducing');\n% GP with memory saving option enabled\ngp2 = gp_set('type', 'FIC', 'lik', lik, 'cf', gpcf1, 'X_u', Xu, ...\n 'jitterSigma2', 1e-4, 'infer_params', 'covariance+inducing', 'savememory', 'on');\nopt=optimset('TolFun',1e-2,'TolX',1e-2, 'Display', 'off');\n\n\nfprintf('Spatial process (Laplace), FIC GP, PPCS3 covariance function, without and with memory saving (optimization and prediction)\\n');\n\n% Optimization and prediction without memory saving\ntic,gp=gp_optim(gp,x,y,'z',ye,'opt',opt);\n[Ef, Varf] = gp_pred(gp, x, y, x, 'z', ye, 'tstind', [1:n]); toc\n\n% Optimization and prediction with memory saving\ntic,gp2=gp_optim(gp2,x,y,'z',ye,'opt',opt);\n[Ef2, Varf2] = gp_pred(gp2, x, y, x, 'z', ye, 'tstind', [1:n]); toc\n\n% Check that predictions (and optimization) with and without memory saving are same\nassert(all(Ef==Ef2)); assert(all(Varf==Varf2));\n\ngp = gp_set('lik', lik, 'cf', gpcf2, 'jitterSigma2', 1e-4, 'latent_method', 'EP');\ngp2 = gp_set('lik', lik, 'cf', gpcf2, 'jitterSigma2', 1e-4, 'latent_method', 'EP', 'savememory', 'on');\n\nfprintf('Spatial process (EP), FIC GP, Squared-Exponential covariance function, without and with memory saving (optimization and prediction)\\n');\n\n% Optimization and prediction without memory saving\ntic,gp=gp_optim(gp,x,y,'z',ye,'opt',opt);\n[Ef, Varf] = gp_pred(gp, x, y, x, 'z', ye, 'tstind', [1:n]); toc\n\n% Optimization and prediction with memory saving\ntic,gp2=gp_optim(gp2,x,y,'z',ye,'opt',opt);\n[Ef2, Varf2] = gp_pred(gp2, x, y, x, 'z', ye, 'tstind', [1:n]); toc\n\n% Check that predictions (and optimization) with and without memory saving are same\nassert(all(Ef==Ef2)); assert(all(Varf==Varf2));\n\ngp = gp_set('lik', lik, 'cf', gpcf3, 'jitterSigma2', 1e-4);\ngp2 = gp_set('lik', lik, 'cf', gpcf3, 'jitterSigma2', 1e-4, 'savememory', 'on');\n\nfprintf('Spatial process (Laplace), FIC GP, Neuralnetwork covariance function, without and with memory saving (optimization and prediction)\\n');\ntic,gp=gp_optim(gp,x,y,'z',ye,'opt',opt);\n[Ef, Varf] = gp_pred(gp, x, y, x, 'z', ye, 'tstind', [1:n]); toc\n\ntic,gp2=gp_optim(gp2,x,y,'z',ye,'opt',opt);\n[Ef2, Varf2] = gp_pred(gp2, x, y, x, 'z', ye, 'tstind', [1:n]); toc\n\n% Check that predictions (and optimization) with and without memory saving are same\nassert(all(Ef==Ef2)); assert(all(Varf==Varf2));", "meta": {"author": "gpstuff-dev", "repo": "gpstuff", "sha": "114937ec0a201306489a66cbba38283e722fb998", "save_path": "github-repos/MATLAB/gpstuff-dev-gpstuff", "path": "github-repos/MATLAB/gpstuff-dev-gpstuff/gpstuff-114937ec0a201306489a66cbba38283e722fb998/gp/demo_memorysave.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.32987802343849515}} {"text": "function output = callmaxdet(interfacedata)\n\n[F_struc,F_blksz,G_struc,G_blksz] = sedumi2maxdet(interfacedata.F_struc,interfacedata.K); \n\nc = interfacedata.c;\noptions = interfacedata.options;\nx0 = interfacedata.x0;\nonlyfeasible = (nnz(c)==0) & isempty(G_blksz);\n\nif isempty(G_blksz)\n G_blksz = 1;\n G_struc = [1 zeros(1,length(c))];\nelse\nend\n\nif isempty(F_blksz)\n x = zeros(length(c),1)+NaN;\n problem = 11;\n infostr = yalmiperror(problems,'MAXDET failed since there are no inequality constraints in F(x)');\n solveroutput = [];\n solvertime = 0;\n D_struc = []; \nend\n\nproblem = 0;\nsolvertimephase1=0;\nD_struc = [];\nif isempty(x0)\n solvertimephase1 = tic;\n showprogress('Calling MAXDET/phase1',options.showprogress);\n [x0,z0,w0,problem,infostr,solveroutput] = callmaxdetphase1(full(F_struc),full(F_blksz), full(G_struc),full(G_blksz), full(c), options);\n solvertimephase1 = toc(solvertimephase1);\nend\nif (problem~=0) | (onlyfeasible==1)\n if isempty(x0)\n x = repmat(nan,length(c),1);\n else\n x = x0;\t\n end\n solvertime = solvertimephase1;\nelse\n z0=zeros(size(F_struc,1),1);\n w0=zeros(size(G_struc,1),1);\t\n solvertime = tic;\n showprogress('Calling MAXDET',options.showprogress);\n if options.verbose==0\n evalc('[x,Z,W,ul,hist,infostr]=maxdet(full(F_struc),F_blksz,full(G_struc), G_blksz,c'',x0,z0,w0,options.maxdet.AbsTol,options.maxdet.RelTol,options.maxdet.gam,options.maxdet.NTiters);');\n else\n [x,Z,W,ul,hist,infostr]=maxdet(full(F_struc),F_blksz,full(G_struc), G_blksz,c',x0,z0,w0,options.maxdet.AbsTol,options.maxdet.RelTol,options.maxdet.gam,options.maxdet.NTiters);\n end\n solvertime = toc(solvertime)+solvertimephase1;\n \n D_struc = [Z;W];\n \n if options.savesolveroutput\n solveroutput.x = x;\n solveroutput.Z = Z;\n solveroutput.W = W;\n solveroutput.ul = ul;\n solveroutput.hist = hist;\n solveroutput.infostr = infostr;\n else\n solveroutput = [];\n end\n \n switch infostr\n case {'target reached','relative accuracy reached','absolute accuracy reached','absolute tolerance reached','relative tolerance reached'}\n problem = 0;\n case 'maximum Newton iteration exceeded'\n problem = 3;\n otherwise\n problem = 1;\n end \nend\n\n% Standard interface \noutput = createOutputStructure(x,D_struc,[],problem,interfacedata.solver.tag,[],solveroutput,solvertime);\n\nfunction [x0,z0,w0,problem,infostr,solveroutput] = callmaxdetphase1(F_struc,F_blksz, G_struc,G_blksz, c, options);\n\ntry\n if options.verbose==0\n evalc('[x0,z0,w0,ul] = phase1(full(F_struc),F_blksz,full(G_struc), G_blksz,options.maxdet.gam,options.maxdet.AbsTol,options.maxdet.RelTol,options.maxdet.NTiters);');\n else\n [x0,z0,w0,ul] = phase1(full(F_struc),F_blksz,full(G_struc), G_blksz,options.maxdet.gam,options.maxdet.AbsTol,options.maxdet.RelTol,options.maxdet.NTiters);\n end\n if ul(1)<0\n problem = 0;\n elseif ul(2)>=0\n problem = 1;\n else\n problem = 8;\n end\n % % Problems currently detected outside\n% problem = (ul(1)>0);\n\n% In case of problems, phase1 outputs the extended vector instead\n% of last primal iterate\nif problem\n x0 = x0(1:length(c));\nend\n\ncatch\n problem = 9;\n x0 = [];\n z0 = [];\n w0 = [];\n ul = [];\nend\ninfostr = yalmiperror(problem,'MAXDET/phase1');\nif options.savesolveroutput\n solveroutput.x = x0;\n solveroutput.Z = z0;\n solveroutput.W = w0;\n solveroutput.ul = ul;\n solveroutput.infostr = infostr;\nelse\n solveroutput = [];\nend\n\n% CODE TAKEN DIRECTLY FROM MAXDET/PHASE1\n% THE REASON FOR HAVING A COPY HERE IS THAT \n% A FILE NAMED PHASE1 EXIST FOR SP ALSO\n%MAXDET, version ALPHA, April 1996.\n\n%COPYRIGHT 1996 SHAO-PO WU, LIEVEN VANDENBERGHE AND STEPHEN BOYD\n%Permission to use, copy, modify, and distribute this software for \n%any purpose without fee is hereby granted, provided that this entire \n%notice is included in all copies of any software which is or includes\n%a copy or modification of this software and in all copies of the \n%supporting documentation for such software.\n%This software is being provided \"as is\", without any express or \n%implied warranty. In particular, the authors do not make any\n%representation or warranty of any kind concerning the merchantability\n%of this software or its fitness for any particular purpose.\nfunction [x,Z,W,ul] = phase1(F,F_blkszs,G,G_blkszs,gam,abstol,reltol,NTiters);\n\nm = size(F,2)-1;\nif (m ~= size(G,2)-1)\n error('F and G must have the same number of columns.');\nend\nif (size(F,1) ~= sum(F_blkszs.^2)) \n error('Dimensions of F do not match F_blkszs.');\nend;\nif (size(G,1) ~= sum(G_blkszs.^2)) \n error('Dimensions of G do not match G_blkszs.');\nend;\n\n% mineigF is the smallest eigenvalue of F_0\nmineigF = 0.0;\nk=0; for n=F_blkszs,\n mineigF = min(mineigF, min(eig(reshape(F(k+[1:n*n],1),n,n))));\n k=k+n*n; % k = sum n_i*n_i \nend;\n% mineigG is the smallest eigenvalue of G_0\nmineigG = 0.0;\nk=0; for n=G_blkszs,\n mineigG = min(mineigG, min(eig(reshape(G(k+[1:n*n],1),n,n))));\n k=k+n*n; % k = sum n_i*n_i \nend;\n\n% eyeF is the identity\neyeF = zeros(size(F,1),1); \nk=0; for n=F_blkszs,\n eyeF(k+[1:n*n]) = reshape(eye(n),n*n,1); % identity\n k=k+n*n; % k = sum n_i*n_i \nend;\n% eyeG is the identity\neyeG = zeros(size(G,1),1); \nk=0; for n=G_blkszs,\n eyeG(k+[1:n*n]) = reshape(eye(n),n*n,1); % identity\n k=k+n*n; % k = sum n_i*n_i \nend;\n\n% initial x0 \nx0 = [zeros(m,1); max(-1.1*min(mineigF,mineigG), 1)];\n\n% linear objective\nc = [zeros(m,1); 1];\n\n% call maxdet\n[x,Z,W,ul,hist,infostr]=maxdet([F,eyeF; G,eyeG],...\n [F_blkszs(:)',G_blkszs(:)'],...\n [1 zeros(1,m+1)],1,c,x0,...\n zeros(size(F,1)+size(G,1),1),0,...\n abstol,reltol,gam,NTiters);\n\n% prepare output\nx = x(1:m);\nW = Z(size(F,1)+1:size(F,1)+size(G,1));\nZ = Z(1:size(F,1));\n%if ul(1)<0\n% infostr = 'feasible';\n%elseif ul(2)>=0\n% infostr = 'infeasible';\n%else\n% infostr = 'feasibility cannot be determined';\n%end\n\nfunction [F_struc,blksz] = deblock(F_struc,blksz);\nX = any(F_struc(end-blksz^2+1:end,:),2);\nX = reshape(X,blksz,blksz);\n[v,dummy,r,dummy2]=dmperm(X);\nblks = diff(r);\n\nlogt = F_struc;\n\nnewlogt = [];\nfor i = 1:size(logt,2)\n temp = reshape(logt(:,i),blksz,blksz);\n temp = temp(v,v);\n newlogt = [newlogt temp(:)];\nend\nlogt = newlogt;\n\npattern = [];\nfor i = 1:length(blks)\n pattern = blkdiag(pattern,ones(blks(i)));\nend\n\nF_struc = logt(find(pattern),:);\nblksz = blks;", "meta": {"author": "yalmip", "repo": "YALMIP", "sha": "f6d5a6d4222a4d722de30bffb43cae4b3e13b860", "save_path": "github-repos/MATLAB/yalmip-YALMIP", "path": "github-repos/MATLAB/yalmip-YALMIP/YALMIP-f6d5a6d4222a4d722de30bffb43cae4b3e13b860/solvers/callmaxdet.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6297746074044135, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.3296368447588546}} {"text": "%% SPACEXPLOSION Analyze the SpaceX explosion that occurred on 1 Sep 2016\n% All supporting functions are in the infrasoundGT directory (or GISMO)\n% \n\n%% setup\nclear all\nclose all\nmatfile = '/Users/glennthompson/Dropbox/Rockets/analysis/20160901_SpaceXplosion/explosion2.mat';\nif exist(matfile,'file')\n load(matfile);\nelse\n\n % waveform data parameters\n %ds = datasource('antelope', '/raid/data/rockets/dbspacexplosion');\n ds = datasource('antelope', '/Users/glennthompson/Dropbox/Rockets/db/20160901_explosion');\n snum=datenum(2016,9,1,13,0,0);\n enum = snum + 1/24;\n scnl = scnlobject('BCHH', '*', 'FL');\n \n % Geographical coordinates\n % %%%%%%%%%%%%% SCAFFOLD - could load these from Antelope or Excel\n lat = [28.574182 28.573894 28.574004 28.574013 28.574013 28.574013];\n lon = [-80.572410 -80.572352 -80.572561 -80.572360 -80.572360 -80.572360];\n source.lat = 28.562106; % SLC40 - SpaceX launch complex\n source.lon = -80.57718;\n % Wind tower data - could read this from Excel instead\n relativeHumidity = 92; % percent from NASA weather tower data\n temperatureF = 80; % 80 Fahrenheit according to weather tower data from NASA\n wind_direction_from = 150; % degrees - this is the direction FROM according to NASA, see Lisa Huddleston email of Oct 10th\n wind_direction = mod(wind_direction_from + 180, 360);\n wind_speed_knots = 10; % knots\n wind_speed = wind_speed_knots * 0.514444; % m/s\n % rmpath(genpath('/raid/apps/src/GISMO'))\n \n %% compute speed of sound based on temperature & rel. humidity\n temperatureC = fahrenheit2celsius(temperatureF);\n speed_of_sound = computeSpeedOfSound(temperatureC, relativeHumidity);\n disp(sprintf('speed of sound at %.1f Celsius and %f percent relative humidity is %.1f',temperatureC, relativeHumidity, speed_of_sound));\n \n %% load waveform data\n disp('Loading waveform data...')\n w=waveform(ds,scnl,snum,enum);\n \n save(matfile);\nend\n\nmake_figures = true\n%addpath('infrasoundGT')\nfigureOutDirectory = '20160901_results';\nmkdir('.',figureOutDirectory);\n\n\nsave(matfile)\n\n%% plot raw waveform data\nif make_figures\n figure\n plot_panels(w);\n outfile = sprintf('%s/waveforms_raw.png',figureOutDirectory);\n feval('print', '-dpng', outfile); \n close\nend\n\n%% compute predicted travel times for infrasound waves based on GPS coords & wind\n%% also add lat, lon, distance and bacaz fields to waveform objects\ndisp('Predicting travel times based on GPS coordinates and wind vector...')\nfprintf('\\n_______________________________________________\\n');\nfprintf('PREDICTED TRAVEL TIME BASED ON:\\n');\nfprintf(' sound speed %.1fm/s\\n', speed_of_sound);\nfprintf(' wind speed %.1fm/s\\n', wind_speed);\nfprintf(' wind direction %.1f degrees\\n', wind_direction);\nfprintf('------\\t--------\\t-----------\\t----------\\n');\nfprintf('Channel\\tDistance\\tBackAzimuth\\tTravelTime\\n');\nfprintf('------\\t--------\\t-----------\\t----------\\n');\nfor c=1:length(lat)\n [arclen(c), backaz(c)] = distance(lat(c), lon(c), source.lat, source.lon, 'degrees');\n arclen(c) = deg2km(arclen(c))*1000;\n effective_speed = speed_of_sound + wind_speed * cos(deg2rad( (180+backaz(c)) - wind_direction) );\n predicted_traveltime_seconds(c) = arclen(c)/effective_speed;\n fprintf('%s\\t%.1fm\\t\\t%.1f degrees\\t%.3fs\\n',get(w(c),'channel'), arclen(c), backaz(c), predicted_traveltime_seconds(c));\n w(c) = addfield(w(c), 'lat', lat(c));\n w(c) = addfield(w(c), 'lon', lon(c));\n w(c) = addfield(w(c), 'distance', arclen(c));\n w(c) = addfield(w(c), 'backaz', backaz(c));\n \nend\nfprintf('_______________________________________________\\n');\nfprintf('Program name: %s\\n',mfilename('fullpath'))\nsave spacexplosion.mat\n\n\n%% plot array map & compute eastings and northings\nif make_figures\n disp('Plotting array map')\n close all\n deg2m = deg2km(1) * 1000;\n cols = 'rwbggg';\n for c=1:length(lat)\n chan = get(w(c),'channel');\n easting(c) = distance(lat(c), lon(c), lat(c), source.lon) * deg2m;\n northing(c) = distance(lat(c), lon(c), source.lat, lon(c)) * deg2m;\n plot(easting(c),northing(c),'o','MarkerFaceColor',cols(c),'MarkerSize',10)\n hold on\n quiver(easting(c),northing(c),-easting(c)/100,-northing(c)/100,0); % /100 just gives arrow length\n text(easting(c)+1,northing(c),chan(1:3));\n end\n grid on\n quiver(440,1325,wind_speed*sin(deg2rad(wind_direction)), wind_speed*cos(deg2rad(wind_direction)) ,0,'k');\n text(440,1325,'wind')\n hold off\n title('Beach House array position relative to SLC40');\n xlabel('metres east');\n ylabel('metres north');\n axis equal;\n outfile = sprintf('%s/arraymap.png',figureOutDirectory);\n feval('print', '-dpng', outfile); \n close\n save spacexplosion.mat\nend\n\n%% Load arrivals\ndisp('Loading arrivals...')\narrivals=Arrival.retrieve('antelope', '/raid/data/rockets/dbspacexplosion');\nsave spacexplosion.mat\n\n%% Subset out X1 arrivals\ndisp('Subsetting arrivals...')\narrivals = arrivals.subset('iphase', 'X1');\nsave spacexplosion.mat\n\n%% Associate events\ndisp('Associating arrivals into events...')\nmaxTimeDiff = 1; % seconds\neventOn = false;\neventNumber = 0;\nfor c=2:numel(arrivals.daynumber)\n if arrivals.daynumber(c-1) + maxTimeDiff/86400 > arrivals.daynumber(c)\n if ~eventOn % start new event\n eventOn = true;\n eventNumber = eventNumber + 1;\n infrasoundEvent(eventNumber).FirstArrivalTime = arrivals.daynumber(c-1);\n else % event already in progress\n end\n infrasoundEvent(eventNumber).LastArrivalTime = arrivals.daynumber(c);\n else \n if eventOn % write out last event\n eventOn = false;\n end\n end\nend\nnumEvents = numel(infrasoundEvent);\nsave spacexplosion.mat\n\n\n%% Filter waveform data to center around zero\ndisp('Filtering waveform data...')\nwfilt = detrend(w);\nf=filterobject('h',[10],3);\nwfilt=filtfilt(f,wfilt);\nsave spacexplosion.mat\n\n%% Segment event waveforms\npretrigger = 1;\nposttrigger = 1;\nwevent = segment_event_waveforms(wfilt, infrasoundEvent, pretrigger, posttrigger);\nsave spacexplosion.mat\n\n%% Plot infrasound events\nif make_figures\n plot_events(wevent, 'waveforms_infrasoundEvent', figureOutDirectory);\nend\n\n%% correlate\n% loop through infrasound channels\n% take a 0.3-second snippet starting 0.1s before FirstArrivalTime, till 0.2s\n% after it\n% correlate this against the whole wevent for each infrasound\n% trace\n% this should result in a correlation matrix\n% from this record the time lag matrix for each infrasound channel against each other\n% infrasound channel\ndisp('CORRELATION ...')\ndisp('_______________')\n%infrasoundEvent = xcorr3C(wevent, infrasoundEvent, make_figures, figureOutDirectory, pretrigger);\ninfrasoundEvent = xcorr3C(wevent, infrasoundEvent, false, figureOutDirectory, pretrigger);\n\n% for eventNumber=1:numEvents\n% fprintf('- processing event %d of %d\\n', eventNumber, numEvents);\n% haystacks = wevent{eventNumber};\n% infrasoundEvent(eventNumber).maxCorr = eye(3);\n% infrasoundEvent(eventNumber).secsDiff = eye(3);\n% precorrtime = 0.1; % NEEDLE seconds of data to add before first arrival\n% postcorrtime = 0.2; % NEEDLE seconds of data to add after first arrival\n% for chanNumber=1:3\n% needle = extract(haystacks(chanNumber), 'time', infrasoundEvent(eventNumber).FirstArrivalTime-precorrtime/86400, infrasoundEvent(eventNumber).FirstArrivalTime+postcorrtime/86400);\n% for haystackNum = 1:3\n% fprintf(' - looking for needle %d in haystack %d\\n', chanNumber, haystackNum);\n% haystack = haystacks(haystackNum);\n% [acor,lag] = xcorr(get(needle,'data'),get(haystack,'data'));\n% [m,I] = max(abs(acor));\n% infrasoundEvent(eventNumber).maxCorr(chanNumber,haystackNum) = m;\n% infrasoundEvent(eventNumber).secsDiff(chanNumber,haystackNum) = lag(I)/get(haystack,'freq') + pretrigger - precorrtime; \n% if make_figures\n% figure; \n% subplot(3,1,1),plot(haystack);\n% subplot(3,1,2),plot(needle);\n% subplot(3,1,3),plot(lag,acor);\n% outfile = sprintf('figs/xcorr_infrasoundEvent%03d_%d_%d.png',eventNumber,chanNumber,haystackNum);\n% feval('print', '-dpng', outfile); \n% close \n% end\n% end\n% end\n% end\nsave spacexplosion.mat\n\n%% Construct a master infrasound event, from all the individual ones\ndisp('Constructing master infrasound event from individual event statistics')\nmasterEvent.FirstArrivalTime = infrasoundEvent(1).FirstArrivalTime;\nmasterEvent.LastArrivalTime = infrasoundEvent(1).LastArrivalTime;\n\n% find the mean xcorr time lag difference for non-identical infrasound components - it should be close to zero if only one event in time window\n% e.g. needle 1 and haystack 2 should have same magnitude but opposite sign\n% time delay to needle 2 and haystack 1 if there is only one clear N wave\n% in the haystacks\ndisp('- finding events with a mean time lag difference of close to 0 - these are the events we can use')\nindexes = find(abs([infrasoundEvent.meanSecsDiff]) < 0.01); % these are events with probably only one event in wevent time window\nfprintf('- found %d events we can use\\n', numel(indexes));\ndisp('- event indexes to use');\ndisp(indexes)\n\nmasterEvent.secsDiff = zeros(3,3);\nmasterEvent.stdSecsDiff = zeros(3,3);\nfor row=1:3\n for column=1:3\n a = [];\n for eventNumber = indexes\n thisEvent = infrasoundEvent(eventNumber);\n a = [a thisEvent.secsDiff(row, column)];\n end\n \n % eliminate any events which have a difference from the mean of\n % greater than the standard deviation\n diffa = abs( (a-mean(a))/std(a) );\n \n % now set the mean and std for the master event\n masterEvent.secsDiff(row, column) = mean(a(diffa<1.0));\n masterEvent.stdSecsDiff(row, column) = std(a(diffa<1.0));\n end\nend\ndisp(' - mean:');\ndisp(masterEvent.secsDiff)\ndisp(' - std:')\ndisp(masterEvent.stdSecsDiff)\ndisp(' - fractional std:')\ndisp(masterEvent.stdSecsDiff ./ masterEvent.secsDiff)\n\n%% compute sound speed based on GPS coordinates and master event differential travel times\ndisp('- Estimating sound speed for each component pair using GPS coordinates')\nclear speed\nspeed = zeros(3,3)*NaN;\nfor row=1:3\n for column = 1:3\n if row ~= column\n radialDistanceDifference = ( get(w(row),'distance') - get(w(column),'distance') );\n timeDifference = masterEvent.secsDiff(row, column);\n s = radialDistanceDifference / timeDifference;\n disp(sprintf('row %d column %d distance difference %.1f time difference %.4f speed %.1fm/s',row,column,radialDistanceDifference,timeDifference,s));\n speed(row,column) = s;\n end\n end\nend\nspeed\nmeanspeed = nanmean(nanmean(abs(speed)));\nstdspeed = nanstd(nanstd(abs(speed)));\nfprintf('- mean sound speed %.1f, std sound speed %.1f\\n', meanspeed, stdspeed);\nsave spacexplosion.mat\n\n%% beamforming\ndisp('Beamforming to estimate backazimuth of source from array')\n[bestbackaz,bestsoundspeed,distanceDiff,speedMatrix] = beamform2(easting(1:3), northing(1:3), masterEvent.secsDiff, 199.0, 348.6); \ndistanceDiff\nspeedMatrix\nsourceDist = get(w(2),'distance');\n[beamformingsourcelat, beamformingsourcelon] = reckon(lat(2), lon(2), km2deg(sourceDist/1000), bestbackaz);\ndistFromSLC40 = deg2km(distance(beamformingsourcelat, beamformingsourcelon, source.lat, source.lon)) * 1000;\ndisp(sprintf('- source location estimated to be lat = %.4f lon = %.4f, which is %1.fm from true position',beamformingsourcelat, beamformingsourcelon,distFromSLC40));\n\n%%\nif make_figures\n outfile = sprintf('%s/beamforming.png',figureOutDirectory);\n feval('print', '-dpng', outfile); \n close\nend\nsave spacexplosion.mat\n\n%% estimate travel times from cross-correlation derived differential travel times and actual source location, wind speed, and predicted sound speed\n[minimumPredictedTravelTime,index] = min(predicted_traveltime_seconds);\nfor component=1:3\n traveltime_secs(component) = minimumPredictedTravelTime + mean([masterEvent.secsDiff(component,index) -masterEvent.secsDiff(index,component)]);\nend\ntraveltime_secs(4) = minimumPredictedTravelTime + (get(w(4),'distance') - get(w(index),'distance')) / bestsoundspeed;\ntraveltime_secs(5) = traveltime_secs(4);\ntraveltime_secs(6) = traveltime_secs(4);\nsave spacexplosion.mat\n\n%% Shift waveforms based on travel times \nwshift = wfilt;\nfor c=1:numel(wshift)\n starttime = get(w(c), 'start');\n newstarttime = starttime - traveltime_secs(c)/86400;\n disp(sprintf('moving channel %d from %s to %s\\n', c, datestr(starttime, 'HH:MM:SS.FFF'), datestr(newstarttime, 'HH:MM:SS.FFF')));\n wshift(c)=set(wshift(c),'start', newstarttime);\n disp(sprintf('%s\\n',datestr(get(wshift(c),'start'))));\nend\nsave spacexplosion.mat\n\n%% Segment time shifted event waveforms\ndisp('Segmenting traveltime-corrected event waveforms...')\narrivalTimeCorrection = minimumPredictedTravelTime;\npreplot = 0.15;\npostplot = 0.15;\nweventshift = segment_event_waveforms(wshift, infrasoundEvent, preplot, postplot, arrivalTimeCorrection);\nsave spacexplosion.mat\n\n\n%% Plot shifted events\nif make_figures\n plot_events(weventshift, 'waveforms_infrasoundEvent_shifted', figureOutDirectory)\nend\n\n\n\n%% Pick events\nclose all\nfor eventNumber=1:numEvents\n \n % plot waveforms for this event\n w2=weventshift{eventNumber};\n fh=plot_panels(w2);\n ah=get(fh,'Children');\n set(fh, 'Position', [0 0 1600 1000]);\n infrasoundEvent(eventNumber).maxAmp=zeros(1,6);\n infrasoundEvent(eventNumber).minAmp=zeros(1,6);\n infrasoundEvent(eventNumber).maxTime=zeros(1,6);\n infrasoundEvent(eventNumber).minTime=zeros(1,6);\n\n for chanNum=1:6\n \n % scan over this event on this channel and find the greatest\n % max/min difference in 0.1s\n y = get(w2(chanNum),'data');\n fs = get(w2(chanNum),'freq');\n numSamples = length(y);\n windowSize = round(fs/25);\n maxA = 0;\n for startSamp = 1:windowSize:round(numSamples*0.7)-windowSize\n samples = startSamp:startSamp+windowSize-1;\n [maxy, maxindex] = max(y(samples));\n [miny, minindex] = min(y(samples));\n if (maxy-miny) > maxA\n maxSecs = ((maxindex+samples(1)-1)/fs);\n minSecs = ((minindex+samples(1)-1)/fs);\n maxA = maxy-miny;\n \n infrasoundEvent(eventNumber).maxTime(chanNum) = tstart + maxSecs/86400;\n infrasoundEvent(eventNumber).minTime(chanNum) = tstart + minSecs/86400;\n infrasoundEvent(eventNumber).maxAmp(chanNum) = maxy;\n infrasoundEvent(eventNumber).minAmp(chanNum) = miny;\n end\n end\n \n % plot max & min\n axisnum = 8 - chanNum;\n axes(ah(axisnum));\n hold on\n plot(ah(axisnum),maxSecs, infrasoundEvent(eventNumber).maxAmp(chanNum), 'g*');\n plot(ah(axisnum),minSecs, infrasoundEvent(eventNumber).minAmp(chanNum), 'r*');\n\n end\n feval('print', '-dpng', sprintf('%s/picked_event_%03d',figureOutDirectory, eventNumber) );\n close\nend\nsave spacexplosion.mat\n\n%% Compute relative calibrations of infrasound sensors\nclc\ntolerance = 0.02; % times have to be within 2 hundreds of a second\ncomponent_pairs = [ [1,3]; [1,2]; [2,3] ];\n\nfor component_pair_num = 1:length(component_pairs)\n chanNum = nan(2,1);\n chanNum(1) = component_pairs(component_pair_num, 1);\n chanNum(2) = component_pairs(component_pair_num, 2);\n maxA = nan(2, numEvents);\n minA = nan(2, numEvents);\n for eventNum = 1:numEvents\n ev = infrasoundEvent(eventNum);\n if std(ev.maxTime) < tolerance/86400 & std(ev.minTime) < tolerance/86400\n for c=1:2\n maxA(c, eventNum) = ev.maxAmp(chanNum(c));\n minA(c, eventNum) = ev.minAmp(chanNum(c));\n end\n end\n end\n avA = (maxA - minA)/2;\n\n % first compute raw ratio, mean and std\n ratio = avA(1,:)./avA(2,:);\n m=nanmean(ratio);\n s=nanstd(ratio);\n\n % now recompute after throwing out any measurement that has an error larger\n % than the standard deviation\n ratio2 = ratio(ratio>m-s & ratio0&&abs(v(nv))>opt.maxinno\n exc(i)=1;\n rtk.sat(sat).rejc(rem(j,2)+1)=rtk.sat(sat).rejc(rem(j,2)+1)+1;\n j=j+1; continue;\n end\n \n % record large post-fit residuals\n if post~=0&&abs(v(nv))>sqrt(var(nv))*4\n obsi(ne+1)=i;frqi(ne+1)=j;ve(ne+1)=v(nv);\n ne=ne+1;\n end\n \n if rem(j,2)==0,rtk.sat(sat).vsat(fix(j/2)+1)=1;end\n \n nv=nv+1; \n j=j+1; \n end\n \nend \n\nif nv-1==0\n v=NaN;H=NaN;var=NaN;\nelseif nv-1<2*nobs*nf\n v(nv:end)=[]; H(nv:end,:)=[]; var(nv:end)=[];\nend\nobsi(ne+1:end,:)=[];frqi(ne+1:end,:)=[];ve(ne+1:end,:)=[];\n\n% reject satellite with large and max post-fit residual\nif post~=0 && ne>0\n vmax=ve(1);maxobs=obsi(1);maxfrqi=frqi(1);rej=1; %#ok\n j=2;\n while j<=ne\n if abs(vmax)>=abs(ve(j))\n j=j+1; continue;\n end\n vmax=ve(j);maxobs=obsi(j);maxfrqi=frqi(j);rej=j; %#ok\n j=j+1;\n end\n sat=obs(maxobs).sat;\n exc(maxobs)=1;\n rtk.sat(sat).rejc(rem(j,2)+1)=rtk.sat(sat).rejc(rem(j,2)+1)+1;\n stat=0;\n ve(rej)=0; %#ok\nend\n\n% measurement noise matrix\nif nv-1>0\n R=zeros(nv-1,nv-1);\n for i=1:nv-1\n for j=1:nv-1\n if i==j\n R(i,j)=var(i);\n else\n R(i,j)=0;\n end\n end\n end\nelse\n R=NaN;\nend\n\nif post==0\n stat=nv-1;\nend\n\nreturn\n\n", "meta": {"author": "kaichen686", "repo": "GINav", "sha": "bc6b3ab6c40db996a4fd8e8ca5b748fe21a23666", "save_path": "github-repos/MATLAB/kaichen686-GINav", "path": "github-repos/MATLAB/kaichen686-GINav/GINav-bc6b3ab6c40db996a4fd8e8ca5b748fe21a23666/src/gnss/ppp/ppp_res.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.32955061547952097}} {"text": "% Copyright and terms of use (DO NOT REMOVE):\n% The code is made freely available for non-commercial uses only, provided that the copyright \n% header in each file not be removed, and suitable citation(s) (see below) be made for papers \n% published based on the code.\n%\n% The code is not optimized for speed, and we are not responsible for any errors that might\n% occur in the code.\n%\n% The copyright of the code is retained by the authors. By downloading/using this code you\n% agree to all the terms stated above.\n%\n% Lin, J., Keogh, E., Lonardi, S. & Chiu, B. \n% \"A Symbolic Representation of Time Series, with Implications for Streaming Algorithms.\" \n% In proceedings of the 8th ACM SIGMOD Workshop on Research Issues in Data Mining and \n% Knowledge Discovery. San Diego, CA. June 13, 2003. \n%\n%\n% Lin, J., Keogh, E., Patel, P. & Lonardi, S. \n% \"Finding Motifs in Time Series\". In proceedings of the 2nd Workshop on Temporal Data Mining, \n% at the 8th ACM SIGKDD International Conference on Knowledge Discovery and Data Mining. \n% Edmonton, Alberta, Canada. July 23-26, 2002\n%\n% This function takes in a time series and convert it to string(s).\n% There are two options:\n% 1. Convert the entire time series to ONE string\n% 2. Use sliding windows, extract the subsequences and convert these subsequences to strings\n%\n% For the first option, simply enter the length of the time series as \"N\"\n% ex. We have a time series of length 32 and we want to convert it to a 8-symbol string,\n% with alphabet size 3:\n% timeseries2symbol(data, 32, 8, 3)\n% For the second option, enter the desired sliding window length as \"N\"\n% ex. We have a time series of length 32 and we want extract subsequences of length 32 using\n% sliding windows, and convert the subsequences to 8-symbol strings, with alphabet size 3:\n% timeseries2symbol(data, 16, 8, 3)\n% \n%\n% Input:\n% data is the raw time series. \n% N is the length of sliding window (use the length of the raw time series\n% instead if you don't want to have sliding windows)\n% n is the number of symbols in the low dimensional approximation of the sub sequence.\n% alphabet_size is the number of discrete symbols. 2 <= alphabet_size <= 10, although alphabet_size = 2 is a special \"useless\" case.\n% NR_opt 1: no numerosity reduction (record everything)\n% 2: numerosity reduction (record only if the string is different from the last recorded string)\n% (default)\n% 3: advanced numerosity reduction (record only if the mindist between current string and \n% last recorded string > 0)\n% 4: more reduction (record only if the subsequence is NOT monotonic)\n%\n% Output:\n% symbolic_data: matrix of symbolic data (no-repetition). If consecutive subsequences\n% have the same string, then only the first occurrence is recorded, with\n% a pointer to its location stored in \"pointers\"\n% pointers: location of the first occurrences of the strings\n%\n% N/n must be an integer, otherwise the program will give a warning, and abort.\n%\n% The variable \"win_size\" is assigned to N/n, this is the number of data points on the raw \n% time series that will be mapped to a single symbol, and can be imagined as the \n% \"compression rate\".\n%\n% The symbolic data is returned in \"symbolic_data\", with pointers to the subsequences \n%\n%\n% \n%\n% Copyright (c) 2003, Eamonn Keogh, Jessica Lin, Stefano Lonardi, Pranav Patel. All rights reserved.\n%\nfunction [symbolic_data, pointers] = timeseries2symbol(data, N, n, alphabet_size, NR_opt)\n\nif nargin < 4\n disp('usage: sax_modified(data, window_len, num_segment, alphabet_size, [numerosity_reduction_option]');\n return;\nend\n\n%if (N/n - floor(N/n)) % N/n must be an integer.\n% disp('N/n must be an integer. Aborting '); , return; \n%end; \n\nif alphabet_size > 20\n disp('Currently alphabet_size cannot be larger than 20. Please update the breakpoint table if you wish to do so');\n return;\nend\n\nif nargin < 5\n NR_opt = 2;\nend\n\nwin_size = floor(N/n); % win_size is the number of data points on the raw time series that will be mapped to a single symbol\n\npointers = []; % Initialize pointers,\nsymbolic_data = zeros(1,n); % Initialize symbolic_data with a void string, it will be removed later.\nall_string = zeros(length(data)-N+1,n);\n\n% Scan across the time series extract sub sequences, and converting them to strings.\nfor i = 1 : length(data) - (N -1) \n \n if mod(i, 1000) == 0\n %disp(num2str(i));\n end\n \n % Remove the current subsection.\n sub_section = data(i:i + N -1); \n \n % Z normalize it.\n sub_section = (sub_section - mean(sub_section))/std(sub_section); \n \n % take care of the special case where there is no dimensionality reduction\n if N == n\n PAA = sub_section;\n \n % N is not dividable by n\n else\n if (N/n - floor(N/n)) \n temp = zeros(n, N);\n for j = 1 : n\n temp(j, :) = sub_section;\n end\n expanded_sub_section = reshape(temp, 1, N*n);\n PAA = [mean(reshape(expanded_sub_section, N, n))];\n % N is dividable by n\n else \n PAA = [mean(reshape(sub_section,win_size,n))];\n end\n % Convert to PAA. \n %else\n % PAA = [mean(reshape(sub_section,win_size,n))]; \n end\n \n current_string = map_to_string(PAA,alphabet_size); % Convert the PAA to a string. \n\n % no numerosity reduction: record everything\n if NR_opt == 1\n symbolic_data = [symbolic_data; current_string]; % ... add it to the set...\n pointers = [pointers ; i]; % ... and add a new pointer.\n \n % with numerosity reduction: record a string only if it differs from its leftmost neighbor\n elseif NR_opt == 2\n \n if ~all(current_string == symbolic_data(end,:)) % If the string differs from its leftmost neighbor...\n symbolic_data = [symbolic_data; current_string]; % ... add it to the set...\n pointers = [pointers ; i]; % ... and add a new pointer.\n end;\n \n % advanced numerosity reduction: record a string only if its mindist to the last recorded\n % string > 0\n elseif NR_opt == 3\n\n % always record the first string\n if i == 1\n symbolic_data = [symbolic_data; current_string]; % ... add it to the set...\n pointers = [pointers ; i]; % ... and add a new pointer.\n\n % subsequent strings\n else\n \n % we only need to check if two sliding windows have different strings (if they are\n % the same then their mindist is 0)\n if ~all(current_string == symbolic_data(end,:)) % If the string differs from its leftmost neighbor... \n \n % Here we're doing a simplified version of mindist. Since we're only interested\n % in knowing if the distance of two strings is 0, we can do so without any extra\n % computation. Since only adjacent symbols have distance 0, all we have to\n % do is check if any two symbols are non-adjacent.\n if any(abs(symbolic_data(end,:) - current_string) > 1)\n symbolic_data = [symbolic_data; current_string]; % ... add it to the set...\n pointers = [pointers ; i]; % ... and add a new pointer.\n end\n end\n end\n \n else\n \n \n % we only need to check if two sliding windows have different strings (if they are\n % the same then their mindist is 0)\n if ~all(current_string == symbolic_data(end,:)) % If the string differs from its leftmost neighbor... \n if any(abs(symbolic_data(end,:) - current_string) > 1)\n if ~all(sign(diff(current_string)) >= 0) && ~all(sign(diff(current_string)) <= 0)\n symbolic_data = [symbolic_data; current_string]; % ... add it to the set...\n pointers = [pointers ; i]; % ... and add a new pointer.\n end\n end\n end\n end \n \nend;\n% Delete the first element, it was just used to initialize the data structure\nsymbolic_data(1,:) = []; \n\n%--------------------------------------------------------------------------------------------------------------------------------------------------------\n%----------------Local Functions----------------------Local Functions----------------Local Functions----------------------Local Functions----------------\n%--------------------------------------------------------------------------------------------------------------------------------------------------------\n\nfunction string = map_to_string(PAA,alphabet_size)\n\nstring = zeros(1,length(PAA));\n\nswitch alphabet_size\n case 2, cut_points = [-inf 0];\n case 3, cut_points = [-inf -0.43 0.43];\n case 4, cut_points = [-inf -0.67 0 0.67];\n case 5, cut_points = [-inf -0.84 -0.25 0.25 0.84];\n case 6, cut_points = [-inf -0.97 -0.43 0 0.43 0.97];\n case 7, cut_points = [-inf -1.07 -0.57 -0.18 0.18 0.57 1.07];\n case 8, cut_points = [-inf -1.15 -0.67 -0.32 0 0.32 0.67 1.15];\n case 9, cut_points = [-inf -1.22 -0.76 -0.43 -0.14 0.14 0.43 0.76 1.22];\n case 10, cut_points = [-inf -1.28 -0.84 -0.52 -0.25 0. 0.25 0.52 0.84 1.28];\n case 11, cut_points = [-inf -1.34 -0.91 -0.6 -0.35 -0.11 0.11 0.35 0.6 0.91 1.34];\n case 12, cut_points = [-inf -1.38 -0.97 -0.67 -0.43 -0.21 0 0.21 0.43 0.67 0.97 1.38];\n case 13, cut_points = [-inf -1.43 -1.02 -0.74 -0.5 -0.29 -0.1 0.1 0.29 0.5 0.74 1.02 1.43];\n case 14, cut_points = [-inf -1.47 -1.07 -0.79 -0.57 -0.37 -0.18 0 0.18 0.37 0.57 0.79 1.07 1.47];\n case 15, cut_points = [-inf -1.5 -1.11 -0.84 -0.62 -0.43 -0.25 -0.08 0.08 0.25 0.43 0.62 0.84 1.11 1.5];\n case 16, cut_points = [-inf -1.53 -1.15 -0.89 -0.67 -0.49 -0.32 -0.16 0 0.16 0.32 0.49 0.67 0.89 1.15 1.53];\n case 17, cut_points = [-inf -1.56 -1.19 -0.93 -0.72 -0.54 -0.38 -0.22 -0.07 0.07 0.22 0.38 0.54 0.72 0.93 1.19 1.56];\n case 18, cut_points = [-inf -1.59 -1.22 -0.97 -0.76 -0.59 -0.43 -0.28 -0.14 0 0.14 0.28 0.43 0.59 0.76 0.97 1.22 1.59];\n case 19, cut_points = [-inf -1.62 -1.25 -1 -0.8 -0.63 -0.48 -0.34 -0.2 -0.07 0.07 0.2 0.34 0.48 0.63 0.8 1 1.25 1.62];\n case 20, cut_points = [-inf -1.64 -1.28 -1.04 -0.84 -0.67 -0.52 -0.39 -0.25 -0.13 0 0.13 0.25 0.39 0.52 0.67 0.84 1.04 1.28 1.64];\n otherwise disp('Error! alphabet_size is too big'); \nend;\n \nfor i = 1 : length(PAA) \n string(i) = sum( (cut_points <= PAA(i)), 2 ); % order is now: a = 1, b = 2, c = 3..\nend; ", "meta": {"author": "dsmi-lab-ntust", "repo": "AnomalyDetectionToolbox", "sha": "b9385ba405026f56a008f88c0580b1a18e24b355", "save_path": "github-repos/MATLAB/dsmi-lab-ntust-AnomalyDetectionToolbox", "path": "github-repos/MATLAB/dsmi-lab-ntust-AnomalyDetectionToolbox/AnomalyDetectionToolbox-b9385ba405026f56a008f88c0580b1a18e24b355/Algorithms/distanceBased/HOTSAX/timeseries2symbol.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5660185205547239, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.3290283153603828}} {"text": "function res = PDD_Profile_res(params, doseV_obj, doseV_array,doseV_arrayFF, doseV_e, ...\n doseProfile1_obj, doseP1p5cm_array, doseP1p5cm_arrayFF, doseP1p5cm_e, ...\n doseProfile2_obj, doseP5cm_array, doseP5cm_arrayFF, doseP5cm_e, ...\n doseProfile3_obj, doseP10cm_array, doseP10cm_arrayFF, doseP10cm_e, ...\n doseProfile4_obj, doseP20cm_array, doseP20cm_arrayFF, doseP20cm_e, ...\n energy, numBin, extraBin, numBinFF)\n%\n% Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team.\n% \n% This file is part of The Computational Environment for Radiotherapy Research (CERR).\n% \n% CERR development has been led by: Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy.\n% \n% CERR has been financially supported by the US National Institutes of Health under multiple grants.\n% \n% CERR is distributed under the terms of the Lesser GNU Public License. \n% \n% This version of CERR is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% CERR is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;\n% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n% See the GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with CERR. If not, see .\n\n\n%Start the function.\n%Calculate the residue of the PDD and dose profile difference between DPM and the measurement.\n\ndoseV_sum = zeros(size(doseV_obj));\n\nener = energy/numBin: energy/numBin:energy*(1+extraBin/numBin);\na = Fatigue(params(1:4), ener);\na(find(isnan(a))) = 0;\n\ncutoff = 0.85;\nEf = energy*cutoff;\nkt = energy*0.15; % change kt\nf = 1./(1+exp((ener-Ef)/kt));\na = a.*f;\n\n% Sum the contribution of primary and \"OnlyHorn\" effect\ndoseV_sum = (doseV_array) * real(a)';\ndoseProfile1_sum = (doseP1p5cm_array) * real(a)';\ndoseProfile2_sum = (doseP5cm_array) * real(a)';\ndoseProfile3_sum = (doseP10cm_array) * real(a)';\ndoseProfile4_sum = (doseP20cm_array) * real(a)';\n\n\n% Get the weights/spectrum for the flattening filter\nenerFF = energy/numBin : energy/numBin : numBinFF*energy/numBin;\naFF = Fatigue(params(1:4), params(5)* enerFF);\naFF(find(isnan(aFF))) = 0;\n\n% Get modified Flattening filter spectrum/weights \nf = 1./(1+exp((params(5)*enerFF-Ef)/kt));\naFF = aFF.* f;\naFF = aFF * (sum(a)/sum(aFF)*params(6)) ; % scale FF weight respect to sum(a)\n\n%calculate the dose contribution of the flattening filter\ndoseV_sumFF = doseV_arrayFF * real(aFF)';\ndoseProfile1_sumFF = doseP1p5cm_arrayFF * real(aFF)';\ndoseProfile2_sumFF = doseP5cm_arrayFF * real(aFF)';\ndoseProfile3_sumFF = doseP10cm_arrayFF * real(aFF)';\ndoseProfile4_sumFF = doseP20cm_arrayFF * real(aFF)';\n\n% Nov. 1 2006 \n% Add the asd\nfilterSize = 7;\nfilterWindow = [-3 -2 -1 0 1 2 3];\nG1 = gauss(filterWindow, params(9)); %p(9) is sigma\nG1 = G1/sum(G1); % normalize, to make sum(G1)==1;\n\ndoseV_DPM = doseV_sum + doseV_sumFF + params(8) * sum(a)* doseV_e;\ndoseProfile1_DPM = doseProfile1_sum + doseProfile1_sumFF + params(8) * sum(a)* doseP1p5cm_e;\ndoseProfile1_DPM = conv(G1, doseProfile1_DPM);\ndoseProfile2_DPM = doseProfile2_sum + doseProfile2_sumFF + params(8) * sum(a)* doseP5cm_e;\ndoseProfile2_DPM = conv(G1, doseProfile2_DPM);\ndoseProfile3_DPM = doseProfile3_sum + doseProfile3_sumFF + params(8) * sum(a)* doseP10cm_e;\ndoseProfile3_DPM = conv(G1, doseProfile3_DPM);\ndoseProfile4_DPM = doseProfile4_sum + doseProfile4_sumFF + params(8) * sum(a)* doseP20cm_e;\ndoseProfile4_DPM = conv(G1, doseProfile4_DPM);\n \n% Use relative weight for PDD as 5; for lateral dose profile, use weight\n% as 1. \n% for doseV_obj, dose different absolute dose value make a difference?\n% Should it be weighed by the dose values at those points?\n\ndiffsqr = 1.0*sum ((doseV_obj - doseV_DPM).^2) ...\n + sum((doseProfile1_obj - doseProfile1_DPM(4:end-3)).^2) ...\n + sum((doseProfile2_obj - doseProfile2_DPM(4:end-3)).^2) ...\n + sum((doseProfile3_obj - doseProfile3_DPM(4:end-3)).^2) ...\n + sum((doseProfile4_obj - doseProfile4_DPM(4:end-3)).^2);\nres = sqrt(diffsqr);\nreturn;", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/IMRTP/recompDose/MC/BeamModelCommission/PDD_Profile_res.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8152325073083132, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.3290008180372167}} {"text": "%-------------------------------------------------------------------------------------------------------------------%\n%\n% IB2d is an Immersed Boundary Code (IB) for solving fully coupled non-linear \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: nick.battista@unc.edu\n% Date Created: September 9th, 2016\n% Institution: UNC-CH\n%\n% This code is capable of creating Lagrangian Structures using:\n% \t1. Springs\n% \t2. Beams (*torsional springs)\n% \t3. Target Points\n%\t4. Muscle-Model (combined Force-Length-Velocity model, \"HIll+(Length-Tension)\")\n%\n% One is able to update those Lagrangian Structure parameters, e.g., spring constants, resting %%\tlengths, 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 (nick.battista@unc.edu) know.\n%\n%--------------------------------------------------------------------------------------------------------------------%\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: creates the geometry and prints associated input files\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction Make_Your_Plates_and_Input_Files()\n\n%\n% Grid Parameters (MAKE SURE MATCHES IN input2d !!!)\n%\nNx = 64; % # of Eulerian Grid Pts. in x-Direction (MUST BE EVEN!!!)\nLx = 1.0; % Length of Eulerian Grid in x-Direction\ndx = Lx/Nx; % Grid spatial resolution\n\n%\n% Immersed Structure Geometric / Dynamic Parameters %\n%\nds = 0.5*dx; % Lagrangian Pt. Spacing (2x resolution of Eulerian grid)\nstruct_name = 'corals'; % Name for .vertex, .spring, etc files. (must match what's in 'input2d')\n\n\n% Call function to construct geometry\n[xLag,yLag] = give_Me_Immsersed_Boundary_Geometry(ds,Nx,Lx);\n\n\n% Plot Geometry to test\nplot(xLag,yLag,'r-'); hold on;\nplot(xLag,yLag,'*'); hold on;\nxlabel('x'); ylabel('y');\naxis([0 Lx 0 Lx]);\n\n\n% Prints .vertex file!\nprint_Lagrangian_Vertices(xLag,yLag,struct_name);\n\n\n% Prints .spring file!\n% k_Spring = 2.5e4; % Spring stiffness (does not need to be equal for all springs)\n% ds_Plates = dist; % Spring resting length (does not need to be equal for all springs)\n% print_Lagrangian_Springs(xLag,yLag,k_Spring,ds_Plates,ds,struct_name);\n\n\n% Prints .beam file!\n% k_Beam = 0.5; % Beam Stiffness (does not need to be equal for all beams)\n% C = compute_Curvatures(xLag,yLag) % Computes curvature of initial configuration\n%print_Lagrangian_Beams(xLag,yLag,k_Beam,C,struct_name);\n\n\n% Prints .target file!\nk_Target = 1e7;\nprint_Lagrangian_Target_Pts(xLag,k_Target,struct_name);\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: prints VERTEX points to a file called 'struct_name'.vertex\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction print_Lagrangian_Vertices(xLag,yLag,struct_name)\n\n N = length(xLag); % Total # of Lag. Pts\n\n vertex_fid = fopen([struct_name '.vertex'], 'w');\n\n fprintf(vertex_fid, '%d\\n', N );\n\n %Loops over all Lagrangian Pts.\n for s = 1:N\n X_v = xLag(s);\n Y_v = yLag(s);\n fprintf(vertex_fid, '%1.16e %1.16e\\n', X_v, Y_v);\n end\n\n fclose(vertex_fid);\n\n \n \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: prints SPRING points to a file called 'struct_name'.spring\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction print_Lagrangian_Springs(xLag,yLag,k_Spring,ds_Plates,ds,struct_name)\n\n N = length(xLag);\n\n spring_fid = fopen([struct_name '.spring'], 'w');\n\n fprintf(spring_fid, '%d\\n', N-2 + N/2 ); % Print # of springs \n\n %SPRINGS BETWEEN VERTICES\n for s = 1:N\n if s < N/2 \n fprintf(spring_fid, '%d %d %1.16e %1.16e\\n', s, s+1, k_Spring, ds); \n elseif s > N/2\n fprintf(spring_fid, '%d %d %1.16e %1.16e\\n', s, s+1, k_Spring, ds); \n end\n end\n \n % SPRINGS ACROSS PLATES\n for s=1:N/2\n fprintf(spring_fid, '%d %d %1.16e %1.16e\\n', s, s+N/2, k_Spring, ds_Plates); \n end\n \n fclose(spring_fid); \n \n \n \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: prints TARGET points to a file called 'struct_name'.vertex\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction print_Lagrangian_Target_Pts(xLag,k_Target,struct_name)\n\n N = length(xLag);\n\n target_fid = fopen([struct_name '.target'], 'w');\n\n fprintf(target_fid, '%d\\n', N );\n\n %Loops over all Lagrangian Pts.\n for s = 1:N\n fprintf(target_fid, '%d %1.16e\\n', s, k_Target);\n end\n\n fclose(target_fid); \n \n \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: prints BEAM (Torsional Spring) points to a file called 'struct_name'.beam\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction print_Lagrangian_Beams(xLag,yLag,k_Beam,C,struct_name)\n\n % k_Beam: beam stiffness\n % C: beam curvature\n \n N = length(xLag); % NOTE: Total number of beams = Number of Total Lag Pts. - 2\n\n beam_fid = fopen([struct_name '.beam'], 'w');\n\n fprintf(beam_fid, '%d\\n', N );\n\n %spring_force = kappa_spring*ds/(ds^2);\n\n %BEAMS BETWEEN VERTICES\n for s = 2:N-1\n if s <= N-1 \n fprintf(beam_fid, '%d %d %d %1.16e %1.16e\\n',s-1, s, s+1, k_Beam, C(s) ); \n else\n %Case s=N\n fprintf(beam_fid, '%d %d %d %1.16e %1.16e\\n',s-1, s, 1, k_Beam, C(s) ); \n end\n end\n fclose(beam_fid); \n \n \n \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: computes \"curvature\" of starting configuration\n% \n% NOTE: not curvature in the traditional geometric sense, in the 'discrete'\n% sense through cross product.\n%\n% NOTE: assumes a CLOSED structure\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction C = compute_Curvatures(xLag,yLag)\n\nN = length(xLag);\nC = zeros( N );\n\n%Note: needs to be done same order as you print .beam file!\nfor i=1:N\n \n % Pts Xp -> Xq -> Xr (same as beam force calc.)\n \n if ( (i > 1) && (i < N) )\n \n Xp = xLag(i-1); Xq = xLag(i); Xr = xLag(i+1);\n Yp = yLag(i-1); Yq = yLag(i); Yr = yLag(i+1);\n \n elseif (i==1)\n \n Xp = xLag(N); Xq = xLag(i); Xr = xLag(i+1);\n Yp = yLag(N); Yq = yLag(i); Yr = yLag(i+1);\n \n elseif (i==N)\n \n Xp = xLag(N-1); Xq = xLag(N); Xr = xLag(1);\n Yp = yLag(N-1); Yq = yLag(N); Yr = yLag(1);\n \n end\n \n C(i) = (Xr-Xq)*(Yq-Yp) - (Yr-Yq)*(Xq-Xp); %Cross product btwn vectors\n \nend\n \n \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: creates the Lagrangian structure geometry\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n \nfunction [xLag,yLag] = give_Me_Immsersed_Boundary_Geometry(ds,Nx,L)\n\n% ds: Lagrangian pt. spacing\n% Nx: Eulerian grid resolution\n% L: Length of computational domain\n\nratio = 1024 / (2*Nx);\n\n% Gives LEFT Coral\n[x1,y1,N] = please_Give_Single_Polyp_Geometry(ratio);\nx1 = x1 + L/10;\n\n% Makes RIGHT Coral\nx2 = x1 + L/5;\ny2 = y1;\n\n% TESTS GEOMETRY BY PLOTTING\nplot(x1,y1,'k*'); hold on;\nplot(x1(1),y1(1),'g*'); hold on;\nplot(x1(end/2),y1(end/2),'b*'); hold on;\nplot(x1(end/2+1),y1(end/2+1),'g*'); hold on;\nplot(x1(end),y1(end),'b*'); hold on;\n%\nplot(x2,y2,'r*'); hold on;\nplot(x2(1),y2(1),'g*'); hold on;\nplot(x2(end/2),y2(end/2),'b*'); hold on;\nplot(x2(end/2+1),y2(end/2+1),'g*'); hold on;\nplot(x2(end),y2(end),'b*'); hold on;\n\nxRef = [x1 x2]; yRef = [y1 y2]; \nang = pi/4;\n\n% Store Values for Centers of Rotation\nxL_1 = xRef(1); yL_1 = yRef(1); % Left side of Left Pair\nxR_1 = xRef(end/4+1); yR_1 = yRef(end/4+1); % Right side of Left Pair\n\nxL_2 = xRef(end/2+1); yL_2 = yRef(end/2+1); % Left side of Right Pair\nxR_2 = xRef(3*end/4+1); yR_2 = yRef(3*end/4+1); % Right side of Right Pair\n\n% -> Rotate Geometry <- %\n% LEFT PAIR %\n[xR_Ref_1,yR_Ref_1] = rotate_Geometry(ang,xR_1,yR_1,xRef(end/4+1:end/2),yRef(end/4+1:end/2) );\n[xL_Ref_1,yL_Ref_1] = rotate_Geometry(-ang,xL_1,yL_1,xRef(1:end/4),yRef(1:end/4) );\n% RIGHT PAIR %\n[xR_Ref_2,yR_Ref_2] = rotate_Geometry(ang,xR_2,yR_2,xRef(3*end/4+1:end),yRef(3*end/4+1:end) );\n[xL_Ref_2,yL_Ref_2] = rotate_Geometry(-ang,xL_2,yL_2,xRef(end/2+1:3*end/4),yRef(end/2+1:3*end/4) );\n\nxLag = [xL_Ref_1 xR_Ref_1 xL_Ref_2 xR_Ref_2];\nyLag = [yL_Ref_1 yR_Ref_1 yL_Ref_2 yR_Ref_2];\n\nplot(xLag,yLag,'ro'); hold on;\naxis([0 1 0 1]);\n\n% Combine into ONE Vector\n%xLag = [xLag_L xLag_R];\n%yLag = [yLag yLag];\n\n% Plot the Geometry\n% plot(xLag,yLag,'*'); hold on;\n% axis([0 L 0 L]);\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: rotate geometry\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [x,y] = rotate_Geometry(ang,xC,yC,xRef,yRef)\n\nlen = length(xRef);\nx = zeros(1,len); y=x;\n\nxRef = xRef - xC;\nyRef = yRef - yC;\n\nfor i=1:len\n x(i) = xRef(i)*cos(ang) - yRef(i)*sin(ang);\n y(i) = xRef(i)*sin(ang) + yRef(i)*cos(ang);\nend\n\nx = x + xC;\ny = y + yC;\n\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: Reads in the vertices for one coral polyp\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [x,y,N] = please_Give_Single_Polyp_Geometry(ratio)\n\nxoffset = 0.3; % To put geometry into QUADRANT-1\nyoffset = 0.5; % To put geometry into QUADRANT-1\n\n% Note: (1) ds for stored data is 0.6/(2*1024)\n% (2) 'ratio' is comparing 1024:desired resolution\n\n% Get LEFT side geometry\nstruct_name1 = 'coral2d_left_1024';\n[~,x1,y1] = read_Vertex_Points(struct_name1);\n\n% Reverse order so first point is on bottom\nx1 = x1(end:-1:1); y1 = y1(end:-1:1);\n\n% Get RIGHT side geometry\nstruct_name2 = 'coral2d_right_1024';\n[~,x2,y2] = read_Vertex_Points(struct_name2);\n\n% Reverse order so first point is on bottom\nx2 = x2(end:-1:1); y2 = y2(end:-1:1);\n\n% Put Geometry Together for One Polyp\nxAux = [x1; x2]; yAux = [y1; y2];\nxAux = xAux+xoffset; yAux = yAux+yoffset;\n\n% Pull out correct resolution\nx=xAux(1:ratio:end)';\ny=yAux(1:ratio:end)';\nN = length(x)/2;\n\n\n%plot(xAux,yAux,'*'); hold on;\n%plot(x,y,'ro'); hold on;\n\n%NOTE: (1) N here is the # of pts. on one arm (NOT ENTIRE POLYP)!!\n% (2) The geometry here is listed for 1024x1024 meshes -> will need\n% to take every 8 or 16 pts to render geometry usable for MATLAB\n% code\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: Reads in the # of vertex pts and all the vertex pts from the\n% .vertex file.\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [N,xLag,yLag] = read_Vertex_Points(struct_name)\n\nfilename = [struct_name '.vertex']; %Name of file to read in\nfileID = fopen(filename);\n\n% Read in the file, use 'CollectOutput' to gather all similar data together\n% and 'CommentStyle' to to end and be able to skip lines in file.\nC = textscan(fileID,'%f %f','CollectOutput',1);\n\n\nfclose(fileID); %Close the data file.\n\nvertices = C{1}; %Stores all read in data in vertices (N+1,2) array\n\nN = vertices(1,1); % # of Lagrangian Pts\nxLag = zeros(N,1); % Initialize storage for Lagrangian Pts.\nyLag = xLag; % Initialize storage for Lagrangian Pts.\n\nfor i=1:N\n xLag(i,1) = vertices(i+1,1); %Stores x-values of Lagrangian Mesh\n yLag(i,1) = vertices(i+1,2); %Stores y-values of Lagrangian Mesh\n \nend\n\n\n", "meta": {"author": "nickabattista", "repo": "IB2d", "sha": "392d99c228cc801ff65766889c72e2e1492fe747", "save_path": "github-repos/MATLAB/nickabattista-IB2d", "path": "github-repos/MATLAB/nickabattista-IB2d/IB2d-392d99c228cc801ff65766889c72e2e1492fe747/matIB2d/Examples/Examples_First_Year_Seminar/Corals/Make_Your_Plates_and_Input_Files.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6791786861878392, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.32898062925479704}} {"text": "function [Ain, Cin, b_in, f_in, center, res] = greedyROI(Y, K, params, ROI_list)\n% component initialization using a greedy algorithm to identify neurons in 2d or 3d calcium imaging movies\n%\n% Usage: [Ain, Cin, bin, fin, center, res] = greedyROI2d(data, K, params)\n%\n% Input:\n% Y d1 x d2 x (d3 x) T movie, raw data, each column is a vectorized movie\n% K number of neurons to extract (if K is a vector then the algorithm is run multiple times with different parameters)\n% params tuning parameter for fine-tuning the shape (optional)\n% params.nIter: number of iterations for shape tuning (default 5)\n% params.gSig: variance of Gaussian kernel to use (default 5) If params.gSig is a cell, then the algorithm is run with multiple times with different parameters\n% params.gSiz: size of kernel (default 2*gSiz+1)\n% params.nb: rank of background component (default 1)\n% params.save_memory: flag for processing data in chunks to save memory (default 0)\n% params.windowSiz: size of spatial window when computing the median (default 32 x 32)\n% params.chunkSiz: number of timesteps to be processed simultaneously if on save_memory mode (default: 100)\n% params.med_app: number of timesteps to be interleaved for fast (approximate) median calculation (default: 1, no approximation)\n% params.rolling_sum: flag for using rolling sum to detect new components (default: True)\n% params.rolling_length: length of rolling window (default: 100)\n% ROI_list Kn x 2 (or 3) matrix with user specified centroids. If this are present, then the algorithm only finds components around these centroids\n\n%Output:\n% Ain (d) x K matrix, location of each neuron\n% Cin T x K matrix, calcium activity of each neuron\n% center K x 2 (or 3) matrix, inferred center of each neuron\n% bin (d) X nb matrix, initialization of spatial background\n% fin nb X T matrix, initalization of temporal background\n% res d1 x d2 x (d3 x) T movie, residual\n%\n% Author: Yuanjun Gao with modifications from Eftychios A. Pnevmatikakis and Weijian Yang\n\nuse_sum = false;\nif nargin < 4 || isempty(ROI_list)\n user_ROIs = 0;\nelse\n user_ROIs = 1;\n K = size(ROI_list,1);\nend\n\ndimY = ndims(Y) - 1; % dimensionality of imaged data (2d or 3d)\nsizY = size(Y);\nT = sizY(end); % # of timesteps\ndx = sizY(1:dimY); % # of voxels in each axis\nd = prod(dx); % total # of voxels \n\nif ~exist('K', 'var'), %find K neurons\n K = 30; \n warning(['number of neurons are not specified, set to be the default value', num2str(K)]);\nend\n\nif ~exist('params', 'var') params = []; end\n\nif ~isfield(params, 'gSig') || isempty(params.gSig); \n if dimY == 2; params.gSig = [5, 5]; else params.gSig = [5,5,5]; end\nelseif length(params.gSig) == 1, params.gSig = params.gSig + zeros(1,dimY);\n if dimY == 3; params.gSig(3) = params.gSig(3)/2; end\nend\n\nif ~isfield(params, 'gSiz') || isempty(params.gSiz); \n if ~iscell(params.gSig)\n params.gSiz = ceil(2*params.gSig + 1);\n else\n for j = 1:length(params.gSig)\n params.gSiz{j,1} = 2*params.gSig{j}+1; %cellfun(@times,params.gSig{j},num2cell(ones(size(params.gSig{j}))*2));\n end\n end\nelseif length(params.gSiz) == 1, params.gSiz = params.gSiz + zeros(1,dimY);\n if dimY == 3; params.gSiz(3) = ceil(params.gSiz(3)/2); end\nend\n\nif isfield(params,'ssub'); \n if ~iscell(params.gSig); params.gSig(1:2) = params.gSig(1:2)/params.ssub; params.gSiz(1:2) = ceil(params.gSiz(1:2)/params.ssub); \n else\n for j = 1:length(params.gSig)\n params.gSig{j,1} = params.gSig{j}/params.ssub; %cellfun(@times,params.gSig{j},num2cell(ones(size(params.gSig{j}))/params.ssub));\n params.gSiz{j,1} = params.gSiz{j}/params.ssub; %cellfun(@times,params.gSiz{j},num2cell(ones(size(params.gSiz{j}))/params.ssub));\n end\n end\nend\n\nif ~isfield(params,'nb'), nb = 1; else nb = params.nb; end\n\nif ~isfield(params, 'nIter'), nIter = 5; \nelse nIter = params.nIter; end\n\nif ~isfield(params, 'save_memory'), save_memory = 0;\nelse save_memory = params.save_memory; end\n \nif ~isfield(params, 'chunkSiz'), chunkSiz = 100; else chunkSiz = params.chunkSiz; end\nif ~isfield(params, 'windowSiz'), windowSiz = 32; else windowSiz = params.windowSiz; end\nif ~isfield(params, 'med_app'), med_app = 1; else med_app = params.med_app; end\n\nif ~isfield(params,'rem_prct') || isempty(params.rem_prct); params.rem_prct = 20; end\n\nTint = 1:med_app:T;\n% if save_memory\n% med = zeros(M,N);\n% for ii = 1:ceil(M/windowSiz)\n% intx = (ii-1)*windowSiz+1:min(ii*windowSiz,M);\n% for jj = 1:ceil(N/windowSiz)\n% inty = (jj-1)*windowSiz+1:min(jj*windowSiz,N);\n% med(intx,inty) = median(data(intx,inty,Tint),3);\n% end\n% end \n% else\n%if dimY == 2; med = median(Y(:,:,Tint), 3); else med = median(Y(:,:,:,Tint), 4); end\nif dimY == 2; med = prctile(Y(:,:,Tint),params.rem_prct, 3); else med = prctile(Y(:,:,:,Tint),params.rem_prct,4); end\n\n% end\n\nY = bsxfun(@minus, Y, med);\nif iscell(params.gSig); params.gSig = cell2mat(params.gSig); params.gSiz = cell2mat(params.gSiz); end\nif length(K) > 1 % order size of components to be found in descending order\n [~,ord] = sort(sum(params.gSig,2),'descend');\n K = K(ord);\n params.gSig = params.gSig(ord,:);\n params.gSiz = params.gSiz(ord,:);\nend\n\nif ~iscell(params.gSiz)\n Ain = spalloc(d,sum(K),K(:)'*ceil(params.gSiz(:,1).^2)); %zeros(M*N,sum(K));\nelse\n Ain = sparse(d,sum(K));\nend\nCin = zeros(sum(K),T);\ncenter = zeros(sum(K),dimY);\n\nfor r = 1:length(K)\n gSig = params.gSig(r,:);\n gSiz = params.gSiz(r,:);\n \n gHalf = floor(gSiz / 2); %half size of the kernel, used to calculate margin\n gSiz = 2 * gHalf + 1; %actual size\n\n Atemp = spalloc(d,K(r),K(r)*ceil(prod(gSiz))); %zeros(M, N, K(r));\n %basis = spalloc(M*N,K,K*prod(gSiz));\n trace = zeros(T, K(r));\n centers = zeros(K(r), dimY);\n\n\n %scan the whole image (only need to do this at the first iteration)\n rho = imblur(Y, gSig, gSiz, dimY, save_memory, chunkSiz); %covariance of data and basis\n \n if ~params.rolling_sum\n v = sum(rho.^2, dimY+1); %variance explained\n else\n % running maximum\n avg_fil = ones(1,params.rolling_length)/params.rolling_length;\n rho_s = filter(avg_fil,1,rho.^2,[],dimY+1);\n v = max(rho_s,[],dimY+1);\n end\n \n for k = 1:K(r), \n if user_ROIs\n iHat = ROI_list(k,:);\n else\n [~, ind] = max(v(:));\n %[iHat, jHat] = ind2sub([M, N], ind);\n iHat = zeros(1,dimY);\n if dimY == 2; [iHat(1),iHat(2)] = ind2sub(dx,ind); else [iHat(1),iHat(2),iHat(3)] = ind2sub(dx,ind); end \n end\n centers(k,:) = round(iHat);\n\n %iSig = [max(iHat - gHalf(1), 1), min(iHat + gHalf(1), M)]; iSigLen = iSig(2) - iSig(1) + 1;\n %jSig = [max(jHat - gHalf(2), 1), min(jHat + gHalf(2), N)]; jSigLen = jSig(2) - jSig(1) + 1;\n iSig = [max(iHat - gHalf,1)', min(iHat + gHalf,dx)']; iSigLen = iSig(:,2) - iSig(:,1) + 1;\n \n %fine tune the shape\n if dimY == 2\n dataTemp = Y(iSig(1,1):iSig(1,2), iSig(2,1):iSig(2,2), :);\n traceTemp = squeeze(rho(iHat(1), iHat(2), :));\n else\n dataTemp = Y(iSig(1,1):iSig(1,2), iSig(2,1):iSig(2,2), iSig(3,1):iSig(3,2), :);\n traceTemp = squeeze(rho(iHat(1), iHat(2), iHat(3), :));\n end\n [coef, score] = finetune(dataTemp, traceTemp, nIter); \n\n dataSig = bsxfun(@times, coef, reshape(score, [ones(1,dimY),T]));\n %[xSig,ySig] = meshgrid(iSig(1):iSig(2),jSig(1):jSig(2));\n basis = zeros(dx);\n if dimY == 2; basis(iSig(1,1):iSig(1,2), iSig(2,1):iSig(2,2)) = coef; else basis(iSig(1,1):iSig(1,2), iSig(2,1):iSig(2,2), iSig(3,1):iSig(3,2)) = coef; end\n Atemp(:,k) = basis(:);\n %basis(sub2ind([M,N],xSig(:),ySig(:)),k) = coef(:);\n \n trace(:, k) = score';\n \n if dimY == 2;\n Y(iSig(1,1):iSig(1,2), iSig(2,1):iSig(2,2), :) = Y(iSig(1,1):iSig(1,2), iSig(2,1):iSig(2,2), :) - dataSig; %update residual\n else\n Y(iSig(1,1):iSig(1,2), iSig(2,1):iSig(2,2), iSig(3,1):iSig(3,2), :) = Y(iSig(1,1):iSig(1,2), iSig(2,1):iSig(2,2), iSig(3,1):iSig(3,2),:) - dataSig;\n end\n \n if mod(k,10) == 0; fprintf('found %i out of %i neurons..\\n', k,K(r)); end\n\n %get next basis;\n if k < K(r)\n %iMod = [max(iHat - 2 * gHalf(1), 1), min(iHat + 2 * gHalf(1), M)]; iModLen = iMod(2) - iMod(1) + 1;%patches to modify\n %jMod = [max(jHat - 2 * gHalf(2), 1), min(jHat + 2 * gHalf(2), N)]; jModLen = jMod(2) - jMod(1) + 1;\n iMod = [max(iHat - 2*gHalf,1)', min(iHat + 2*gHalf,dx)']; iModLen = iMod(:,2) - iMod(:,1) + 1;\n %iLag = iSig - iMod(1) + 1; %relative location of iSig in the small patch\n %jLag = jSig - jMod(1) + 1;\n iLag = iSig - repmat(iMod(:,1),1,2) + 1;\n %dataTemp = zeros(iModLen, jModLen);\n dataTemp = zeros(iModLen(:)');\n %dataTemp(iLag(1):iLag(2), jLag(1):jLag(2)) = reshape(coef, [iSigLen, jSigLen]);\n if dimY == 2\n dataTemp(iLag(1,1):iLag(1,2), iLag(2,1):iLag(2,2)) = reshape(coef, iSigLen(:)');\n else\n dataTemp(iLag(1,1):iLag(1,2), iLag(2,1):iLag(2,2), iLag(3,1):iLag(3,2)) = reshape(coef, iSigLen(:)');\n end\n dataTemp = imblur(dataTemp, gSig, gSiz, dimY, 0, chunkSiz);\n rhoTemp = bsxfun(@times, dataTemp, reshape(score, [ones(1,dimY),T]));\n if dimY == 2\n rhoTemp = rho(iMod(1,1):iMod(1,2), iMod(2,1):iMod(2,2), :) - rhoTemp;\n rho(iMod(1,1):iMod(1,2), iMod(2,1):iMod(2,2), :) = rhoTemp;\n if ~params.rolling_sum\n v(iMod(1,1):iMod(1,2), iMod(2,1):iMod(2,2)) = sum(rhoTemp.^2, 3);\n else\n rho_filt = filter(avg_fil,1,rhoTemp.^2,[],3);\n v(iMod(1,1):iMod(1,2), iMod(2,1):iMod(2,2)) = max(rho_filt,[],3);\n end\n else\n rhoTemp = rho(iMod(1,1):iMod(1,2), iMod(2,1):iMod(2,2), iMod(3,1):iMod(3,2), :) - rhoTemp;\n rho(iMod(1,1):iMod(1,2), iMod(2,1):iMod(2,2), iMod(3,1):iMod(3,2), :) = rhoTemp;\n if ~params.rolling_sum\n v(iMod(1,1):iMod(1,2), iMod(2,1):iMod(2,2), iMod(3,1):iMod(3,2)) = sum(rhoTemp.^2, 4);\n else\n rho_filt = filter(avg_fil,1,rhoTemp.^2,[],4);\n v(iMod(1,1):iMod(1,2), iMod(2,1):iMod(2,2), iMod(3,1):iMod(3,2)) = max(rho_filt,[],4);\n end\n end\n end\n end\n Ain(:,sum(K(1:r-1))+1:sum(K(1:r))) = Atemp; %sparse(reshape(basis,d,K(r))); \n Cin(sum(K(1:r-1))+1:sum(K(1:r)),:) = trace';\n center(sum(K(1:r-1))+1:sum(K(1:r)),:) = centers;\nend\nres = reshape(Y,d,T) + repmat(med(:),1,T);\n\n%% clear data matrix from local memory (avoid out-of-memory? see greedyROI_corr.m)\nclear Y\n\n%[b_in,f_in] = nnmf(max(res,0),nb);\n%[b_in,f_in] = nnsvd(max(res,0),nb);\nf_in = [mean(res);rand(nb-1,T)];\n\nfor nmfiter = 1:100\n b_in = max((res*f_in')/(f_in*f_in'),0); \n f_in = max((b_in'*b_in)\\(b_in'*res),0);\nend\n\n\nfunction [ain,cin] = finetune(data,cin,nIter)\n \n %rank-1 semi-NMF to fine tune the inferred components\n %\n %Input:\n %data d1 x d2 x (d3 x) T matrix, small patch containing one neuron\n %trace initial value for trace\n %nIter number of coordinate descent steps\n %\n %Output:\n %basis d1 x d2 (x d3) matrix, result of the fine-tuned neuron shape\n %trace 1 x T matrix, result of the neuron\n \n if ~exist('nIter', 'var'), nIter = 1; end\n data = reshape(data,prod(iSigLen),T);\n for iter = 1:nIter\n %nc = norm(cin)^2;\n ain = max(data*cin,0)/norm(cin);\n an = norm(ain);\n if an > 0\n ain = ain/an;\n else\n fprintf('found degenerate component!\\n')\n \n %break\n end\n cin = data'*ain;\n end\n ain = reshape(ain,iSigLen(:)');\n cin = cin(:)';\nend\n\nfunction data = imblur(data, sig, siz, nDimBlur, save_memory, chunkSiz)\n%Gaussian blur for high dimensional data\n%Input:\n%data original data\n%sig std of gaussian kernel\n%siz size of kernel\n%nDimBlur number of dims to blur (default: ndims(data) - 1)\n%\n%Output:\n%data result after the Gaussian blur\n\nif ~exist('nDimBlur', 'var'), nDimBlur = ndims(data) - 1; \nelse nDimBlur = min(nDimBlur, ndims(data)); end\n\nif length(sig) == 1, sig = sig * ones(1,nDimBlur); end\nassert(nDimBlur == length(sig));\n\nif length(siz) == 1, siz = siz * ones(1,nDimBlur); end\nassert(nDimBlur == length(siz));\n\nfor i = 1:nDimBlur,\n if sig(i) > 0,\n x = -floor(siz(i) / 2):floor(siz(i) / 2);\n H = exp(-(x.^2/ (2 * sig(i)^2)));\n H = H' / norm(H(:));\n if nDimBlur > 1,\n indH = 1:nDimBlur; indH(i) = 1; indH(1) = i;\n H = permute(H, indH);\n end\n if save_memory\n L = size(data,ndims(data));\n for ci = 1:ceil(L/chunkSiz)\n int = (ci-1)*chunkSiz+1:min(ci*chunkSiz,L);\n data(:,:,int) = imfilter(data(:,:,int), H, 'same', 0);\n end\n else\n data = imfilter(data, H, 'same', 0);\n end\n end\nend\nend\n\nend\n", "meta": {"author": "flatironinstitute", "repo": "CaImAn-MATLAB", "sha": "49b7884e93348d50df7173e1619d7499468bb1f6", "save_path": "github-repos/MATLAB/flatironinstitute-CaImAn-MATLAB", "path": "github-repos/MATLAB/flatironinstitute-CaImAn-MATLAB/CaImAn-MATLAB-49b7884e93348d50df7173e1619d7499468bb1f6/utilities/greedyROI.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7185944046238981, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.3284958868603771}} {"text": "function obj = t3_hand_eye_func_new(in1,in2,in3)\ncoefs_tq1_1 = in2(1);\ncoefs_tq1_2 = in2(4);\ncoefs_tq1_3 = in2(7);\ncoefs_tq1_4 = in2(10);\ncoefs_tq1_5 = in2(13);\ncoefs_tq1_6 = in2(16);\ncoefs_tq1_7 = in2(19);\ncoefs_tq1_8 = in2(22);\ncoefs_tq1_9 = in2(25);\ncoefs_tq2_1 = in2(2);\ncoefs_tq2_2 = in2(5);\ncoefs_tq2_3 = in2(8);\ncoefs_tq2_4 = in2(11);\ncoefs_tq2_5 = in2(14);\ncoefs_tq2_6 = in2(17);\ncoefs_tq2_7 = in2(20);\ncoefs_tq2_8 = in2(23);\ncoefs_tq2_9 = in2(26);\ncoefs_tq3_1 = in2(3);\ncoefs_tq3_2 = in2(6);\ncoefs_tq3_3 = in2(9);\ncoefs_tq3_4 = in2(12);\ncoefs_tq3_5 = in2(15);\ncoefs_tq3_6 = in2(18);\ncoefs_tq3_7 = in2(21);\ncoefs_tq3_8 = in2(24);\ncoefs_tq3_9 = in2(27);\ncoefs_tq1_10 = in2(28);\ncoefs_tq1_11 = in2(31);\ncoefs_tq2_10 = in2(29);\ncoefs_tq2_11 = in2(32);\ncoefs_tq3_10 = in2(30);\ncoefs_tq3_11 = in2(33);\npinvG3_1 = in1(3);\npinvG3_2 = in1(6);\npinvG3_3 = in1(9);\nq0 = in3(1,:);\nq1 = in3(2,:);\nq2 = in3(3,:);\nq3 = in3(4,:);\nobj = q0.^2.*(coefs_tq1_1.*pinvG3_1+coefs_tq2_1.*pinvG3_2+coefs_tq3_1.*pinvG3_3)+q1.^2.*(coefs_tq1_5.*pinvG3_1+coefs_tq2_5.*pinvG3_2+coefs_tq3_5.*pinvG3_3)+q2.^2.*(coefs_tq1_8.*pinvG3_1+coefs_tq2_8.*pinvG3_2+coefs_tq3_8.*pinvG3_3)+q3.^2.*(coefs_tq1_10.*pinvG3_1+coefs_tq2_10.*pinvG3_2+coefs_tq3_10.*pinvG3_3)+coefs_tq1_11.*pinvG3_1+coefs_tq2_11.*pinvG3_2+coefs_tq3_11.*pinvG3_3+q0.*q1.*(coefs_tq1_2.*pinvG3_1+coefs_tq2_2.*pinvG3_2+coefs_tq3_2.*pinvG3_3)+q0.*q2.*(coefs_tq1_3.*pinvG3_1+coefs_tq2_3.*pinvG3_2+coefs_tq3_3.*pinvG3_3)+q0.*q3.*(coefs_tq1_4.*pinvG3_1+coefs_tq2_4.*pinvG3_2+coefs_tq3_4.*pinvG3_3)+q1.*q2.*(coefs_tq1_6.*pinvG3_1+coefs_tq2_6.*pinvG3_2+coefs_tq3_6.*pinvG3_3)+q1.*q3.*(coefs_tq1_7.*pinvG3_1+coefs_tq2_7.*pinvG3_2+coefs_tq3_7.*pinvG3_3)+q2.*q3.*(coefs_tq1_9.*pinvG3_1+coefs_tq2_9.*pinvG3_2+coefs_tq3_9.*pinvG3_3);\n", "meta": {"author": "zarathustr", "repo": "LibQPEP", "sha": "99e5c23e746ace0bac4a86742c31db6fcf7297ba", "save_path": "github-repos/MATLAB/zarathustr-LibQPEP", "path": "github-repos/MATLAB/zarathustr-LibQPEP/LibQPEP-99e5c23e746ace0bac4a86742c31db6fcf7297ba/MATLAB/func_files/t3_hand_eye_func_new.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7185944046238981, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.3284958868603771}} {"text": "function [positionSLR,marksSLR,ind,messages]=SLR2(marks,messages)\n% post processing rule for delineation\n%\n% [positionSLR,marksSLR,ind,messages]=SLR2(marks,messages)\n%\n% INPUT:\n% marks: structure with a matrix of annotations in samples; in each field\n% each matrix of annotations has one line per beat and 10 colunms\n% corresponding respectively to P onset, P peak, P end, QRS onset, QRS\n% main peak, QRS end, T onset, T peak, T prima, T end\n% messages.setup.SLR.freq: sampling frequency of the recording.\n% messages.setup.SLR.QRSlimit: admited diference between marks of the same beat in ms (optional)\n% by default QRSlimit= 250 ms.\n% messages.setup.SLR.k: number of neighbours to consider in SLR rule (optional)\n% by default k=3 \n% messages.setup.SLR.delta: neighbourhood to consider in SLR rule in ms (optional)\n% by default delta = [4 nan 4 12 nan 10 12 nan nan 12] ms for 10 marks\n% or delta = [4 nan nan 4 nan 12 nan nan nan nan 10 12 nan nan 12] ms for 15 marks\n% messages.setup.wavedet.refrper: minimum time between two admisible beats, by default 257ms\n% messages.setup.SLR.tolerance = time in ms to define each individual QRS wave, by default 10ms\n% \n% OUTPUT:\n%positionSLR: struture with multilead based on marks obtained by SLR rule\n% marksSLR: matrix multilead based on marks obtained by SLR rule\n% ind: indexes of the initial column vectors for each set, corresponding to the sincronized beats\n% each line of ind corresponds to a beat and each column to a set\n% if a beat is absent of a set\n% messages.errors: errors during the processing\n% messages.errors_desc:errors description\n% messages.status: sucess of the procesing (1) ou fail (0)\n% messages.status: parameters considered\n% Last update: 27JAN2012\npositionSLR=[];\nmarksSLR=[];\nind=[];\nif nargin<2\n messages.errors= 'Fatal error in SLR.';\n messages.errors_desc= 'Inputs marks and messages.setup.SLR.freq required';\n messages.status=0;\n return\nelse\n if size(marks{1},2)~=10 && size(marks{1},2)~=15\n messages.errors= 'Fatal error in SLR.';\n messages.errors_desc= 'Input marks should include 10 or 15 marks.';\n messages.status=0;\n return\n end\n if ~isfield(messages,'setup') || ((~isfield(messages.setup,'SLR') ||...\n (~isfield(messages.setup.SLR,'freq') && ~isfield(messages.setup.SLR,'fa'))) &&...\n (~isfield(messages.setup.wavedet,'wavedet') || ( isfield(messages.setup.wavedet,'wavedet') &&...\n ~isfield(messages.setup.wavedet,'freq')))) %\n messages.errors= 'Fatal error in SLR.';\n messages.errors_desc= 'Inputs messages.setup.SLR.freq required';\n messages.status=0;\n return\n else\n try\n fa=messages.setup.SLR.freq;\n catch me\n me.message = 'Not exist messages.setup.SLR.freq';\n try\n fa=messages.setup.SLR.fa;\n catch me\n me.message = 'Not exist messages.setup.SLR.fa';\n fa= messages.setup.wavedet.freq;\n end\n end\n end\nend\nmessages.status=1;\nif ~isfield(messages,'errors')\n messages.errors=[];\nend\nif ~isfield(messages,'errors_desc')\n messages.errors_desc=[];\nend\nif ~isfield(messages,'warnings')\n messages.warnings=[];\nend\nif ~isfield(messages,'status')\n messages.status=1;\nend\nif ~isfield(messages.setup.SLR,'k')\n messages.setup.SLR.k=min(3,size(marks{1},1)-1);\nend\nif ~isfield(messages.setup.SLR,'QRSlimit')\n messages.setup.SLR.QRSlimit=250;\nend\nif ~isfield(messages.setup.SLR,'delta')\n if size(marks{1},2)==10\n messages.setup.SLR.delta = [4 nan 4 12 nan 10 12 nan nan 12];\n elseif size(marks{1},2)==15\n messages.setup.SLR.delta = [4 nan nan 4 nan 12 nan nan nan nan 10 12 nan nan 12];\n end\nend\n\nQRSlimit= messages.setup.SLR.QRSlimit*fa/1000;\ndelta= messages.setup.SLR.delta*fa/1000;\nk= messages.setup.SLR.k;\nif isempty(k) || ~isnumeric(k) || isnan(k)\n k=min(3,size(marks{1},1)-1);\n messages.setup.SLR.k=k;\nend\nif isempty(QRSlimit) || ~isnumeric(QRSlimit) || isnan(QRSlimit)\n messages.setup.SLR.QRSlimit=250;\n QRSlimit=messages.setup.SLR.QRSlimit*fa/1000;\nend\nif isempty(delta) | size(delta)~=size(marks{1},2) %#ok\n if size(marks{1},2)==10\n messages.setup.SLR.delta = [4 nan 4 12 nan 10 12 nan nan 12];\n elseif size(marks{1},2)==15\n messages.setup.SLR.delta = [4 nan nan 4 nan 12 nan nan nan nan 10 12 nan nan 12];\n end\n delta= messages.setup.SLR.delta*fa/1000;\nend\n \nif ~isfield(messages.setup.SLR,'refrper')\n if isfield(messages.setup,'wavedet') && isfield(messages.setup.wavedet,'refrper')\n messages.setup.SLR.refrper=messages.setup.wavedet.refrper*fa/1000;\n else\n messages.setup.SLR.refrper=275*fa/1000;\n end\nend\nif ~isfield(messages.setup.SLR,'tolerance')\n messages.setup.SLR.tolerance=10*fa/1000;\nend\n\nif isstruct(marks)\n leads = fieldnames(marks);\n messages.setup.SLR.nleads=length(leads);\nelse\n messages.setup.SLR.nleads = size(marks,2);\nend\n\nif length(delta)==10\n messages.setup.SLR.marks_desc={'(','P',')','(','QRS',')','(','T','T''',')'};\n peaks=[2 5 8 9];\n onsets=[1 4 6];\n ends=[3 6 10];\n refmark=5; \nelseif length(delta)==15\n messages.setup.SLR.marks_desc={'(','P','P''',')','QRS_first_peak','(','Q','R','S','R''',')','(','T','T''',')'};\n peaks=[2 3 8 13 14];\n onsets=[1 6 12];\n ends=[4 11 15];\n refmark=[8 9 7 10];%RUTE % porque la onda R puede ni existir en una derivacion especifica!\nend\nnmarks=length(delta);\nbeats=0;\nrefmark_n=refmark;\n \nfor g=1:messages.setup.SLR.nleads\n if isstruct(marks)\n f = getfield(marks, char(leads(g))); %#ok\n else\n f = marks{g};\n end\n if length(f)> size(beats,1)\n beats((size(beats,1)+1):length(f),1:g)=zeros(length((size(beats,1)+1):length(f)),g);\n end\n for n=1:size(f,1)\n refmark(n)=refmark_n(find(~isnan(f(n,refmark_n)),1,'first')); %#ok\n beats(n,g)=f(n,refmark(n)); %#ok\n end \nend\n\nbeats(beats==0)=NaN;\n[ind,messages1]=sincronizabeats(beats,QRSlimit); \nif messages1.status == 0\n return;\nend\nind(sum(~isnan(ind),2)\n else\n f = marks{g};\n end\n beats(~isnan(ind(:,g)),g)=f(ind(~isnan(ind(:,g)),g),5);\nend\nind(find(diff(nanmedian(beats,2)) < messages.setup.SLR.refrper)+1,:) = [];\n\nnbeats=size(ind,1);\nmarksSLR=NaN.*ones(nbeats,nmarks);\nmarksSLR_lead=NaN.*ones(nbeats,nmarks);\nfor mark=peaks\n beats=NaN*ones(size(ind));\n for g=1:size(ind,2)\n if isstruct(marks)\n f = getfield(marks, char(leads(g))); %#ok\n else\n f = marks{g};\n end\n beats(~isnan(ind(:,g)),g)=f(ind(~isnan(ind(:,g)),g),mark);\n end\n marksSLR(:,mark)=nanmedian(beats,2);\nend\n\nif nmarks==15;\n mark=7:10;\n QRS{1}=NaN*ones(size(ind));\n QRS{2}=QRS{1};\n QRS{3}=QRS{1};\n QRS{4}=QRS{1};\n for g=1:size(ind,2)\n if isstruct(marks)\n f = getfield(marks, char(leads(g))); %#ok\n else\n f = marks{g};\n end\n QRS{1}(~isnan(ind(:,g)),g)=f(ind(~isnan(ind(:,g)),g),mark(1)); %#ok\n QRS{2}(~isnan(ind(:,g)),g)=f(ind(~isnan(ind(:,g)),g),mark(2)); %#ok\n QRS{3}(~isnan(ind(:,g)),g)=f(ind(~isnan(ind(:,g)),g),mark(3)); %#ok\n QRS{4}(~isnan(ind(:,g)),g)=f(ind(~isnan(ind(:,g)),g),mark(4)); %#ok\n end \n for beat=1:nbeats\n AA=[QRS{1}(beat,:);QRS{2}(beat,:);QRS{3}(beat,:);QRS{4}(beat,:)];\n %look for small R waves that should go with Q waves\n %RS that is an inverted QR or RSR' that is an inverted QRS\n ii=find(AA(2,:)-nanmedian(AA(2,:))<-messages.setup.SLR.tolerance);\n QRS{1}(beat,ii)=QRS{2}(beat,ii); %#ok\n QRS{2}(beat,ii)=QRS{3}(beat,ii); %#ok\n QRS{3}(beat,ii)=QRS{4}(beat,ii); %#ok\n QRS{4}(beat,ii)=NaN; %#ok\n AA=[QRS{1}(beat,:);QRS{2}(beat,:);QRS{3}(beat,:);QRS{4}(beat,:)];\n %look for Q waves that should go with R waves\n %QS complexes or QR that is an inverted RS\n ii=find(AA(1,:)-nanmedian(AA(1,:))>messages.setup.SLR.tolerance);\n QRS{4}(beat,ii)=QRS{3}(beat,ii); %#ok\n QRS{3}(beat,ii)=QRS{2}(beat,ii); %#ok\n QRS{2}(beat,ii)=QRS{1}(beat,ii); %#ok\n QRS{1}(beat,ii)=NaN; %#ok\n AA=[QRS{1}(beat,:);QRS{2}(beat,:);QRS{3}(beat,:);QRS{4}(beat,:)];\n %look for R' waves that should go with S waves\n ii=find(AA(4,:)-nanmedian(AA(4,:))<-messages.setup.SLR.tolerance);\n QRS{1}(beat,ii)=QRS{2}(beat,ii); %#ok\n QRS{2}(beat,ii)=QRS{3}(beat,ii); %#ok\n QRS{3}(beat,ii)=QRS{4}(beat,ii); %#ok\n QRS{4}(beat,ii)=NaN; %#ok\n AA=[QRS{1}(beat,:);QRS{2}(beat,:);QRS{3}(beat,:);QRS{4}(beat,:)];\n marksSLR(beat,mark)=nanmedian(AA,2)';\n end\nend\nif size(marksSLR,2) == 15\n positionSLR.P = marksSLR(:,2);\n positionSLR.Pprima = marksSLR(:,3);\n positionSLR.qrs = marksSLR(:,8);\n positionSLR.QRSon = marksSLR(:,6);\n positionSLR.Q = marksSLR(:,7);\n positionSLR.R = marksSLR(:,8);\n positionSLR.S = marksSLR(:,9);\n positionSLR.Rprima = marksSLR(:,10);\n positionSLR.T = marksSLR(:,13);\n positionSLR.Tprima = marksSLR(:,14);\nelse\n positionSLR.P = marksSLR(:,2);\n positionSLR.qrs = marksSLR(:,5);\n positionSLR.T = marksSLR(:,8);\n positionSLR.Tprima = marksSLR(:,9);\nend\nfor mark=onsets, %onsets\n beats=NaN.*ones(nbeats,nmarks);\n for g=1:size(ind,2)\n if isstruct(marks)\n f = getfield(marks, char(leads(g))); %#ok\n else\n f = marks{g};\n end\n beats(~isnan(ind(:,g)),g)=f(ind(~isnan(ind(:,g)),g),mark);\n end\n aux= sum(~isnan(beats),2);\n for beat=1:nbeats\n if aux(beat)>k, % if the mark was found in more than k of the leads\n kk = beats(beat,:);\n kk(isnan(kk))=[];\n [kk kki] =sort(kk); % sorted the mark found in the leads in beat\n while (length(kk)>k && kk(k+1)>(kk(1)+delta(mark))), %eliminate the first mark until kk satisfy the rule or length(kk)\n else\n f = marks{g};\n end\n beats(~isnan(ind(:,g)),g)=f(ind(~isnan(ind(:,g)),g),mark);\n end\n aux= sum(~isnan(beats),2);\n for beat=1:nbeats\n if aux(beat)>k, %\n kk = beats(beat,:);\n kk(isnan(kk))=[];\n [kk kki] =sort(kk,'descend');\n % kk =flipud(sort(kk)')'; \n while (length(kk)>k && kk(k+1)<(kk(1)-delta(mark))),\n kk(1)=[];\n kki(1)=[];\n end\n if length(kk)==k\n marksSLR(beat,mark)=nan;\n else\n marksSLR(beat,mark)=kk(1);\n marksSLR_lead(beat,mark)=kki(1);\n end\n else\n marksSLR(beat,mark)=nan;\n end\n end\nend\npositionSLR.Poff = marksSLR(:,ends(1));\npositionSLR.QRSoff = marksSLR(:,ends(2));\npositionSLR.Toff = marksSLR(:,ends(3));\npositionSLR.Poff_lead = marksSLR_lead(:,ends(1));\npositionSLR.QRSoff_lead = marksSLR_lead(:,ends(2));\npositionSLR.Toff_lead = marksSLR_lead(:,ends(3));\n", "meta": {"author": "marianux", "repo": "ecg-kit", "sha": "c8e3de47c54a9214138143676d2aa546b0540dd2", "save_path": "github-repos/MATLAB/marianux-ecg-kit", "path": "github-repos/MATLAB/marianux-ecg-kit/ecg-kit-c8e3de47c54a9214138143676d2aa546b0540dd2/common/wavedet/SLR2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7371581741774411, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.3284257385918957}} {"text": "function obj = Make_f11(obj,D_filename,file_suffixes,bathyfile)\n% obj = Make_f11(obj,D_filename,file_suffixes)\n% Input a msh class object get the values of the density over the depth \n% based on D_filename, and computes the depth-averaged value which\n% populates the f11 struct in the msh class object.\n%\n% Author: William Pringle \n% Created: March 19 2018 \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nif isempty(obj.b)\n error('No bathymetry data in grid to calculate the depth-averaged value')\nend\nrho0 = 1000;\n%g = 9.807;\n\n% %% Do some projection for obj.p\n% proj = 'Mercator';\n% R = 6378206.4; %[m]\n% m_proj(proj,'lon',[ min(obj.p(:,1)) max(obj.p(:,1)) ],...\n% 'lat',[ min(obj.p(:,2)) max(obj.p(:,2))]) \n% [xx,yy] = m_ll2xy(obj.p(:,1),obj.p(:,2));\n% xx = R*xx; yy= R*yy; \n% \n% %% Get the element areas and slopes, connectivity table\n% A = polyarea(xx(obj.t(:,1:3))',yy(obj.t(:,1:3))')'; \n% % Get x differences\n% a = [ xx(obj.t(:,3)) - xx(obj.t(:,2))\n% xx(obj.t(:,1)) - xx(obj.t(:,3)) \n% xx(obj.t(:,2)) - xx(obj.t(:,1)) ] ;\n% a = reshape(a,[],3);\n% \n% % Get y differences\n% b = [ yy(obj.t(:,2)) - yy(obj.t(:,3))\n% yy(obj.t(:,3)) - yy(obj.t(:,1)) \n% yy(obj.t(:,1)) - yy(obj.t(:,2)) ]; \n% b = reshape(b,[],3);\n% \n% % Get the vertex to element table\n% vtoe = VertToEle(obj.t);\n% vtoe(vtoe == 0) = length(obj.t) + 1;\n% A(end+1) = 0; \n% An = sum(A(vtoe))';\n\n% nearest neighbour extrapolation of T and S (0 for no extrapolation)?\nFillNaN = 0;\n\n[direc , title , ext ] = fileparts( D_filename);\n\nif isempty(title)\n D_filename = dir(direc);\n D_filename(1:2) = [];\n idx = zeros(length(D_filename),1);\n for jj = 1:size(file_suffixes,1)\n for ii = 1:length(D_filename)\n if idx(ii) == 0\n idx(ii) = contains(D_filename(ii).name,file_suffixes(jj,:));\n end\n end\n end\n D_filename = D_filename(find(idx));\nelse\n name = D_filename; D_filename = [];\n D_filename.folder = direc;\n D_filename.name = [title ext];\nend\n\nBx = NaN(length(obj.b),size(D_filename,1));\nBy = NaN(length(obj.b),size(D_filename,1));\ntic\nfor ii = 1:size(D_filename,1)\n Dn = [D_filename(ii).folder '/' D_filename(ii).name];\n [~ , ~ , ext ] = fileparts( Dn);\n %% Read the grid and density data \n if strcmp(ext,'.nc')\n try\n title = ncreadatt(Dn,'/','title'); % Reading some \n lon = ncread(Dn,'lon');\n lat = ncread(Dn,'lat');\n z = ncread(Dn,'depth');\n sigma_t = ncread(Dn,'I_an');\n time_all = 0;\n catch\n title = ncreadatt(Dn,'/','History'); % Reading some \n [time_all(ii),lon,lat,z,~,~,dpx,dpy] = Make_Gridded_rho(Dn,...\n {'time','depth','lon','lat','salinity','water_temp','surf_el'}); %,...\n %bathyfile);\n disp(['Read time ' datestr(time_all(ii))])\n %if ii == 1\n % sigma_t = zeros([size(rho) size(D_filename,1)]);\n %end\n %sigma_t(:,:,:,ii) = rho - 1000; clear rho \n end\n elseif strcmp(ext,'.mat')\n load(Dn);\n %sigma_t = rho - 1000; clear rho\n else\n error('does not understand file extension')\n end\n% % zeta on the finite-element mesh\n% [Lon,Lat] = ndgrid(lon,lat);\n% F = griddedInterpolant(Lon,Lat,zeta,'linear','none');\n% zeta = F(obj.p);\n% % Get rho on the finite-element mesh\n% [~,~,~,rho] = Gridded_to_Mesh_SeaBed_DepthAveraged(...\n% obj.p(:,1),obj.p(:,2),obj.b,z,rho,lon,lat,FillNaN); \n% \n% % Compute bx, by for each element (loop over to reduce memory issues)\n% bxe = zeros(length(obj.t),length(z));\n% bye = zeros(length(obj.t),length(z));\n% for k = 1:length(z)\n% if k == 1\n% BCPe = zeta.*rho{k};\n% else\n% BCPe = rho{k} - rho0;\n% end\n% BCPe = BCPe(obj.t);\n% bxe(:,k) = 0.5 * sum(BCPe.*b,2); \n% bye(:,k) = 0.5 * sum(BCPe.*a,2);\n% end\n% bxe(end+1,:) = 0; bye(end+1,:) = 0;\n% bx = zeros(length(obj.b),length(z));\n% by = zeros(length(obj.b),length(z));\n% for k = length(z):-1:1\n% if k > 1\n% bxe(:,k) = trapz(z(1:k),bxe(:,1:k),2);\n% bye(:,k) = trapz(z(1:k),bye(:,1:k),2);\n% end\n% temp = sum(reshape(bxe(vtoe,k),size(vtoe,1),[]),'omitnan')';\n% bx(:,k) = temp./An;\n% by(:,k) = temp./An;\n% end\n\n % Interpolate the gradient at each depth\n dpx(isnan(dpy)) = NaN; dpy(isnan(dpx)) = NaN;\n [lonN,latN] = ndgrid(lon,lat);\n bx = NaN(length(obj.p),length(z));\n by = NaN(length(obj.p),length(z));\n for kk = 1:length(z)\n if kk == 1\n Fx = griddedInterpolant(lonN,latN,dpx(:,:,kk),'linear','none');\n Fy = griddedInterpolant(lonN,latN,dpy(:,:,kk),'linear','none');\n else\n Fx.Values = dpx(:,:,kk);\n Fy.Values = dpy(:,:,kk);\n end\n bb = obj.b >= z(kk);\n pt = obj.p(bb,:); \n bxt = Fx(obj.p(bb,:));\n byt = Fy(obj.p(bb,:));\n if ~isempty(find(isnan(bxt), 1)) \n idn = find(isnan(bxt));\n idg = find(~isnan(bxt));\n idx = knnsearch(pt(idg,:),pt(idn,:));\n bxt(idn) = bxt(idg(idx));\n end\n if ~isempty(find(isnan(byt), 1)) \n idn1 = find(isnan(byt));\n idg = find(~isnan(byt));\n if sum(idn - idn1) ~= 0\n idx = knnsearch(pt(idg,:),pt(idn1,:));\n end\n byt(idn1) = byt(idg(idx));\n end\n bx(bb,kk) = bxt;\n by(bb,kk) = byt;\n end\n % Now do the integration over the depth taking into account actual\n % depth on the computational mesh\n for kk = length(z):-1:1\n bb = isnan(Bx(:,ii)) & obj.b > z(kk) & ...\n ~isnan(bx(:,kk)) & ~isnan(by(:,kk));\n Bx(bb,ii) = trapz(z(1:kk),bx(bb,1:kk),2) + ...\n bx(bb,kk).*(obj.b(bb) - z(kk));\n By(bb,ii) = trapz(z(1:kk),by(bb,1:kk),2) + ...\n by(bb,kk).*(obj.b(bb) - z(kk)); \n end\n % Get the depth averaged\n Bx(:,ii) = Bx(:,ii)./obj.b/rho0;\n By(:,ii) = By(:,ii)./obj.b/rho0;\n\n% figure;\n% fastscatter(obj.p(:,1),obj.p(:,2),9.807*hypot(Bx,By))\n% colormap(cmocean('speed'))\n% caxis([0 1e-4])\n% colorbar;\nend\ntoc\ndisp(time_all)\nDTIMINC = round(seconds(median(diff(time_all))));\n\n%\n% tic \n% Bx = zeros(length(obj.b),size(sigma_t,4));\n% By = zeros(length(obj.b),size(sigma_t,4));\n% for t = 1:size(sigma_t,4)\n% disp(['Computing ' datestr(time_all(t))])\n% %% Calculate the depth-averaged density\n% [~,Sigma_tm,~,Sigma_3D] = Gridded_to_Mesh_SeaBed_DepthAveraged(...\n% obj.p(:,1),obj.p(:,2),obj.b,z,sigma_t(:,:,:,t),lon,lat,FillNaN); \n% \n% %% Calculate the integrated barcolinic pressure's\n% Sigma_3D = reshape(cell2mat(Sigma_3D),[],length(Sigma_3D));\n% % Make sure derivative with \"ground\" returns NaN;\n% BCP = NaN(length(obj.b),length(z));\n% for k = 1:length(z)\n% bb = obj.b >= z(k);\n% BCP(bb,k) = trapz(z(1:k),Sigma_3D(bb,1:k),2);\n% end\n% BCP = BCP/rho0;\n% \n% %% Calculate the bx/by's for each element\n% % Compute bx, by for each element (loop over to reduce memory issues)\n% bxe = zeros(length(obj.t),length(z));\n% bye = zeros(length(obj.t),length(z));\n% for k = 1:length(z)\n% BCPe = BCP(:,k);\n% BCPe = BCPe(obj.t);\n% bxe(:,k) = 0.5 * sum(BCPe.*b,2); \n% bye(:,k) = 0.5 * sum(BCPe.*a,2);\n% end\n% %% Sum the contributions of each element connected to a node\n% % Add in a zero ghost element and refer to the zero indices of vtoe to this\n% bxe(end+1,:) = 0; bye(end+1,:) = 0;\n% \n% % Sum up all element contributions to each node and take the integral\n% bx = zeros(length(obj.b),length(z));\n% by = zeros(length(obj.b),length(z));\n% for k = 1:length(z)\n% bb = obj.b >= z(k);\n% temp = sum(reshape(bxe(vtoe,k),size(vtoe,1),[]),'omitnan')';\n% bx(bb,k) = temp(bb)./An(bb);\n% temp = sum(reshape(bye(vtoe,k),size(vtoe,1),[]),'omitnan')';\n% by(bb,k) = temp(bb)./An(bb);\n% end\n% Bx(:,t) = trapz(z,bx,2)./obj.b;\n% By(:,t) = trapz(z,by,2)./obj.b;\n% Bx(obj.b == 0,t) = NaN; By(obj.b == 0,t) = NaN;\n% % % On the structured grid\n% %% Calculate the integrated barcolinic pressure's\n% Sigma_3D = sigma_t(:,:,:,t);\n% % Make sure derivative with \"ground\" returns NaN;\n% BCP = NaN(size(Sigma_3D));\n% for k = 1:length(z)\n% BCP(:,:,k) = trapz(z(1:k),Sigma_3D(:,:,1:k),3);\n% end\n% BCP = BCP/rho0;\n% \n% bx = zeros(size(Sigma_3D));\n% by = zeros(size(Sigma_3D));\n% for k = 1:length(z)\n% [bx(:,:,k),by(:,:,k)] = gradient(BCP(:,:,k),(lon(2)-lon(1))*111e3,(lat(2)-lat(1))*111e3);\n% end\n% bxv = reshape(bx,[],length(z));\n% byv = reshape(by,[],length(z));\n% Bx_struc = NaN(size(bxv,1),1);\n% By_struc = NaN(size(bxv,1),1);\n% for k = 1:length(z)\n% bb = ~isnan(bxv(:,k));\n% Bx_struc(bb) = trapz(z(1:k),bxv(bb,1:k),2)./z(k);\n% bb = ~isnan(byv(:,k));\n% By_struc(bb) = trapz(z(1:k),byv(bb,1:k),2)./z(k);\n% end\n% Bx_struc(Bx_struc == 0) = NaN;\n% By_struc(By_struc == 0) = NaN;\n% Bx_struc = reshape(Bx_struc,size(Sigma_3D,1),[])';\n% By_struc = reshape(By_struc,size(Sigma_3D,1),[])';\n% figure;\n% pcolor(hypot(Bx_struc,By_struc))\n% shading interp\n% colormap(cmocean('ice'))\n% caxis([0 2e-6])\n% colorbar;\n%end\n%toc\n% Calculate the depth-averaged\n% rhoxe = sum(Sigma_tm(obj.t).*b,2)/rho0; \n% rhoye = sum(Sigma_tm(obj.t).*a,2)/rho0;\n% rhoxe(end+1,:) = 0; rhoye(end+1,:) = 0;\n% rhox = sum(rhoxe(vtoe))'./An;\n% rhoy = sum(rhoye(vtoe))'./An;\n% Bx2D = 0.5*obj.b.^2.*rhox;\n% By2D = 0.5*obj.b.^2.*rhoy;\n\n\n%% Make into f11 struct\n%summary = ncreadatt(D_filename,'/','summary'); % global attributes\nobj.f11.DataTitle = title;\n%[~,name,~] = fileparts(D_filename);\n%obj.f11.DataSubTitle = [summary ': ' name];\nobj.f11.DTIMINC = DTIMINC;\nobj.f11.TimeVec = time_all;\nobj.f11.NumOfNodes = length(obj.b);\nobj.f11.Val = cell(size(Bx,2),1); %zeros(3,length(obj.b),size(sigma_t,4));\nfor t = 1:size(Bx,2)\n idx = find(~isnan(Bx(:,t)) & ~isnan(By(:,t)));\n obj.f11.Val{t} = [idx'; Bx(idx,t)'; By(idx,t)']; % Sigma_tm'; \nend\n%EOF\nend\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/Make_f11.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7431680086124812, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.3282372480776689}} {"text": "function [oz] = mi32oz(mi3)\n% Convert volume from cubic miles to US liquid ounces. \n% Chad Greene 2012\noz = mi3*140942994870000;", "meta": {"author": "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/mi32oz.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.3282330904745325}} {"text": "function [E,dE,f,g] = spm_DEM_eval(M,qu,qp)\n% evaluates state equations and derivatives for DEM schemes\n% FORMAT [E dE f g] = spm_DEM_eval(M,qu,qp)\n%\n% M - model structure\n% qu - conditional mode of states\n% qu.v{i} - casual states\n% qu.x(i) - hidden states\n% qu.y(i) - response\n% qu.u(i) - input\n% qp - conditional density of parameters\n% qp.p{i} - parameter deviates for i-th level\n% qp.u(i) - basis set\n% qp.x(i) - expansion point ( = prior expectation)\n%\n% E - generalised errors (i.e.., y - g(x,v,P); x[1] - f(x,v,P))\n%\n% dE:\n% dE.du - de[1:n]/du\n% dE.dy - de[1:n]/dy[1:n]\n% dE.dc - de[1:n]/dc[1:d]\n% dE.dp - de[1:n]/dp\n% dE.dup - d/dp[de[1:n]/du\n% dE.dpu - d/du[de[1:n]/dp\n%\n% where u = x{1:d]; v[1:d]\n%\n% To accelerate computations one can specify the nature of the model using\n% the field:\n%\n% M(1).E.linear = 0: full - evaluates 1st and 2nd derivatives\n% M(1).E.linear = 1: linear - equations are linear in x and v\n% M(1).E.linear = 2: bilinear - equations are linear in x, v & x*v\n% M(1).E.linear = 3: nonlinear - equations are linear in x, v, x*v, & x*x\n% M(1).E.linear = 4: full linear - evaluates 1st derivatives (for generalised \n% filtering, where parameters change)\n%__________________________________________________________________________\n% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging\n \n% Karl Friston\n% $Id: spm_DEM_eval.m 6270 2014-11-29 12:04:48Z karl $\n \n \n% get dimensions\n%==========================================================================\nnl = size(M,2); % number of levels\nne = sum(spm_vec(M.l)); % number of e (errors)\nnv = sum(spm_vec(M.m)); % number of x (causal states)\nnx = sum(spm_vec(M.n)); % number of x (hidden states)\nnp = sum(spm_vec(M.p)); % number of p (parameters)\n\n\n% evaluate functions at each hierarchical level\n%==========================================================================\n \n% Get states {qu.v{1},qu.x{1}} in hierarchical form (v{i},x{i})\n%--------------------------------------------------------------------------\nv = spm_unvec(qu.v{1},{M(1 + 1:end).v});\nx = spm_unvec(qu.x{1},{M(1:end - 1).x});\nfor i = 1:(nl - 1)\n p = spm_unvec(spm_vec(M(i).pE) + qp.u{i}*qp.p{i},M(i).pE);\n f{i,1} = feval(M(i).f,x{i},v{i},p);\n g{i,1} = feval(M(i).g,x{i},v{i},p);\nend\n \n \n% Get Derivatives\n%==========================================================================\npersistent D\ntry\n method = M(1).E.linear;\ncatch\n method = 0;\nend\n\nswitch method\n \n % get derivatives at each iteration of D-step - full evaluation\n %----------------------------------------------------------------------\n case{0} \n \n D = spm_DEM_eval_diff(x,v,qp,M);\n \n % gradients w.r.t. states\n %------------------------------------------------------------------\n dedy = D.dedy;\n dedc = D.dedc;\n dfdy = D.dfdy;\n dfdc = D.dfdc;\n dgdx = D.dgdx;\n dgdv = D.dgdv;\n dfdv = D.dfdv;\n dfdx = D.dfdx;\n dgdxp = D.dgdxp;\n dfdxp = D.dfdxp;\n dgdvp = D.dgdvp;\n dfdvp = D.dfdvp;\n \n % gradients w.r.t. parameters\n %------------------------------------------------------------------\n dgdp = D.dgdp;\n dfdp = D.dfdp;\n \n % linear: assume equations are linear in x and v\n %---------------------------------------------------------------------- \n case{1}\n \n % get derivatives and store expansion point (states)\n %------------------------------------------------------------------\n if isempty(D)\n \n D = spm_DEM_eval_diff(x,v,qp,M);\n D.x = x;\n D.v = v;\n \n % gradients w.r.t. states\n %--------------------------------------------------------------\n dedy = D.dedy;\n dedc = D.dedc;\n dfdy = D.dfdy;\n dfdc = D.dfdc;\n dgdx = D.dgdx;\n dgdv = D.dgdv;\n dfdv = D.dfdv;\n dfdx = D.dfdx;\n \n % gradients w.r.t. parameters (state-dependent)\n %--------------------------------------------------------------\n dgdxp = D.dgdxp;\n dfdxp = D.dfdxp;\n dgdvp = D.dgdvp;\n dfdvp = D.dfdvp;\n \n % gradients w.r.t. parameters\n %--------------------------------------------------------------\n dgdp = D.dgdp;\n dfdp = D.dfdp;\n \n % linear expansion for derivatives w.r.t. parameters\n %------------------------------------------------------------------\n else\n \n % gradients w.r.t. states\n %--------------------------------------------------------------\n dedy = D.dedy;\n dedc = D.dedc;\n dfdy = D.dfdy;\n dfdc = D.dfdc;\n dgdx = D.dgdx;\n dgdv = D.dgdv;\n dfdv = D.dfdv;\n dfdx = D.dfdx;\n dgdxp = D.dgdxp;\n dfdxp = D.dfdxp;\n dgdvp = D.dgdvp;\n dfdvp = D.dfdvp;\n \n % gradients w.r.t. parameters\n %--------------------------------------------------------------\n dx = spm_vec(qu.x{1}) - spm_vec(D.x);\n dv = spm_vec(qu.v{1}) - spm_vec(D.v);\n dgdp = D.dgdp;\n dfdp = D.dfdp;\n for p = 1:np\n dgdp(:,p) = D.dgdp(:,p) + D.dgdxp{p}*dx + D.dgdvp{p}*dv;\n if nx\n dfdp(:,p) = D.dfdp(:,p) + D.dfdxp{p}*dx + D.dfdvp{p}*dv;\n end\n end\n \n end\n \n % bilinear: assume equations are linear in x and v and x*v\n %---------------------------------------------------------------------- \n case{2}\n \n % get derivatives and store expansion point (states)\n %------------------------------------------------------------------\n if isempty(D)\n \n % get high-order derivatives\n %--------------------------------------------------------------\n [Dv D] = spm_diff('spm_DEM_eval_diff',x,v,qp,M,2);\n \n for i = 1:nv, Dv{i} = spm_unvec(Dv{i},D); end\n D.x = x;\n D.v = v;\n D.Dv = Dv;\n \n % gradients w.r.t. states\n %--------------------------------------------------------------\n dedy = D.dedy;\n dedc = D.dedc;\n dfdy = D.dfdy;\n dfdc = D.dfdc;\n dgdx = D.dgdx;\n dgdv = D.dgdv;\n dfdv = D.dfdv;\n dfdx = D.dfdx;\n dgdxp = D.dgdxp;\n dfdxp = D.dfdxp;\n dgdvp = D.dgdvp;\n dfdvp = D.dfdvp;\n \n % gradients w.r.t. parameters\n %--------------------------------------------------------------\n dgdp = D.dgdp;\n dfdp = D.dfdp;\n \n % linear expansion for derivatives w.r.t. parameters\n %------------------------------------------------------------------\n else\n \n % gradients w.r.t. causes and data\n %--------------------------------------------------------------\n dedy = D.dedy;\n dedc = D.dedc;\n dfdy = D.dfdy;\n dfdc = D.dfdc;\n \n % states (relative to expansion point)\n %--------------------------------------------------------------\n dv = spm_vec(qu.v{1}) - spm_vec(D.v);\n \n % gradients w.r.t. states\n %--------------------------------------------------------------\n dgdx = D.dgdx;\n dgdv = D.dgdv;\n dfdx = D.dfdx;\n dfdv = D.dfdv;\n for i = 1:nv; dgdx = dgdx + D.Dv{i}.dgdx*dv(i); end\n for i = 1:nv; dgdv = dgdv + D.Dv{i}.dgdv*dv(i); end\n for i = 1:nv; dfdx = dfdx + D.Dv{i}.dfdx*dv(i); end\n for i = 1:nv; dfdv = dfdv + D.Dv{i}.dfdv*dv(i); end\n \n \n % second-order derivatives\n %--------------------------------------------------------------\n dgdxp = D.dgdxp;\n dgdvp = D.dgdvp;\n dfdxp = D.dfdxp;\n dfdvp = D.dfdvp;\n for p = 1:np\n for i = 1:nv; dgdxp{p} = dgdxp{p} + D.Dv{i}.dgdxp{p}*dv(i); end\n for i = 1:nv; dgdvp{p} = dgdvp{p} + D.Dv{i}.dgdvp{p}*dv(i); end\n for i = 1:nv; dfdxp{p} = dfdxp{p} + D.Dv{i}.dfdxp{p}*dv(i); end\n for i = 1:nv; dfdvp{p} = dfdvp{p} + D.Dv{i}.dfdvp{p}*dv(i); end\n end\n \n \n % gradients w.r.t. parameters\n %--------------------------------------------------------------\n dgdp = D.dgdp;\n dfdp = D.dfdp;\n for p = 1:np\n Dgdxp = (D.dgdxp{p} + dgdxp{p})/2;\n Dgdvp = (D.dgdvp{p} + dgdvp{p})/2;\n Dfdxp = (D.dfdxp{p} + dfdxp{p})/2;\n Dfdvp = (D.dfdvp{p} + dfdvp{p})/2;\n dgdp(:,p) = dgdp(:,p) + Dgdvp*dv;\n dfdp(:,p) = dfdp(:,p) + Dfdvp*dv;\n end\n \n end\n \n % nonlinear: assume equations are bilinear in x and v\n %----------------------------------------------------------------------\n case{3}\n \n % get derivatives and store expansion point (states)\n %------------------------------------------------------------------\n if isempty(D)\n \n % get high-order derivatives\n %--------------------------------------------------------------\n [Dx D] = spm_diff('spm_DEM_eval_diff',x,v,qp,M,1,'q');\n [Dv D] = spm_diff('spm_DEM_eval_diff',x,v,qp,M,2,'q');\n \n for i = 1:nx, Dx{i} = spm_unvec(Dx{i},D); end\n for i = 1:nv, Dv{i} = spm_unvec(Dv{i},D); end\n D.x = x;\n D.v = v;\n D.Dx = Dx;\n D.Dv = Dv;\n \n % gradients w.r.t. states\n %--------------------------------------------------------------\n dedy = D.dedy;\n dedc = D.dedc;\n dfdy = D.dfdy;\n dfdc = D.dfdc;\n dgdx = D.dgdx;\n dgdv = D.dgdv;\n dfdv = D.dfdv;\n dfdx = D.dfdx;\n dgdxp = D.dgdxp;\n dfdxp = D.dfdxp;\n dgdvp = D.dgdvp;\n dfdvp = D.dfdvp;\n \n % gradients w.r.t. parameters\n %--------------------------------------------------------------\n dgdp = D.dgdp;\n dfdp = D.dfdp;\n \n % linear expansion for derivatives w.r.t. parameters\n %------------------------------------------------------------------\n else\n \n % gradients w.r.t. causes and data\n %--------------------------------------------------------------\n dedy = D.dedy;\n dedc = D.dedc;\n dfdy = D.dfdy;\n dfdc = D.dfdc;\n \n % states (relative to expansion point)\n %--------------------------------------------------------------\n dx = spm_vec(qu.x{1}) - spm_vec(D.x);\n dv = spm_vec(qu.v{1}) - spm_vec(D.v);\n \n % gradients w.r.t. states\n %--------------------------------------------------------------\n dgdx = D.dgdx;\n dgdv = D.dgdv;\n dfdx = D.dfdx;\n dfdv = D.dfdv;\n for i = 1:nx; dgdx = dgdx + D.Dx{i}.dgdx*dx(i); end\n for i = 1:nv; dgdx = dgdx + D.Dv{i}.dgdx*dv(i); end\n for i = 1:nx; dgdv = dgdv + D.Dx{i}.dgdv*dx(i); end\n for i = 1:nv; dgdv = dgdv + D.Dv{i}.dgdv*dv(i); end\n for i = 1:nx; dfdx = dfdx + D.Dx{i}.dfdx*dx(i); end\n for i = 1:nv; dfdx = dfdx + D.Dv{i}.dfdx*dv(i); end\n for i = 1:nx; dfdv = dfdv + D.Dx{i}.dfdv*dx(i); end\n for i = 1:nv; dfdv = dfdv + D.Dv{i}.dfdv*dv(i); end\n \n \n % second-order derivatives\n %--------------------------------------------------------------\n dgdxp = D.dgdxp;\n dgdvp = D.dgdvp;\n dfdxp = D.dfdxp;\n dfdvp = D.dfdvp;\n for p = 1:np\n for i = 1:nx; dgdxp{p} = dgdxp{p} + D.Dx{i}.dgdxp{p}*dx(i); end\n for i = 1:nv; dgdxp{p} = dgdxp{p} + D.Dv{i}.dgdxp{p}*dv(i); end\n for i = 1:nx; dgdvp{p} = dgdvp{p} + D.Dx{i}.dgdvp{p}*dx(i); end\n for i = 1:nv; dgdvp{p} = dgdvp{p} + D.Dv{i}.dgdvp{p}*dv(i); end\n for i = 1:nx; dfdxp{p} = dfdxp{p} + D.Dx{i}.dfdxp{p}*dx(i); end\n for i = 1:nv; dfdxp{p} = dfdxp{p} + D.Dv{i}.dfdxp{p}*dv(i); end\n for i = 1:nx; dfdvp{p} = dfdvp{p} + D.Dx{i}.dfdvp{p}*dx(i); end\n for i = 1:nv; dfdvp{p} = dfdvp{p} + D.Dv{i}.dfdvp{p}*dv(i); end\n end\n \n \n % gradients w.r.t. parameters\n %--------------------------------------------------------------\n dgdp = D.dgdp;\n dfdp = D.dfdp;\n for p = 1:np\n Dgdxp = (D.dgdxp{p} + dgdxp{p})/2;\n Dgdvp = (D.dgdvp{p} + dgdvp{p})/2;\n Dfdxp = (D.dfdxp{p} + dfdxp{p})/2;\n Dfdvp = (D.dfdvp{p} + dfdvp{p})/2;\n dgdp(:,p) = dgdp(:,p) + Dgdxp*dx + Dgdvp*dv;\n dfdp(:,p) = dfdp(:,p) + Dfdxp*dx + Dfdvp*dv;\n end\n \n end\n \n % repeated evaluation of first order derivatives (for Laplace scheme)\n %---------------------------------------------------------------------- \n case{4}\n \n % get derivatives and store expansion point (states)\n %------------------------------------------------------------------\n if isempty(D)\n \n D = spm_DEM_eval_diff(x,v,qp,M);\n D.x = x;\n D.v = v;\n \n % gradients w.r.t. states\n %--------------------------------------------------------------\n dedy = D.dedy;\n dedc = D.dedc;\n dfdy = D.dfdy;\n dfdc = D.dfdc;\n dgdx = D.dgdx;\n dgdv = D.dgdv;\n dfdv = D.dfdv;\n dfdx = D.dfdx;\n \n % gradients w.r.t. parameters (state-dependent)\n %--------------------------------------------------------------\n dgdxp = D.dgdxp;\n dfdxp = D.dfdxp;\n dgdvp = D.dgdvp;\n dfdvp = D.dfdvp;\n \n % gradients w.r.t. parameters\n %--------------------------------------------------------------\n dgdp = D.dgdp;\n dfdp = D.dfdp;\n \n % re-evaluate first-order derivatives\n %------------------------------------------------------------------\n else\n \n % retain second-order gradients\n %--------------------------------------------------------------\n dgdxp = D.dgdxp;\n dfdxp = D.dfdxp;\n dgdvp = D.dgdvp;\n dfdvp = D.dfdvp;\n \n % re-evaluate first-order gradients\n %--------------------------------------------------------------\n D = spm_DEM_eval_diff(x,v,qp,M,0);\n dedy = D.dedy;\n dedc = D.dedc;\n dfdy = D.dfdy;\n dfdc = D.dfdc;\n dgdx = D.dgdx;\n dgdv = D.dgdv;\n dfdv = D.dfdv;\n dfdx = D.dfdx;\n \n % replace second-order gradients\n %--------------------------------------------------------------\n D.dgdxp = dgdxp;\n D.dfdxp = dfdxp;\n D.dgdvp = dgdvp;\n D.dfdvp = dfdvp;\n \n % gradients w.r.t. parameters\n %--------------------------------------------------------------\n dx = spm_vec(qu.x{1}) - spm_vec(x);\n dv = spm_vec(qu.v{1}) - spm_vec(v);\n dgdp = D.dgdp;\n dfdp = D.dfdp;\n for p = 1:np\n dgdp(:,p) = D.dgdp(:,p) + D.dgdxp{p}*dx + D.dgdvp{p}*dv;\n if nx\n dfdp(:,p) = D.dfdp(:,p) + D.dfdxp{p}*dx + D.dfdvp{p}*dv;\n end\n end\n \n end\n \n otherwise\n disp('Unknown method')\n \nend\n \n\n% order parameters (d = n = 1 for static models)\n%--------------------------------------------------------------------------\nd = M(1).E.d + 1; % generalisation order of q(v)\nn = M(1).E.n + 1; % embedding order (n >= d)\n\n% Generalised prediction errors and derivatives\n%==========================================================================\nEx = cell(n,1);\nEv = cell(n,1);\n[Ex{:}] = deal(sparse(nx,1));\n[Ev{:}] = deal(sparse(ne,1));\n \n% prediction error (E) - causes\n%--------------------------------------------------------------------------\nfor i = 1:n\n qu.y{i} = spm_vec(qu.y{i});\nend\nEv{1} = [qu.y{1}; qu.v{1}] - [spm_vec(g); qu.u{1}];\nfor i = 2:n\n Ev{i} = dedy*qu.y{i} + dedc*qu.u{i} ... % generalised response\n - dgdx*qu.x{i} - dgdv*qu.v{i}; % and prediction\nend\n \n% prediction error (E) - states\n%--------------------------------------------------------------------------\ntry\n Ex{1} = qu.x{2} - spm_vec(f);\nend\nfor i = 2:n - 1\n Ex{i} = qu.x{i + 1} ... % generalised motion\n - dfdx*qu.x{i} - dfdv*qu.v{i}; % and prediction\nend\n \n% error\n%--------------------------------------------------------------------------\nE = spm_vec({Ev,Ex});\n \n \n% Kronecker forms of derivatives for generalised motion\n%==========================================================================\nif nargout < 2, return, end\n \n% dE.dp (parameters)\n%--------------------------------------------------------------------------\ndgdp = {dgdp};\ndfdp = {dfdp};\nfor i = 2:n\n dgdp{i,1} = dgdp{1};\n dfdp{i,1} = dfdp{1};\n for p = 1:np\n dgdp{i,1}(:,p) = dgdxp{p}*qu.x{i} + dgdvp{p}*qu.v{i};\n dfdp{i,1}(:,p) = dfdxp{p}*qu.x{i} + dfdvp{p}*qu.v{i};\n end\nend\n \n% generalised temporal derivatives: dE.du (states)\n%--------------------------------------------------------------------------\ndedy = kron(spm_speye(n,n),dedy);\ndedc = kron(spm_speye(n,d),dedc);\ndfdy = kron(spm_speye(n,n),dfdy);\ndfdc = kron(spm_speye(n,d),dfdc);\ndgdx = kron(spm_speye(n,n),dgdx);\ndgdv = kron(spm_speye(n,d),dgdv);\ndfdv = kron(spm_speye(n,d),dfdv);\ndfdx = kron(spm_speye(n,n),dfdx) - kron(spm_speye(n,n,1),speye(nx,nx));\n \n% 1st error derivatives (states)\n%--------------------------------------------------------------------------\ndE.dy = spm_cat({dedy; dfdy});\ndE.dc = spm_cat({dedc; dfdc});\ndE.dp = -spm_cat({dgdp; dfdp});\ndE.du = -spm_cat({dgdx, dgdv ;\n dfdx, dfdv});\n \n \n% bilinear derivatives\n%--------------------------------------------------------------------------\nfor i = 1:np\n dgdxp{i} = kron(spm_speye(n,n),dgdxp{i});\n dfdxp{i} = kron(spm_speye(n,n),dfdxp{i});\n dgdvp{i} = kron(spm_speye(n,d),dgdvp{i});\n dfdvp{i} = kron(spm_speye(n,d),dfdvp{i});\n dE.dup{i} = -spm_cat({dgdxp{i}, dgdvp{i};\n dfdxp{i}, dfdvp{i}});\nend\nif np\n dE.dpu = spm_cell_swap(dE.dup);\nelse\n dE.dpu = {};\nend\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/spm_DEM_eval.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7690802264851919, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.32787550695195156}} {"text": " classdef matRad_MinMaxDVH < DoseConstraints.matRad_DoseConstraint\n % matRad_MinMaxDVH Implements a MinMaxDVH constraint\n % See matRad_DoseConstraint for interface description\n %\n % References\n % -\n %\n % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n %\n % Copyright 2020 the matRad development team. \n % \n % This file is part of the matRad project. It is subject to the license \n % terms in the LICENSE file found in the top-level directory of this \n % distribution and at https://github.com/e0404/matRad/LICENSES.txt. No part \n % of the matRad project, including this file, may be copied, modified, \n % propagated, or distributed except according to the terms contained in the \n % LICENSE file.\n %\n % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n \n properties (Constant)\n name = 'DVH constraint';\n parameterNames = {'d^{ref}', 'V^{min}', 'V^{max}'};\n %parameterIsDose = logical([1 0 0]);\n parameterTypes = {'dose','numeric','numeric'};\n end\n \n properties\n voxelScalingRatio = 1;\n referenceScalingVal = 0.01;\n parameters = {30,0,100};\n end\n \n methods\n function obj = matRad_MinMaxDVH(dRef,vMin,vMax)\n \n %If we have a struct in first argument\n if nargin == 1 && isstruct(dRef)\n inputStruct = dRef;\n initFromStruct = true;\n else\n initFromStruct = false;\n inputStruct = [];\n end\n \n %Call Superclass Constructor (for struct initialization)\n obj@DoseConstraints.matRad_DoseConstraint(inputStruct);\n \n %now handle initialization from other parameters\n if ~initFromStruct \n if nargin == 3 && isscalar(vMax)\n obj.parameters{3} = vMax;\n end\n \n if nargin >= 1 && isscalar(dRef)\n obj.parameters{1} = dRef;\n end\n \n if nargin >= 2 && isscalar(vMin)\n obj.parameters{2} = vMin;\n end\n end\n end\n \n %Overloads the struct function to add constraint specific\n %parameters\n function s = struct(obj)\n s = struct@DoseConstraints.matRad_DoseConstraint(obj);\n s.voxelScalingRatio = 1;\n s.referenceScalingVal = 0.01;\n end\n \n function cu = upperBounds(obj,n)\n cu = obj.parameters{3} / 100;\n end\n function cl = lowerBounds(obj,n)\n cl = obj.parameters{2} / 100;\n end\n %% Calculates the Constraint Function value\n function cDose = computeDoseConstraintFunction(obj,dose)\n \n %Fast DVH point calculation\n cDose = sum(dose >= obj.parameters{1})/numel(dose);\n \n %cDose = 100 * cDose; %In Percent\n \n % alternative constraint calculation 3/4 %\n % % get reference Volume\n % refVol = cst{j,6}(k).volume/100;\n %\n % % calc deviation\n % deviation = d_i - d_ref;\n %\n % % calc d_ref2: V(d_ref2) = refVol\n % d_ref2 = matRad_calcInversDVH(refVol,d_i);\n %\n % % apply lower and upper dose limits\n % if isequal(cst{j,6}(k).type, 'max DVH constraint')\n % deviation(d_i < d_ref | d_i > d_ref2) = 0;\n % elseif isequal(cst{j,6}(k).type, 'min DVH constraint')\n % deviation(d_i > d_ref | d_i < d_ref2) = 0;\n % end\n %\n % %c = sum(deviation); % linear deviation\n % %c = deviation'*deviation; % square devioation\n % c = (1/size(cst{j,4},1))*(deviation'*deviation); % square deviation with normalization\n % %c = (deviation).^2'*(deviation).^2; % squared square devioation\n % alternative constraint calculation 3/4 %\n end\n \n %% Calculates the Constraint jacobian\n function cDoseJacob = computeDoseConstraintJacobian(obj,dose)\n %logistic approximation\n \n %Do we really need to sort two times?\n dose_sort = sort(dose);\n \n % calculate scaling\n NoVoxels = max(obj.voxelScalingRatio*numel(dose),10);\n absDiffsort = sort(abs(obj.parameters{1} - dose_sort)); \n \n deltaDoseMax = absDiffsort(min(ceil(NoVoxels/2),numel(dose)));\n \n % calclulate DVHC scaling\n DVHCScaling = min((log(1/obj.referenceScalingVal-1))/(2*deltaDoseMax),250);\n \n d_diff = dose - obj.parameters{1};\n \n cDoseJacob = (2/numel(dose))*DVHCScaling*exp(2*DVHCScaling*d_diff)./(exp(2*DVHCScaling*d_diff)+1).^2;\n \n % alternative constraint calculation 4/4 %\n % % get reference Volume\n % refVol = cst{j,6}(k).volume/100;\n %\n % % calc deviation\n % deviation = d_i - d_ref;\n %\n % % calc d_ref2: V(d_ref2) = refVol\n % d_ref2 = matRad_calcInversDVH(refVol,d_i);\n %\n % % apply lower and upper dose limits\n % if isequal(cst{j,6}(k).type, 'max DVH constraint')\n % deviation(d_i < d_ref | d_i > d_ref2) = 0;\n % elseif isequal(cst{j,6}(k).type, 'min DVH constraint')\n % deviation(d_i > d_ref | d_i < d_ref2) = 0;\n % end\n %\n % %jacobVec = ones(size(cst{j,4})); % linear deviation\n % %jacobVec = 2*deviation; % square deviation\n % jacobVec = (1/size(cst{j,4},1))*2*deviation; % square deviation with normalization\n % %jacobVec = 4*(deviation).^3; % squared square devioation\n % alternative constraint calculation 4/4 %\n end\n end\n \nend\n\n\n", "meta": {"author": "e0404", "repo": "matRad", "sha": "0a03aee5ef4a100dbc4bef8927db41b59f44946e", "save_path": "github-repos/MATLAB/e0404-matRad", "path": "github-repos/MATLAB/e0404-matRad/matRad-0a03aee5ef4a100dbc4bef8927db41b59f44946e/optimization/+DoseConstraints/matRad_MinMaxDVH.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.665410572017153, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.3275071889300307}} {"text": " function y = reale(x, arg2, arg3)\n%| Return real part of complex data (with error checking).\n%function y = reale(x, arg2, arg3)\n%|\n%| y = reale(x)\n%| y = reale(x, tol) [default tol is 1e-13 for double, else 1e-6]\n%| y = reale(x, 'warn', 'message')\n%| y = reale(x, 'error')\n%| y = reale(x, 'report')\n%| y = reale(x, 'prompt')\n%| y = reale(x, 'disp')\n%|\n%| Checks that imaginary part is negligible (warns etc. if not).\n%|\n%| Copyright Jeff Fessler, University of Michigan\n\nif nargin < 1, ir_usage, end\nif nargin == 1 && streq(x, 'test'), reale_test, return, end\n\ncom = 'error';\nif isa(x, 'double')\n\ttol = 1e-13;\nelse\n\ttol = 1e-6;\nend\n\nif nargin > 1\n\tif ischar(arg2)\n\t\tcom = arg2;\n\telseif isnumeric(arg2)\n\t\ttol = arg2;\n\tend\nend\n\nswitch com\ncase {'disp','prompt', 'report'}\n\t;\ncase 'warn'\n\tonlywarn = 1;\ncase 'error'\n\tonlywarn = 0;\notherwise\n\tfail('bad argument \"%s\"', com)\nend\n\nmax_abs_x = max(abs(x(:)));\nif max_abs_x == 0\n\tif any(imag(x(:)) ~= 0)\n\t\tfail 'max real 0, but imaginary!'\n\telse\n\t\ty = real(x);\n\t\treturn\n\tend\nend\n\nfrac = max(abs(imag(x(:)))) / max_abs_x;\nif streq(com, 'report')\n\tprintm('imaginary part %g%%', frac * 100)\n\treturn\nend\n\nif frac > tol\n\t[cname line] = caller_name;\n\tt = sprintf('%s(%d): %s: imaginary fraction of %s [class %s] is %g', ...\n\t\tcname, line, mfilename, inputname(1), class(x), frac);\n\tif isvar('arg3')\n\t\tt = [t ', ' arg3];\n\tend\n\tif streq(com, 'disp')\n\t\tdisp(t)\n\n\telseif streq(com, 'prompt')\n\t\tprintm('reale() called for input with imaginary part %g%%', frac * 100)\n\t\tprintm('reale() called in context where a large imaginary part')\n\t\tprintm('is likely an *error*. proceed with caution!')\n\t\tt = input('proceed? [y|n]: ', 's');\n\t\tif isempty(t) || t(1) ~= 'y'\n\t\t\tprintm('ok, aborting is probably wise!')\n\t\t\terror ' '\n\t\tend\n\n\telseif onlywarn\n\t\tdisp(t)\n\telse\n\t\tfail(t)\n\tend\nend\ny = real(x);\n\n\nfunction reale_test\nx = 7 + 1i*eps;\nreale(x, 'warn');\nreale(x, 'prompt');\n%reale(x, 'report'); % check error reporting\n%reale(x, eps/100) % check error faulting\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/utilities/reale.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.6297746074044135, "lm_q1q2_score": 0.3271813365706013}} {"text": "function prctmus = gp_predprctmu(gp, x, y, varargin) \n%GP_PREPRCTMU Percentiles of the distribution of the location parameter\n%\n% Description\n% PRCTMU = GP_PREDPRCTMU(GP, X, Y, XT, OPTIONS)\n% takes a GP structure together with matrix X of training inputs\n% and vector Y of training targets, and evaluates the\n% percentiles of the distribution of the location parameter at\n% test inputs XT.\n%\n% PRCTMU = GP_PREDPRCTMU(GP, X, Y, OPTIONS)\n% evaluates the percentiles of the distribution of the location\n% parameter at training inputs X.\n%\n% OPTIONS is optional parameter-value pair\n% prct - percentiles to be computed (default = [5 50 95])\n% nsamp - determines the number of samples used by GP_RND in case of \n% MCMC or IA (default = 5000).\n% predcf - index vector telling which covariance functions are \n% used for prediction. Default is all (1:gpcfn)\n% tstind - a vector defining, which rows of X belong to which \n% training block in *IC type sparse models. Default is [].\n% See also GP_PRED.\n% z - optional observed quantity in triplet (x_i,y_i,z_i)\n% Some likelihoods may use this. For example, in case of \n% Poisson likelihood we have z_i=E_i, that is, expected value \n% for ith case.\n% zt - optional observed quantity in triplet (xt_i,yt_i,zt_i)\n% Some likelihoods may use this. For example, in case of \n% Poisson likelihood we have z_i=E_i, that is, the expected \n% value for the ith case. \n%\n% See also\n% GP_PRED, GP_PAK, GP_UNPAK\n%\n% Copyright (c) 2011 Ville Tolvanen\n% Copyright (c) 2011-2012 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 = 'GP_PREDPRCTMU';\n ip.addRequired('gp',@(x) isstruct(x) || iscell(x));\n ip.addRequired('x', @(x) ~isempty(x) && isreal(x) && all(isfinite(x(:))))\n ip.addRequired('y', @(x) ~isempty(x) && isreal(x) && all(isfinite(x(:))))\n ip.addOptional('xt', [], @(x) isempty(x) || (isreal(x) && all(isfinite(x(:)))))\n ip.addParamValue('z', [], @(x) isreal(x) && all(isfinite(x(:))))\n ip.addParamValue('zt', [], @(x) isreal(x) && all(isfinite(x(:))))\n ip.addParamValue('prct', [5 50 95], @(x) isreal(x) && all(isfinite(x(:))))\n ip.addParamValue('nsamp', 5000, @(x) isreal(x) && all(isfinite(x(:))))\n ip.addParamValue('predcf', [], @(x) isempty(x) || ...\n isvector(x) && isreal(x) && all(isfinite(x)&x>0))\n ip.addParamValue('tstind', [], @(x) isempty(x) || iscell(x) ||...\n (isvector(x) && isreal(x) && all(isfinite(x)&x>0)))\n if numel(varargin)==0 || isnumeric(varargin{1})\n % inputParser should handle this, but it doesn't\n ip.parse(gp, x, y, varargin{:});\n else\n ip.parse(gp, x, y, [], varargin{:});\n end\n xt=ip.Results.xt;\n z = ip.Results.z;\n zt = ip.Results.zt;\n prct = ip.Results.prct;\n nsamp = ip.Results.nsamp;\n predcf=ip.Results.predcf;\n tstind=ip.Results.tstind;\n if isempty(xt)\n xt=x;\n if isempty(tstind)\n if iscell(gp)\n gptype=gp{1}.type;\n else\n gptype=gp.type;\n end\n switch gptype\n case {'FULL' 'VAR' 'DTC' 'SOR'}\n tstind = [];\n case {'FIC' 'CS+FIC'}\n tstind = 1:size(x,1);\n case 'PIC'\n if iscell(gp)\n tstind = gp{1}.tr_index;\n else\n tstind = gp.tr_index;\n end\n end\n end\n if isempty(zt)\n zt=z;\n end\n end\n \n % pass these forward\n options=struct();\n if ~isempty(z);options.z=z;end\n if ~isempty(zt);options.zt=zt;end\n if ~isempty(predcf);options.predcf=predcf;end\n if ~isempty(tstind);options.tstind=tstind;end\n \n [tn, nin] = size(x);\n \n if iscell(gp) || numel(gp.jitterSigma2)>1\n % gp_array or MCMC samples\n % the combined latent posterior is not Gaussian\n sampft = gp_rnd(gp, x, y, xt, 'nsamp', nsamp, options);\n if iscell(gp)\n % in the next step we need just one gp from the array\n gp=gp{1};\n end\n if isfield(gp, 'monotonic') && gp.monotonic\n [gp,x,y,z,xt,zt] = gp.fh.setUpDataForMonotonic(gp,x,y,z,xt,zt);\n end\n if isfield(gp.lik.fh,'trcov')\n % Gaussian likelihood\n prctmus = prctile(sampft', prct)';\n else\n prctmus = prctile(gp.lik.fh.invlink(gp.lik, sampft, zt)', prct)';\n end\n else\n % single GP \n if isfield(gp, 'monotonic') && gp.monotonic\n [gp,x,y,z,xt,zt] = gp.fh.setUpDataForMonotonic(gp,x,y,z,xt,zt);\n end\n % the latent posterior is Gaussian\n [Eft, Varft] = gp_pred(gp, x, y, xt, 'tstind', tstind, options);\n prct = prct./100;\n prct = norminv(prct, 0, 1);\n if isfield(gp.lik.fh,'trcov')\n % Gaussian likelihood\n prctmus = bsxfun(@plus, Eft, bsxfun(@times, sqrt(Varft), prct));\n else\n % Non-Gaussian likelihood\n np = length(prct);\n prctmus = zeros(size(Eft,1),np);\n for i=1:np\n prctmus(:,i) = gp.lik.fh.invlink(gp.lik, Eft+prct(i).*sqrt(Varft), zt);\n end\n end\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/gp_predprctmu.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442251064863695, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.32714515234031233}} {"text": "function ell_demo ( )\n\n%*****************************************************************************80\n%\n%% ELL_DEMO demonstrates MESH2D on the L-shaped region.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 16 February 2015\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'ELL_DEMO:\\n' );\n fprintf ( 1, ' MATLAB version\\n' );\n fprintf ( 1, ' Use MESH2D to mesh the L-shaped region.\\n' );\n fprintf ( 1, ' Use MESH2D_TO_MEDIT to write the mesh to a file.\\n' );\n\n warning off\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Set maximum element size HDATA.HMAX = 0.1\\n' );\n\n v = [ 0.0, 0.0; 2.0, 0.0; 2.0, 1.0; 1.0, 1.0; 1.0, 2.0; 0.0, 2.0 ];\n\n hdata = [];\n hdata.hmax = 0.1;\n\n [ p, t ] = mesh2d ( v, [], hdata );\n\n [ nv, ~ ] = size ( v );\n [ np, ~ ] = size ( p );\n [ nt, ~ ] = size ( t );\n fprintf ( 1, ' %d boundary vertices input, %d nodes and %d triangles created\\n', nv, np, nt );\n pause\n%\n% Now call MESH2D_TO_MEDIT to write the data to a file.\n%\n filename = 'ell.mesh';\n mesh2d_to_medit ( p, t, filename );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Wrote mesh data to MEDIT mesh file \"%s\"\\n', filename );\n%\n% Terminate.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'ELL_DEMO:\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n\n return\nend\nfunction h = hfun1 ( x, y )\n\n%*****************************************************************************80\n%\n%% HFUN1 is a size-function for the L-shaped region.\n%\n% Discussion:\n%\n% The smallest size is at (1.0,1.0), and sizes increase as their distance\n% from that point increases.\n%\n h = 0.01 + 0.1 * sqrt ( ( x - 1.0 ).^2 + ( y - 1.0 ).^2 );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/mesh2d_to_medit/ell_demo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.32679493745252}} {"text": "\nfunction [pk, final_manip] = SCO_null_space(robot, pathT)\n%global robot\nglobal parameters\nglobal hfigures\nhfigures.hpaths = figure;\nhfigures.hcosts = figure;\nhfigures.hee = figure;\nhfigures.htheta = figure;\nhfigures.hbest_costs = figure;\nhfigures.hdtheta = figure;\n\n%N waypoints at each trajectory\n%N = parameters.N;\n%K particles\nK = parameters.K;\n\n%generate K different paths\n%starting from arbitrary positions.\nfor k=1:K\n q0 = uniform(-pi, pi, 1, robot.DOF)';\n [pathq, pathT] = plan_path_moore_penrose(robot, q0);\n %generate particle\n G{k}.pathq = pathq;\n G{k}.pathT = pathT;\n animate_local(robot, pathq)\n figure, plot(pathq'), legend('q1', 'q2', 'q3', 'q4')\nend\n%pick arbitrarily one...\ninitial_manip = compute_manip(robot, pathq);\nG_inicial = G;\n\n%animate one of the particles (random)\n%this may not be the best particle, of course\nanimate_local(robot, pathq)\n\ni=0;\nbest_probs = [];\n%Main loop\n%till convergence of trajectory cost function\nwhile i < 20\n i\n i=i+1;\n G = add_noise_to_particle_set(G, pathT);\n \n %best particle\n [pk, best_prob] = best_particle(G);\n best_probs = [best_probs, best_prob];\n plot_info(G, pk, best_probs)\nend\n\n%plot particle info\nbest_particle_info(pk)\nfigure, \nplot(best_probs)\ntitle('best PROB at each iteration (sum of probs-weights along trajectory)')\n%animate best particle\nanimate_local(robot, pk.pathq)\nfinal_manip = compute_manip(robot, pk.pathq);\nfigure, plot(initial_manip), hold\nplot(final_manip)\nlegend('initial_manip', 'final_manip')\ntitle('manip at each time step')\n\nfigure, hold\nfor k=1:K\n plot(compute_manip(robot, G{k}.pathq))\nend\n\n% function plot_particles_costs(G)\n% K = size(G,2);\n% figure, hold\n% for k=1:K\n% pk = G{k};\n% plot(pk.P)\n% end\n% title('Probabilities')\n\n\n\nfunction plot_info(G, best_pk, best_probs)\nglobal hfigures parameters\nK = size(G,2);\nfigure(hfigures.hpaths), \nclf\nhold on\ntitle('robot paths')\npp=[];\nfor k=1:K\n pk = G{k};\n plot(pk.pathq')\n pp(k) = sum(pk.P);\nend\nfigure(hfigures.hcosts)\nplot(sort(pp))\ntitle('Trajectory sum of probabilities for each particle')\n\nfigure(hfigures.hbest_costs), clf, hold on\nplot(best_probs)\ntitle('Best trajectory probability at each time step (sum of prob-weights)')\n \n\nfunction best_particle_info(pk)\nfigure,\nsubplot(3,1,1)\nplot(pk.pathq(1,:))\nsubplot(3,1,2)\nplot(pk.pathq(2,:))\nsubplot(3,1,3)\nplot(pk.pathq(3,:))\ntitle('joint values')\nfigure, \nplot(pk.P)\ntitle('Prob at each time step of particle SHOULD BE >0')\nfigure,\nplot(pk.pathq')\n\ntitle('BEST PARTICLE PATH')\n\n\nfunction animate_robot(pk)\nglobal robot\nN = size(pk.path,2);\nfor i=1:N\n qi = pk.path(:,i);\n drawrobot3d(robot, qi)\nend\n\n%generate a prior path for the particles\nfunction path = generate_path(robot, q0, qN, N)\ndeltaq=(qN-q0)/(N-1);\npath = [];\nfor i=0:N-1\n qi = q0 + i*deltaq;\n path = [path qi];\n %drawrobot3d(robot, qi)\nend\n\n\nfunction mcost = mean_cost(G)\npk = G{1};\nK = size(G,2);\nN = size(pk.path,2);\ncc = [];\nfor k=1:K\n pk = G{k};\n cc(k) = sum(pk.costs);\nend\nmcost = mean(cc);\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% OBTAIN the best particle according to the defined cost function \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [pk, best_prob] = best_particle(G)\n%global robot\npk = G{1};\nK = size(G,2);\nN = size(pk.pathq,2);\nprobs = [];\n\nfor k=1:K\n pk = G{k};\n probs(k) = sum(pk.P);\nend\n%we must minimize costs\n%[val, index]=min(costs);\n%alternatively maximize our defined weigths\n[val, index]=max(probs);\nfprintf('Best particle is index: k=%d\\n', index)\npk = G{index};\nbest_prob = val;\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Compute cost function to encode manipulability.\n% Return:\n% P: likelihood function\n% q: the cost function it self\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [P, cost] = cost_function_manipulability(q)\nglobal robot parameters\n%compute nil-space!!\n% J = manipulator_jacobian(robot, q);\nmanip = compute_manip(robot, q);\n%define cost: cost is lower as manipulability is higher\ncost = 1/(manip+0.01);\nlambda = parameters.lambda_manip;\n%return likelihood\nP = exp(-(1/lambda)*cost);\n\n\n\n\nfunction V = compute_link_velocity_1(theta, thetad)\nV = 1*thetad(1)^2;\n\nfunction V = compute_link_velocity_2(theta, thetad)\nth1 = theta(1);\nth2 = theta(2);\n\nJ = [-sin(th1) -sin(th1+th2);\n cos(th1) cos(th1+th2)];\nV = J*[thetad(1) thetad(1)+thetad(2)]';\nV = norm(V);\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% generate a noisy particle set\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction G=generate_initial_particle_set(K, path)\nfor k=1:K\n G{k} = generate_particle(path);\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Generate a path for each particle without noise\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction pk = generate_particle(path)\nglobal robot\n%each path is in each row for qi\nDOF = robot.DOF;\nfor i = 1:DOF\n pk.path(i,:) = path(i,:); \nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% add noise to the\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction G=add_noise_to_particle_set(G, pathT)\nK = size(G,2);\n%for every particle in the set\nfor k=1:K\n pk = G{k};\n pathT = pk.pathT;\n pk = add_noise_to_particle_null_space(pk, pathT);\n G{k} = pk;\nend\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% !! Add noise along the null space!!!\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction pk = add_noise_to_particle_null_space(pk, pathT)\nglobal parameters robot\nN = size(pk.pathq, 2);\n%each path is in each row for qi\nDOF = robot.DOF;\n\n% at each particle add some noise!\n%move along the path of the particle\nfor i = 1:N\n %current joint position\n q1 = pk.pathq(:,i);\n %generate some samples along the nulls space\n qq = sample_from_null_space(q1);\n %populate with the current pose!!!\n qq = [qq q1];\n p = [];\n costs = [];\n %for all the new samples!\n for j=1:size(qq,2)\n %weight the samples,\n %compute cost of obstacles and manipulability\n [Pm, costm] = cost_function_manipulability(qq(:,j));\n if robot.DOF == 4\n [Po] = cost_function_distance_4dof(qq(:,j));\n else\n [Po] = cost_function_distance_7dof(qq(:,j));\n end\n p(j)=Pm*Po;\n %p(j)=Pm; \n end\n %select the best one\n %from the sample performed based on probability\n %max probatility!\n [prob, index] = max(p);\n q = qq(:,index);\n pk.pathq(:,i) = q;\n %and current probability\n pk.P(i) = prob;\nend\n\n%obtain samples from the null space\n%near to q\nfunction qq=sample_from_null_space(q1)\nglobal robot\nglobal parameters\n%sigma_noise = parameters.noise_sigma_null_space;\nalpha = parameters.alpha;\ntime_step = parameters.time_step;\n\nq = q1;\nthe = 0;\nqq=[];\n%sigma_noise = 0.3;\n%alpha = mvnrnd(0, sigma_noise);\n%alpha = 0.3;\nss = +1;\n%iterate at each time step: forward movement\nwhile the < abs(alpha)\n %compute null_space\n if robot.DOF==4\n qdnull = null_space_4dof(robot, q);\n else\n qdnull = null_space_7dof(robot, q);\n end\n if norm(qdnull) < 0.01\n break\n end\n qdnull = qdnull/norm(qdnull);\n dq = ss*time_step*qdnull;\n the = the + norm(dq);\n q = q + dq;\n qq = [qq q];\nend\n\nss = -1;\nq = q1;\nthe = 0;\n%backward movement\nwhile the < abs(alpha)\n %compute null_space\n %compute null_space\n if robot.DOF==4\n qdnull = null_space_4dof(robot, q);\n else\n qdnull = null_space_7dof(robot, q);\n end\n if norm(qdnull) < 0.01\n break\n end\n qdnull = qdnull/norm(qdnull);\n dq = ss*time_step*qdnull;\n the = the + norm(dq);\n q = q + dq;\n qq = [qq q];\nend\n\n\n%\n% Uniform value betweenn min_val and max_val\n%\nfunction delta = uniform(min_val, max_val, n, m)\ndelta = (max_val-min_val)*rand(n, m) + min_val;\n\n\n", "meta": {"author": "4rtur1t0", "repo": "ARTE", "sha": "6e836f3156bb36af63b70bd93375c8ff4ee643c4", "save_path": "github-repos/MATLAB/4rtur1t0-ARTE", "path": "github-repos/MATLAB/4rtur1t0-ARTE/ARTE-6e836f3156bb36af63b70bd93375c8ff4ee643c4/lib/SCO_v0.5/SCO_null_space.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6150878555160666, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.3267404342984973}} {"text": "function [ss,gg,tt,ff,zo]=ssubmmse(si,fsz,pp)\n%SSUBMMSE performs speech enhancement using mmse estimate of spectral amplitude or log amplitude [SS,ZO]=(S,FSZ,P)\n%\n% Usage: y=ssubmmse(x,fs); % enhance the speech using default parameters\n%\n% Inputs:\n% si input speech signal\n% fsz sample frequency in Hz\n% Alternatively, the input state from a previous call (see below)\n% pp algorithm parameters [optional]\n%\n% Outputs:\n% ss output enhanced speech\n% gg(t,f,i) selected time-frequency values (see pp.tf below)\n% tt centre of frames (in seconds)\n% ff centre of frequency bins (in Hz)\n% zo output state (or the 2nd argument if gg,tt,ff are omitted)\n%\n% The algorithm operation is controlled by a small number of parameters:\n%\n% pp.of % overlap factor = (fft length)/(frame increment) [2]\n% pp.ti % desired frame increment [0.016 seconds]\n% pp.ri % set to 1 to round ti to the nearest power of 2 samples [0]\n% pp.ta % time const for smoothing SNR estimate [0.396 seconds]\n% pp.gx % maximum posterior SNR as a power ratio [1000 = +30dB]\n% pp.gn % min posterior SNR as a power ratio when estimating prior SNR [1 = 0dB]\n% pp.gz % min posterior SNR as a power ratio [0.001 = -30dB]\n% pp.xn % minimum prior SNR [0]\n% pp.xb % bias compensation factor for prior SNR [1]\n% pp.lg % MMSE target: 0=amplitude, 1=log amplitude [1]\n% pp.ne % noise estimation: 0=min statistics, 1=MMSE [0]\n% pp.bt % threshold for binary gain or -1 for continuous gain [-1]\n% pp.mx % input mixture gain [0]\n% pp.rf % round output signal to an exact number of frames [0]\n% pp.tf % selects time-frequency planes to output in the gg() variable ['g']\n% 'i' = input power spectrum\n% 'I' = input complex spectrum\n% 'n' = noise power spectrum\n% 'z' = \"posterior\" SNR (i.e. (S+N)/N )\n% 'x' = \"prior\" SNR (i.e. S/N )\n% 'g' = gain\n% 'o' = output power spectrum\n% 'O' = output complex spectrum\n%\n% The applied gain is mx+(1-mx)*optgain where optgain is calculated according to [1] or [2].\n% If pp.bt>=0 then optgain is first thresholded with pp.bt to produce a binary gain 0 or 1.\n%\n% The default parameters implement the original algorithm in [1,2].\n%\n% Several parameters relate to the estimation of xi, the so-called \"prior SNR\",\n%\n% xi=max(a*pp.xb*xu+(1-a)*max(gami-1,pp.gn-1),pp.xn);\n%\n% This is estimated as a smoothed version of 1 less than gami, the \"posterior SNR\"\n% which is the noisy speech power divided by the noise power. This is\n% clipped to a min of (pp.gn-1), smoothed using a factor \"a\" which corresponds to a\n% time-constant of pp.ta and then clipped to a minimum of pp.xn. The\n% previous value is taken to be pp.xb*xu where xu is the ratio of the\n% estimated speech amplitude squared to the noise power.\n%\n% In addition it is possible to specify parameters for the noise estimation algorithm\n% which implements reference [3] or [7] according to the setting of pp.ne\n% \n% Minimum statistics noise estimate [3]: pp.ne=0 \n% pp.taca % (11): smoothing time constant for alpha_c [0.0449 seconds]\n% pp.tamax % (3): max smoothing time constant [0.392 seconds]\n% pp.taminh % (3): min smoothing time constant (upper limit) [0.0133 seconds]\n% pp.tpfall % (12): time constant for P to fall [0.064 seconds]\n% pp.tbmax % (20): max smoothing time constant [0.0717 seconds]\n% pp.qeqmin % (23): minimum value of Qeq [2]\n% pp.qeqmax % max value of Qeq per frame [14]\n% pp.av % (23)+13 lines: fudge factor for bc calculation [2.12]\n% pp.td % time to take minimum over [1.536 seconds]\n% pp.nu % number of subwindows to use [3]\n% pp.qith % Q-inverse thresholds to select maximum noise slope [0.03 0.05 0.06 Inf ]\n% pp.nsmdb % corresponding noise slope thresholds in dB/second [47 31.4 15.7 4.1]\n%\n% MMSE noise estimate [7]: pp.ne=1 \n% pp.tax % smoothing time constant for noise power estimate [0.0717 seconds](8)\n% pp.tap % smoothing time constant for smoothed speech prob [0.152 seconds](23)\n% pp.psthr % threshold for smoothed speech probability [0.99] (24)\n% pp.pnsaf % noise probability safety value [0.01] (24)\n% pp.pspri % prior speech probability [0.5] (18)\n% pp.asnr % active SNR in dB [15] (18)\n% pp.psini % initial speech probability [0.5] (23)\n% pp.tavini % assumed speech absent time at start [0.064 seconds]\n%\n% If convenient, you can call specsub in chunks of arbitrary size. Thus the following are equivalent:\n%\n% (a) y=ssubmmse(s,fs);\n%\n% (b) [y1,z]=ssubmmse(s(1:1000),fs);\n% [y2,z]=ssubmmse(s(1001:2000),z);\n% y3=ssubmmse(s(2001:end),z);\n% y=[y1; y2; y3];\n%\n% If the number of output arguments is either 2 or 5, the last partial frame of samples will\n% be retained for overlap adding with the output from the next call to ssubmmse().\n%\n% See also specsub() for an alternative gain function\n%\n% Refs:\n% [1] Ephraim, Y. & Malah, D.\n% Speech enhancement using a minimum-mean square error short-time spectral amplitude estimator\n% IEEE Trans Acoustics Speech and Signal Processing, 32(6):1109-1121, Dec 1984\n% [2] Ephraim, Y. & Malah, D.\n% Speech enhancement using a minimum mean-square error log-spectral amplitude estimator\n% IEEE Trans Acoustics Speech and Signal Processing, 33(2):443-445, Apr 1985\n% [3] Rainer Martin.\n% Noise power spectral density estimation based on optimal smoothing and minimum statistics.\n% IEEE Trans. Speech and Audio Processing, 9(5):504-512, July 2001.\n% [4] O. Cappe.\n% Elimination of the musical noise phenomenon with the ephraim and malah noise suppressor.\n% IEEE Trans Speech Audio Processing, 2 (2): 345–349, Apr. 1994. doi: 10.1109/89.279283.\n% [5] J. Erkelens, J. Jensen, and R. Heusdens.\n% A data-driven approach to optimizing spectral speech enhancement methods for various error criteria.\n% Speech Communication, 49: 530–541, 2007. doi: 10.1016/j.specom.2006.06.012.\n% [6] R. Martin.\n% Statistical methods for the enhancement of noisy speech.\n% In J. Benesty, S. Makino, and J. Chen, editors,\n% Speech Enhancement, chapter 3, pages 43–64. Springer-Verlag, 2005.\n% [7] Gerkmann, T. & Hendriks, R. C.\n% Unbiased MMSE-Based Noise Power Estimation With Low Complexity and Low Tracking Delay\n% IEEE Trans Audio, Speech, Language Processing, 2012, 20, 1383-1393\n\n% Bugs/suggestions:\n% (1) sort out behaviour when si() is a matrix rather than a vector\n%\n% Copyright (C) Mike Brookes 2004-2011\n% Version: $Id: ssubmmse.m 2460 2012-10-29 22:20: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%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nif numel(si)>length(si)\n error('Input speech signal must be a vector not a matrix');\nend\nif isstruct(fsz)\n fs=fsz.fs;\n qq=fsz.qq;\n qp=fsz.qp;\n ze=fsz.ze;\n s=zeros(length(fsz.si)+length(si(:)),1); % allocate space for speech\n s(1:length(fsz.si))=fsz.si;\n s(length(fsz.si)+1:end)=si(:);\nelse\n fs=fsz; % sample frequency\n s=si(:);\n % default algorithm constants\n\n qq.of=2; % overlap factor = (fft length)/(frame increment)\n qq.ti=16e-3; % desired frame increment (16 ms)\n qq.ri=0; % round ni to the nearest power of 2\n qq.ta=0.396; % Time const for smoothing SNR estimate = -tinc/log(0.98) from [1]\n qq.gx=1000; % maximum posterior SNR = 30dB\n qq.gn=1; % min posterior SNR as a power ratio when estimating prior SNR [1]\n qq.gz=0.001; % min posterior SNR as a power ratio [0.001 = -30dB]\n qq.xn=0; % minimum prior SNR = -Inf dB\n qq.xb=1; % bias compensation factor for prior SNR [1]\n qq.lg=1; % use log-domain estimator by default\n qq.ne=0; % noise estimation: 0=min statistics, 1=MMSE [0]\n qq.bt=-1; % suppress binary masking\n qq.mx=0; % no input mixing\n qq.tf='g'; % output the gain time-frequency plane by default\n qq.rf=0;\n if nargin>=3 && ~isempty(pp)\n qp=pp; % save for estnoisem call\n qqn=fieldnames(qq);\n for i=1:length(qqn)\n if isfield(pp,qqn{i})\n qq.(qqn{i})=pp.(qqn{i});\n end\n end\n else\n qp=struct; % make an empty structure\n end\nend\n% derived algorithm constants\nif qq.ri\n ni=pow2(nextpow2(ti*fs*sqrt(0.5)));\nelse\n ni=round(qq.ti*fs); % frame increment in samples\nend\ntinc=ni/fs; % true frame increment time\na=exp(-tinc/qq.ta); % SNR smoothing coefficient\ngx=qq.gx; % max posterior SNR as a power ratio\ngz=qq.gz; % min posterior SNR as a power ratio\nkk=sqrt(2*pi); % sqrt(8)*Gamma(1.5) - required constant\nxn=qq.xn; % floor for prior SNR, xi\nne=qq.ne; % noise estimation: 0=min statistics, 1=MMSE [0]\ngn1=max(qq.gn-1,0); % floor for posterior SNR when estimating prior SNR\nxb=qq.xb;\ntf=qq.tf;\nrf=qq.rf || nargout==2 || nargout==5; % round down to an exact number of frames\n\n% calculate power spectrum in frames\n\nno=round(qq.of); \t% integer overlap factor\nnf=ni*no; % fft length\nw=sqrt(hamming(nf+1))'; w(end)=[]; % for now always use sqrt hamming window\nw=w/sqrt(sum(w(1:ni:nf).^2)); % normalize to give overall gain of 1\nif rf>0\n rfm=''; % truncated input to an exact number of frames\nelse\n rfm='r';\nend\n[y,tt]=enframe(s,w,ni,rfm);\ntt=tt/fs; % frame times\nyf=rfft(y,nf,2);\nyp=yf.*conj(yf); % power spectrum of input speech\n[nr,nf2]=size(yp); % number of frames\nff=(0:nf2-1)*fs/nf;\nif isstruct(fsz)\n if ne>0\n [dp,ze]=estnoiseg(yp,ze); % estimate the noise using MMSE\n else\n [dp,ze]=estnoisem(yp,ze); % estimate the noise using minimum statistics\n end\n ssv=fsz.ssv;\n xu=fsz.xu; % saved unsmoothed SNR\nelse\n if ne>0\n [dp,ze]=estnoiseg(yp,tinc,qp);\t% estimate the noise using MMSE\n else\n [dp,ze]=estnoisem(yp,tinc,qp);\t% estimate the noise using minimum statistics\n end\n ssv=zeros(ni*(no-1),1); \t% dummy saved overlap\n xu=1; % dummy unsmoothed SNR from previous frame\nend\nif ~nr \t% no data frames\n ss=[];\n gg=[];\nelse\n gam=max(min(yp./dp,gx),gz); % gamma = posterior SNR\n g=zeros(nr,nf2); % create space for gain matrix\n x=zeros(nr,nf2); % create space for prior SNR\n if qq.lg % use log domain estimator\n for i=1:nr\n gami=gam(i,:);\n xi=max(a*xb*xu+(1-a)*max(gami-1,gn1),xn); % prior SNR\n xir=xi./(1+xi);\n gi=xir.*exp(0.5*expint(xir.*gami));\n g(i,:)=gi; \t% save gain for later\n x(i,:)=xi; % save prior SNR\n xu=gami.*gi.^2; % unsmoothed prior SNR\n end\n else\n for i=1:nr\n gami=gam(i,:);\n xi=max(a*xb*xu+(1-a)*max(gami-1,gn1),xn); % prior SNR\n v=0.5*xi.*gami./(1+xi);\t% note that this is 0.5*vk in [1]\n gi=(0.277+2*v)./gami; \t% accurate to 0.02 dB for v>0.5\n mv=v<0.5;\n if any(mv)\n vmv=v(mv);\n gi(mv)=kk*sqrt(vmv).*((0.5+vmv).*besseli(0,vmv)+vmv.*besseli(1,vmv))./(gami(mv).*exp(vmv));\n end\n g(i,:)=gi; % save gain for later\n x(i,:)=xi; % save prior SNR\n xu=gami.*gi.^2; % unsmoothed prior SNR\n end\n end\n if qq.bt>=0\n g=g>qq.bt;\n end\n g=qq.mx+(1-qq.mx)*g; % mix in some of the input\n se=(irfft((yf.*g).',nf).').*repmat(w,nr,1); % inverse dft and apply output window\n ss=zeros(ni*(nr+no-1),no); % space for overlapped output speech\n ss(1:ni*(no-1),end)=ssv;\n for i=1:no\n nm=nf*(1+floor((nr-i)/no)); % number of samples in this set\n ss(1+(i-1)*ni:nm+(i-1)*ni,i)=reshape(se(i:no:nr,:)',nm,1);\n end\n ss=sum(ss,2);\n if nargout>2 && ~isempty(tf)\n gg=zeros(nr,nf2,length(tf)); % make space\n for i=1:length(tf)\n switch tf(i)\n case 'i' % 'i' = input power spectrum\n gg(:,:,i)=yp;\n case 'I' % 'i' = input power spectrum\n gg(:,:,i)=yf;\n case 'n' % 'n' = noise power spectrum\n gg(:,:,i)=dp;\n case 'z' % 'z' = posterior SNR (i.e. (S+N)/N )\n gg(:,:,i)=gam;\n case 'x' % 'x' = prior SNR\n gg(:,:,i)=x;\n case 'g' % 'g' = gain\n gg(:,:,i)=g;\n case 'o' % 'o' = output power spectrum\n gg(:,:,i)=yp.*g.^2;\n case 'O' % 'o' = output power spectrum\n gg(:,:,i)=yf.*g;\n end\n end\n end\nend\nif nargout==2 || nargout==5\n if nr\n zo.ssv=ss(end-ni*(no-1)+1:end); % save the output tail for next time\n ss(end-ni*(no-1)+1:end)=[]; % only output the frames that are completed\n else\n zo.ssv=ssv; %\n end\n zo.si=s(length(ss)+1:end); % save the tail end of the input speech signal\n zo.fs=fs; % save sample frequency\n zo.qq=qq; % save local parameters\n zo.qp=qp; % save estnoisem parameters\n zo.ze=ze; % save state of noise estimation\n zo.xu=xu;\n if nargout==2\n gg=zo; % 2nd of two arguments is zo\n end\nelseif rf==0\n ss=ss(1:length(s)); % trim to the correct length if not an exact number of frames\nend\nif ~nargout && nr>0\n ffax=ff/1000;\n ax=zeros(4,1);\n ax(1)=subplot(223);\n imagesc(tt,ffax,20*log10(g)');\n colorbar;\n axis('xy');\n title(sprintf('Filter Gain (dB): ta=%.2g',qq.ta));\n xlabel('Time (s)');\n ylabel('Frequency (kHz)');\n\n ax(2)=subplot(222);\n imagesc(tt,ffax,10*log10(yp)');\n colorbar;\n axis('xy');\n title('Noisy Speech (dB)');\n xlabel('Time (s)');\n ylabel('Frequency (kHz)');\n\n ax(3)=subplot(224);\n imagesc(tt,ffax,10*log10(yp.*g.^2)');\n colorbar;\n axis('xy');\n title('Enhanced Speech (dB)');\n xlabel('Time (s)');\n ylabel('Frequency (kHz)');\n\n ax(4)=subplot(221);\n imagesc(tt,ffax,10*log10(dp)');\n colorbar;\n axis('xy');\n title('Noise Estimate (dB)');\n xlabel('Time (s)');\n ylabel('Frequency (kHz)');\n linkaxes(ax);\nend", "meta": {"author": "covarep", "repo": "covarep", "sha": "5a2be5d6b776f14a0b275c69fde90eb13849e60d", "save_path": "github-repos/MATLAB/covarep-covarep", "path": "github-repos/MATLAB/covarep-covarep/covarep-5a2be5d6b776f14a0b275c69fde90eb13849e60d/external/voicebox/ssubmmse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.689305616785446, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.3258233753961364}} {"text": "% Function which propagates and adds noise to the 3D points and popoulates\n% other variables of the structs passed to the function\n% motion = [trans, rot_yaw_theta]\nfunction [detectionsQ, detectionsT] = propagateDetections(detectionsQ, detectionsT, params_2D3D, params_carCuboid, motion, first_time) \n \n%% for all detections in Query propagate the box to 3D box in F2 frame \n \n for i = 1:length(detectionsQ) \n \n b1Q = [];\n B1Q = [];\n bvolumeQ1 = [];\n \n % check if the detection is first time i.e. we have to start with\n % the canonical cuboid. Else we already have the cuboid.\n \n if(length(detectionsQ{i}.bvolume) == 0 )\n %disp(sprintf('first_time - id :%d\\n',detectionsQ{i}.dno));\n canonicalCuboid = getCanonicalCuboid( params_carCuboid.avg_Sz); \n\n % find center of the bounding box bottom line\n b1Q = [detectionsQ{i}.bbox(1) + (detectionsQ{i}.bbox(3) - detectionsQ{i}.bbox(1))/2 ;\n detectionsQ{i}.bbox(4);\n 1.0];\n\n % project it to 3D\n B1Q = (params_2D3D.h * inv(params_2D3D.K) * b1Q) / (params_2D3D.n' * inv(params_2D3D.K) * b1Q);\n\n % apply offset which is a function of yaw and get car's origin (remember approx.)\n offset_Z = getOffsetBasedOnYaw([params_carCuboid.avg_Sz(1); params_carCuboid.avg_Sz(3)], detectionsQ{i}.yaw); \n\n % car's origin in Query Frame\n B1Q = B1Q + [0; 0; offset_Z];\n\n % translate canonical cuboid\n canonicalCuboid = canonicalCuboid + repmat(B1Q', 8,1);\n\n % BOUNDING VOLUME IN QUERY FRAME \n [bvolumeQ1, k1] = getBoundingVolume(B1Q, canonicalCuboid, detectionsQ{i}.yaw, ... \n detectionsQ{i}.sigma_3D, ...\n params_carCuboid.sz_ub, params_carCuboid.sz_lb ...\n ); \n \n bvolumeQ1 = bvolumeQ1 - repmat([0 params_carCuboid.avg_Sz(2)/2 0], size(bvolumeQ1,1), 1); \n else\n \n B1Q = detectionsQ{i}.origin;\n bvolumeQ1 = detectionsQ{i}.bvolume;\n \n end\n \n % TODO\n % propagate noise and find new noise .... for now same noise \n % \n \n % car's origin in Train frame\n B2Q = motion(1:3) + B1Q ;\n bvolumeQ1 = bvolumeQ1 + repmat(motion(1:3)', size(bvolumeQ1,1),1);\n % CUBOID IN TRAIN FRAME \n \n %dummy_sigma = eye(4,4);\n %dumm_sigma(4,4) = 0;\n \n [bvolumeQ2, k2] = getBoundingVolume(B2Q, bvolumeQ1, motion(4), ... \n detectionsQ{i}.sigma_3D, ...\n params_carCuboid.sz_ub, params_carCuboid.sz_lb ...\n ); \n \n % bvolumeQ2 = bvolumeQ2 - repmat([0 params_carCuboid.avg_Sz(2)/2 0], size(bvolumeQ2,1), 1); % offset the h/2 as car ar to be on road \n \n % compute projection of bvolume and store in bvolume_proj variable\n bvolume_proj = (params_2D3D.K*bvolumeQ2')';\n bvolume_proj(:,1:3) = bvolume_proj(:,1:3)./repmat(bvolume_proj(:,3), 1,3);\n kbvolume_proj = convhull(bvolume_proj(:,1:2));\n bvolume_proj = bvolume_proj(kbvolume_proj,:);\n \n % update the fields of the structure\n \n detectionsQ{i}.bvolume = bvolumeQ2; \n detectionsQ{i}.bvolume_proj = bvolume_proj;\n detectionsQ{i}.yaw = detectionsQ{i}.yaw+motion(4); \n detectionsQ{i}.origin = B2Q; \n detectionsQ{i}.k = k2; \n \n \n end\n \n \n \n \n %% for all detections in Train propagate the box to 3D box in its frame \n \n for i = 1:length(detectionsT)\n\n canonicalCuboid = getCanonicalCuboid( params_carCuboid.avg_Sz); \n \n % find center of the bounding box bottom line\n b1T = [detectionsT{i}.bbox(1) + (detectionsT{i}.bbox(3) - detectionsT{i}.bbox(1))/2 ;\n detectionsT{i}.bbox(4);\n 1.0];\n \n % project it to 3D\n B1T = (params_2D3D.h * inv(params_2D3D.K) * b1T) / (params_2D3D.n' * inv(params_2D3D.K) * b1T);\n \n % apply offset which is a function of yaw and get car's origin (remember approx.)\n offset_Z = getOffsetBasedOnYaw([params_carCuboid.avg_Sz(1); params_carCuboid.avg_Sz(3)], detectionsT{i}.yaw); \n \n % car's origin in Query Frame\n B1T = B1T + [0; 0; offset_Z];\n \n % translate canonical cuboid\n canonicalCuboid = canonicalCuboid + repmat(B1T', 8,1);\n \n % BOUNDING VOLUME IN QUERY FRAME \n [bvolumeT1, k1] = getBoundingVolume(B1T, canonicalCuboid, detectionsT{i}.yaw, ... \n detectionsT{i}.sigma_3D, ...\n params_carCuboid.sz_ub, params_carCuboid.sz_lb ...\n ); \n % update the fields of the structure\n detectionsT{i}.origin = B1T; \n detectionsT{i}.k = k1;\n \n detectionsT{i}.bvolume = bvolumeT1 - repmat([0 params_carCuboid.avg_Sz(2)/2 0], size(bvolumeT1,1), 1); % offset the h/2 as car ar to be on road ; \n \n bvolume_proj = detectionsT{i}.bvolume;\n bvolume_proj = (params_2D3D.K*bvolume_proj')';\n bvolume_proj(:,1:3) = bvolume_proj(:,1:3)./repmat(bvolume_proj(:,3), 1,3);\n kbvolume_proj = convhull(bvolume_proj(:,1:2));\n bvolume_proj = bvolume_proj(kbvolume_proj,:);\n \n detectionsT{i}.bvolume_proj = bvolume_proj;\n end \n \n \nend", "meta": {"author": "JunaidCS032", "repo": "MOTBeyondPixels", "sha": "8bf3c417fbcbf3956b0e4381c6bb53b6c396fd94", "save_path": "github-repos/MATLAB/JunaidCS032-MOTBeyondPixels", "path": "github-repos/MATLAB/JunaidCS032-MOTBeyondPixels/MOTBeyondPixels-8bf3c417fbcbf3956b0e4381c6bb53b6c396fd94/src/propagateDetections.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.32532248777035044}} {"text": "function [warped]= sn2individual(P, input)\n\n% SN2INDIVIDUAL warps the input coordinates (defined as Nx3 matrix) from\n% normalised MNI coordinates to individual headspace coordinates, using the\n% warp parameters defined in the structure spmparams.\n%\n% this is modified from code from nutmeg: nut_mni2mri, which was itself\n% modified from code originally written by John Ashburner:\n% http://www.sph.umich.edu/~nichols/JG2/get_orig_coord2.m\n\n% Copyright (C) 2013-2021, Jan-Mathijs Schoffelen\n%\n% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org\n% for the documentation and details.\n%\n% FieldTrip is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% FieldTrip is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with FieldTrip. If not, see .\n%\n% $Id$\n\nif isfield(P, 'Tr')\n % this is an old-style representation of the parameters, so it uses the\n % code adjusted from nut_mni2mri\n \n if numel(P.Tr)==0\n % only an affine transformation has been done\n T = P.VF.mat*P.Affine/(P.VG.mat);\n warped = ft_warp_apply(T, input);\n \n else\n % we need the spm_dctmtx function for the nonlinear case\n if ~ft_hastoolbox('spm')\n % add SPM8 or later to the path\n ft_hastoolbox('spm8up', 1);\n end\n \n dim = P.VG.dim(1:3);\n xyz = ft_warp_apply(inv(P.VG.mat), input); % goes into voxel coordinates\n \n basX = spm_dctmtx(dim(1), size(P.Tr,1), xyz(:,1)-1);\n basY = spm_dctmtx(dim(2), size(P.Tr,2), xyz(:,2)-1);\n basZ = spm_dctmtx(dim(3), size(P.Tr,3), xyz(:,3)-1);\n \n siz = size(P.Tr);\n Tr1 = reshape(P.Tr(:,:,:,1),siz(1)*siz(2),siz(3));\n Tr2 = reshape(P.Tr(:,:,:,2),siz(1)*siz(2),siz(3));\n Tr3 = reshape(P.Tr(:,:,:,3),siz(1)*siz(2),siz(3));\n \n xyztmp = zeros(size(xyz));\n for i=1:size(xyz,1)\n bx = basX(i,:);\n by = basY(i,:);\n bz = basZ(i,:);\n tx = reshape(Tr1*bz', siz(1), siz(2) );\n ty = reshape(Tr2*bz', siz(1), siz(2) );\n tz = reshape(Tr3*bz', siz(1), siz(2) );\n xyztmp(i,:) = [bx*tx*by' bx*ty*by' bx*tz*by'];\n end\n \n T = P.VF.mat*P.Affine;\n warped = ft_warp_apply(T, xyz+xyztmp);\n end\n \nelse\n % the only way I can come up with to do this, is to write a deformation\n % to disk, and to sample this one. This requires spm12 on the path\n ft_hastoolbox('spm12', 1);\n \n fprintf('creating the deformation field and writing it to a temporary file\\n');\n \n fname = [tempname,'.nii'];\n V = nifti;\n V.dat = file_array(fname, P.image.dim(1:3), [spm_type('float32') spm_platform('bigend')], 0, 1, 0);\n V.mat = P.image.mat;\n if isfield(P.image, 'mat0') \n V.mat0 = P.image.mat0;\n end\n V.descrip = 'deformation field';\n create(V);\n V.dat(:) = 0; % this is necessary, otherwise SPM fails: image too small\n \n P.image = spm_vol(fname);\n spm_preproc_write8(P, zeros(6,4), [0 0], [0 1], 1, 1, nan(2,3), nan);\n \n [pth,nam,ext] = fileparts(fname);\n V = nifti(fullfile(pth,['y_',nam,ext]));\n y = squeeze(V.dat(:,:,:,:,:));\n \n siz = size(y);\n VT.dim = siz(1:3);\n VT.mat = P.tpm(1).mat;\n \n % 2b: write the deformation fields in x/y/z direction to temporary files\n V1.fname = [tempname '.img'];\n V1.dim(1:3) = VT.dim(1:3);\n V1.pinfo = [1 0 0]';\n V1.mat = VT.mat;\n V1.dt = [64 0];\n V1.descrip = 'Deformation field';\n spm_write_vol(V1,y(:,:,:,1));\n \n V2.fname = [tempname '.img'];\n V2.dim(1:3) = VT.dim(1:3);\n V2.pinfo = [1 0 0]';\n V2.mat = VT.mat;\n V2.dt = [64 0];\n V2.descrip = 'Deformation field';\n spm_write_vol(V2,y(:,:,:,2));\n \n V3.fname = [tempname '.img'];\n V3.dim(1:3) = VT.dim(1:3);\n V3.pinfo = [1 0 0]';\n V3.mat = VT.mat;\n V3.dt = [64 0];\n V3.descrip = 'Deformation field';\n spm_write_vol(V3,y(:,:,:,3));\n \n % first warp to voxel coordinates \n input_vox = ft_warp_apply(inv(VT.mat), input); % Express as voxel indices\n \n % apply the non-linear warp\n warped = cat(2, spm_sample_vol(V1,input_vox(:,1),input_vox(:,2),input_vox(:,3),1), ...\n spm_sample_vol(V2,input_vox(:,1),input_vox(:,2),input_vox(:,3),1), ...\n spm_sample_vol(V3,input_vox(:,1),input_vox(:,2),input_vox(:,3),1));\nend\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/utilities/private/sn2individual.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6825737473266735, "lm_q2_score": 0.4765796510636759, "lm_q1q2_score": 0.3253007583261717}} {"text": "function [Y, optinf] = cbpdn(D, S, lambda, opt)\n\n% cbpdn -- Convolutional Basis Pursuit DeNoising\n%\n% argmin_{x_m} (1/2)||\\sum_m d_m * x_m - s||_2^2 +\n% lambda \\sum_m ||x_m||_1\n%\n% The solution is computed using an ADMM approach (see\n% boyd-2010-distributed) with efficient solution of the main\n% linear systems (see wohlberg-2016-efficient).\n%\n% Usage:\n% [Y, optinf] = cbpdn(D, S, lambda, opt);\n%\n% Input:\n% D Dictionary filter set (3D array)\n% S Input image\n% lambda Regularization parameter\n% opt Algorithm parameters structure\n%\n% Output:\n% Y Dictionary coefficient map set (3D array)\n% optinf Details of optimisation\n%\n%\n% Options structure fields:\n% Verbose Flag determining whether iteration status is displayed.\n% Fields are iteration number, functional value,\n% data fidelity term, l1 regularisation term, and\n% primal and dual residuals (see Sec. 3.3 of\n% boyd-2010-distributed). The value of rho is also\n% displayed if options request that it is automatically\n% adjusted.\n% MaxMainIter Maximum main iterations\n% AbsStopTol Absolute convergence tolerance (see Sec. 3.3.1 of\n% boyd-2010-distributed)\n% RelStopTol Relative convergence tolerance (see Sec. 3.3.1 of\n% boyd-2010-distributed)\n% L1Weight Weighting array for coefficients in l1 norm of X\n% Y0 Initial value for Y\n% U0 Initial value for U\n% rho ADMM penalty parameter\n% AutoRho Flag determining whether rho is automatically updated\n% (see Sec. 3.4.1 of boyd-2010-distributed)\n% AutoRhoPeriod Iteration period on which rho is updated\n% RhoRsdlRatio Primal/dual residual ratio in rho update test\n% RhoScaling Multiplier applied to rho when updated\n% AutoRhoScaling Flag determining whether RhoScaling value is \n% adaptively determined (see wohlberg-2015-adaptive). If \n% enabled, RhoScaling specifies a maximum allowed \n% multiplier instead of a fixed multiplier.\n% RhoRsdlTarget Residual ratio targeted by auto rho update policy.\n% StdResiduals Flag determining whether standard residual definitions \n% (see Sec 3.3 of boyd-2010-distributed) are used instead\n% of normalised residuals (see wohlberg-2015-adaptive)\n% RelaxParam Relaxation parameter (see Sec. 3.4.3 of\n% boyd-2010-distributed)\n% NonNegCoef Flag indicating whether solution should be forced to\n% be non-negative\n% NoBndryCross Flag indicating whether all solution coefficients\n% corresponding to filters crossing the image boundary\n% should be forced to zero.\n% AuxVarObj Flag determining whether objective function is computed\n% using the auxiliary (split) variable\n% HighMemSolve Use more memory for a slightly faster solution\n%\n%\n% Author: Brendt Wohlberg Modified: 2015-12-28\n%\n% This file is part of the SPORCO library. Details of the copyright\n% and user license can be found in the 'License' file distributed with\n% the library.\n\n\nif nargin < 4,\n opt = [];\nend\ncheckopt(opt, defaultopts([]));\nopt = defaultopts(opt);\n\n% Set up status display for verbose operation\nhstr = 'Itn Fnc DFid l1 r s ';\nsfms = '%4d %9.2e %9.2e %9.2e %9.2e %9.2e';\nnsep = 54;\nif opt.AutoRho,\n hstr = [hstr ' rho '];\n sfms = [sfms ' %9.2e'];\n nsep = nsep + 10;\nend\nif opt.Verbose && opt.MaxMainIter > 0,\n disp(hstr);\n disp(char('-' * ones(1,nsep)));\nend\n\n% Collapsing of trailing singleton dimensions greatly complicates\n% handling of both SMV and MMV cases. The simplest approach would be\n% if S could always be reshaped to 4d, with dimensions consisting of\n% image rows, image cols, a single dimensional placeholder for number\n% of filters, and number of measurements, but in the single\n% measurement case the third dimension is collapsed so that the array\n% is only 3d.\nif size(S,3) > 1 && size(S,4) == 1,\n xsz = [size(S,1) size(S,2) size(D,3) size(S,3)];\n % Insert singleton 3rd dimension (for number of filters) so that\n % 4th dimension is number of images in input s volume\n S = reshape(S, [size(S,1) size(S,2) 1 size(S,3)]);\nelse\n xsz = [size(S,1) size(S,2) size(D,3) size(S,4)];\nend\n\n% Start timer\ntstart = tic;\n\n% Compute filters in DFT domain\nDf = fft2(D, size(S,1), size(S,2));\n% Convolve-sum and its Hermitian transpose\nDop = @(x) sum(bsxfun(@times, Df, x), 3);\nDHop = @(x) bsxfun(@times, conj(Df), x);\n% Compute signal in DFT domain\nSf = fft2(S);\n% S convolved with all filters in DFT domain\nDSf = DHop(Sf);\n\n% Default lambda is 1/10 times the lambda value beyond which the\n% solution is a zero vector\nif nargin < 3 | isempty(lambda),\n b = ifft2(DHop(Sf), 'symmetric');\n lambda = 0.1*max(vec(abs(b)));\nend\n\n% Set up algorithm parameters and initialise variables\nrho = opt.rho;\nif isempty(rho), rho = 50*lambda+1; end;\nif isempty(opt.RhoRsdlTarget),\n if opt.StdResiduals,\n opt.RhoRsdlTarget = 1;\n else\n opt.RhoRsdlTarget = 1 + (18.3).^(log10(lambda) + 1);\n end\nend\nif opt.HighMemSolve,\n C = bsxfun(@rdivide, Df, sum(Df.*conj(Df), 3) + rho);\nelse\n C = [];\nend\nNx = prod(xsz);\noptinf = struct('itstat', [], 'opt', opt);\nr = Inf;\ns = Inf;\nepri = 0;\nedua = 0;\n\n% Initialise main working variables\nX = [];\nif isempty(opt.Y0),\n Y = zeros(xsz, class(S));\nelse\n Y = opt.Y0;\nend\nYprv = Y;\nif isempty(opt.U0),\n if isempty(opt.Y0),\n U = zeros(xsz, class(S));\n else\n U = (lambda/rho)*sign(Y);\n end\nelse\n U = opt.U0;\nend\n\n% Main loop\nk = 1;\nwhile k <= opt.MaxMainIter && (r > epri | s > edua),\n%while k <= opt.MaxMainIter ,\n % Solve X subproblem\n Xf = solvedbi_sm(Df, rho, DSf + rho*fft2(Y - U), C);\n X = ifft2(Xf, 'symmetric');\n\n % See pg. 21 of boyd-2010-distributed\n if opt.RelaxParam == 1,\n Xr = X;\n else\n Xr = opt.RelaxParam*X + (1-opt.RelaxParam)*Y;\n end\n\n % Solve Y subproblem\n Y = shrink(Xr + U, (lambda/rho)*opt.L1Weight);\n if opt.NonNegCoef,\n Y(Y < 0) = 0;\n end\n if opt.NoBndryCross,\n Y((end-size(D,1)+2):end,:,:,:) = 0;\n Y(:,(end-size(D,2)+2):end,:,:) = 0;\n end\n\n % Update dual variable\n U = U + Xr - Y;\n\n % Compute data fidelity term in Fourier domain (note normalisation)\n if opt.AuxVarObj,\n Yf = fft2(Y); % This represents unnecessary computational cost\n Jdf = sum(vec(abs(sum(bsxfun(@times,Df,Yf),3)-Sf).^2))/(2*xsz(1)*xsz(2));\n Jl1 = sum(abs(vec(bsxfun(@times, opt.L1Weight, Y))));\n else\n Jdf = sum(vec(abs(sum(bsxfun(@times,Df,Xf),3)-Sf).^2))/(2*xsz(1)*xsz(2));\n Jl1 = sum(abs(vec(bsxfun(@times, opt.L1Weight, X))));\n end\n Jfn = Jdf + lambda*Jl1;\n\n nX = norm(X(:)); nY = norm(Y(:)); nU = norm(U(:));\n if opt.StdResiduals,\n % See pp. 19-20 of boyd-2010-distributed\n r = norm(vec(X - Y));\n s = norm(vec(rho*(Yprv - Y)));\n epri = sqrt(Nx)*opt.AbsStopTol+max(nX,nY)*opt.RelStopTol;\n edua = sqrt(Nx)*opt.AbsStopTol+rho*nU*opt.RelStopTol;\n else\n % See wohlberg-2015-adaptive\n r = norm(vec(X - Y))/max(nX,nY);\n s = norm(vec(Yprv - Y))/nU;\n epri = sqrt(Nx)*opt.AbsStopTol/max(nX,nY)+opt.RelStopTol;\n edua = sqrt(Nx)*opt.AbsStopTol/(rho*nU)+opt.RelStopTol;\n end\n\n % Record and display iteration details\n tk = toc(tstart);\n optinf.itstat = [optinf.itstat; [k Jfn Jdf Jl1 r s epri edua rho tk]];\n if opt.Verbose,\n if opt.AutoRho,\n disp(sprintf(sfms, k, Jfn, Jdf, Jl1, r, s, rho));\n else\n disp(sprintf(sfms, k, Jfn, Jdf, Jl1, r, s));\n end\n end\n\n % See wohlberg-2015-adaptive and pp. 20-21 of boyd-2010-distributed\n if opt.AutoRho,\n if k ~= 1 && mod(k, opt.AutoRhoPeriod) == 0,\n if opt.AutoRhoScaling,\n rhomlt = sqrt(r/(s*opt.RhoRsdlTarget));\n if rhomlt < 1, rhomlt = 1/rhomlt; end\n if rhomlt > opt.RhoScaling, rhomlt = opt.RhoScaling; end\n else\n rhomlt = opt.RhoScaling;\n end\n rsf = 1;\n if r > opt.RhoRsdlTarget*opt.RhoRsdlRatio*s, rsf = rhomlt; end\n if s > (opt.RhoRsdlRatio/opt.RhoRsdlTarget)*r, rsf = 1/rhomlt; end\n rho = rsf*rho;\n U = U/rsf;\n if opt.HighMemSolve && rsf ~= 1,\n C = bsxfun(@rdivide, Df, sum(Df.*conj(Df), 3) + rho);\n end\n end\n end\n\n Yprv = Y;\n k = k + 1;\n\nend\n\n% Record run time and working variables\noptinf.runtime = toc(tstart);\noptinf.X = X;\noptinf.Xf = Xf;\noptinf.Y = Y;\noptinf.U = U;\noptinf.lambda = lambda;\noptinf.rho = rho;\n\n% End status display for verbose operation\nif opt.Verbose && opt.MaxMainIter > 0,\n disp(char('-' * ones(1,nsep)));\nend\n\nreturn\n\n\nfunction u = vec(v)\n\n u = v(:);\n\nreturn\n\n\nfunction u = shrink(v, lambda)\n\n if isscalar(lambda),\n u = sign(v).*max(0, abs(v) - lambda);\n else\n u = sign(v).*max(0, bsxfun(@minus, abs(v), lambda));\n end\n\nreturn\n\n\nfunction opt = defaultopts(opt)\n\n if ~isfield(opt,'Verbose'),\n opt.Verbose = 0;\n end\n if ~isfield(opt,'MaxMainIter'),\n opt.MaxMainIter = 1000;\n end\n if ~isfield(opt,'AbsStopTol'),\n opt.AbsStopTol = 0;\n end\n if ~isfield(opt,'RelStopTol'),\n opt.RelStopTol = 1e-4;\n end\n if ~isfield(opt,'L1Weight'),\n opt.L1Weight = 1;\n end\n if ~isfield(opt,'Y0'),\n opt.Y0 = [];\n end\n if ~isfield(opt,'U0'),\n opt.U0 = [];\n end\n if ~isfield(opt,'rho'),\n opt.rho = [];\n end\n if ~isfield(opt,'AutoRho'),\n opt.AutoRho = 1;\n end\n if ~isfield(opt,'AutoRhoPeriod'),\n opt.AutoRhoPeriod = 1;\n end\n if ~isfield(opt,'RhoRsdlRatio'),\n opt.RhoRsdlRatio = 1.2;\n end\n if ~isfield(opt,'RhoScaling'),\n opt.RhoScaling = 100;\n end\n if ~isfield(opt,'AutoRhoScaling'),\n opt.AutoRhoScaling = 1;\n end\n if ~isfield(opt,'RhoRsdlTarget'),\n opt.RhoRsdlTarget = [];\n end\n if ~isfield(opt,'StdResiduals'),\n opt.StdResiduals = 0;\n end\n if ~isfield(opt,'RelaxParam'),\n opt.RelaxParam = 1.8;\n end\n if ~isfield(opt,'NonNegCoef'),\n opt.NonNegCoef = 0;\n end\n if ~isfield(opt,'NoBndryCross'),\n opt.NoBndryCross = 0;\n end\n if ~isfield(opt,'AuxVarObj'),\n opt.AuxVarObj = 0;\n end\n if ~isfield(opt,'HighMemSolve'),\n opt.HighMemSolve = 0;\n end\n\nreturn\n", "meta": {"author": "thfylsty", "repo": "Classic-and-state-of-the-art-image-fusion-methods", "sha": "5d9457df396f1ea6921e1b9b3703995205940862", "save_path": "github-repos/MATLAB/thfylsty-Classic-and-state-of-the-art-image-fusion-methods", "path": "github-repos/MATLAB/thfylsty-Classic-and-state-of-the-art-image-fusion-methods/Classic-and-state-of-the-art-image-fusion-methods-5d9457df396f1ea6921e1b9b3703995205940862/ConvSR_Image_Fusion_Codes/CSR_Fusion_Author/cbpdn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6076631840431539, "lm_q2_score": 0.5350984286266116, "lm_q1q2_score": 0.32515961491573514}} {"text": "function Q = cost_allstim(V,t,tc,Run)\n%\n% Least-squares cost function for the IL model\n%\n% INPUT:\n% Run = stick function\n% tc = time course\n% t = vector of time points\n% V = parameters\n%\n% OUTPUT:\n% Q = cost\n%\n% By Martin Lindquist and Tor Wager\n% Edited 12/12/06\n% Further edited by Christian Waugh 2/15/08 to include multiple trialtypes\n\nnumstim = length(Run);\nlen = length(Run{1});\nh = zeros(length(t),numstim);\nyhatt =zeros(len,numstim);\n\nfor k = 1:numstim\n h(:,k) = Get_Logit(V(k*7-6:k*7),t); % Get IL model corresponding to parameters V\n yhat(:,k) = conv(Run{k}, h(:,k)); % Convolve IL model with stick function\n yhatt(:,k) = yhat(1:len,k);\nend\n\nyhat2 = sum(yhatt,2); %Sum models together to get overall estimate\n\nQ = sum((yhat2-tc).^2); % Calculate cost function\n\nreturn", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/HRF_Est_Toolbox2/Old_stuff/cost_allstim.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7490872243177518, "lm_q2_score": 0.4339814648038985, "lm_q1q2_score": 0.3250899708753044}} {"text": "function [Results, OPTIONS, HeadModel] = bst_wmne_mosher(HeadModel,OPTIONS)\n% BST_WMNE: Compute the whitened and weighted minimum-norm operator (wMNE imaging kernel)\n%\n% USAGE: [Results,OPTIONS] = bst_wmne(HeadModel, OPTIONS) : Compute mininum operator\n% OPTIONS = bst_wmne() : Return default options\n%\n% DESCRIPTION:\n% This program computes the whitened and weighted minimum-norm operator,\n% (the wMNE imaging kernel), which is used to compute whitened \n% and weighted minimum-norm estimates (MNE).\n% (e.g., J=wMNEoperator*B; where B is the unwhitened data).\n% It can also compute the whitened and noise-normalized dynamic \n% statistical parametric mapping (dSPM) inverse operator, and/or the \n% whitened standardized low resolution brain electromagnetic tomography \n% (sLORETA) inverse operator, which are used to compute whitened source\n% activity dSPM and sLORETA maps.\n% (e.g., S_dSPM=dSPMoperator*B; where B is the unwhitened data).\n% (e.g., S_sLORETA=sLORETAoperator*B; where B is the unwhitened data).\n%\n% The function was written with the goal of providing some of the same\n% functionality of the MNE software written by Matti Hamalainen, but no\n% guarantees are made that it performs all computations in the same\n% exact way. It also provides some functionalities not available in the\n% MNE software.\n% \n% INPUTS:\n% - HeadModel: Array of Brainstorm head model structures\n% |- Gain : Forward field matrix for all the channels (unconstrained source orientations)\n% |- GridOrient : Dipole orientation matrix\n% |- area : Vector with the areas (or possibly volumes) associated with the vertices of the source space.\n% - OPTIONS: structure \n% |- NoiseCov : NoiseCov is the noise covariance matrix. \n% |- ChannelTypes : Type of each channel (for each row of the Leadfield and the NoiseCov matrix)\n% |- InverseMethod : {'wmne', 'dspm', 'sloreta'}\n% |- SourceOrient : String or a cell array of strings specifying the type of orientation constraints for each HeadModel (default: 'fixed')\n% |- SNR : Signal-to noise ratio defined as in MNE (default: 3). \n% |- diagnoise : Flag to discard off-diagonal elements of NoiseCov (assuming heteroscedastic uncorrelated noise) (default: 0)\n% |- loose : Value that weights the source variances of the dipole components defining the tangent space of the cortical surfaces (default: []).\n% |- depth : Flag to do depth weighting (default: 1).\n% |- weightexp : Order of the depth weighting. {0=no, 1=full normalization, default=0.8}\n% |- weightlimit: Maximal amount depth weighting (default: 10).\n% |- magreg : Amount of regularization of the magnetometer noise covariance matrix\n% |- gradreg : Amount of regularization of the gradiometer noise covariance matrix.\n% |- eegreg : Amount of regularization of the EEG noise covariance matrix.\n% |- ecogreg : Amount of regularization of the ECOG noise covariance matrix.\n% |- seegreg : Amount of regularization of the SEEG noise covariance matrix.\n% |- fMRI : Vector of fMRI values are the source points.\n% |- fMRIthresh : fMRI threshold. The source variances of source points with OPTIONS.fMRI smaller \n% | than fMRIthresh will be multiplied by OPTIONS.fMRIoff.\n% |- fMRIoff : Weight assigned to non-active source points according to fMRI and fMRIthresh.\n%\n% OUTPUTS:\n% - Results : structure with the wMNE inverse operator and possibly the dSPM\n% and/or sLORETA inverse operators, and other information:\n\n% NOTES:\n% - More leadfield matrices can be used: the solution will combine all\n% leadfield matrices appropriately.\n%\n% - This leadfield structure allows to combine surface and volume\n% source spaces with and without dipole orientation constraints,and\n% with and without area or volumetric current density computations.\n% If using a single sphere headmodel, the silent radial\n% component could be eliminated using the SVD (e.g., use\n% bst_remove_silent.m).\n%\n% - NoisCov: This should be computed from the pre-stimulus period for \n% averaged ERF data (e.g., using MNE), or from an empty room recording \n% for unaveraged spontaneous or induced data.\n%\n% - Orientation constrains for dipoles (.SourceOrient field)\n% - \"fixed\" : Dipoles constrained to point normal to cortical surfaces\n% - \"free\" : No constraints, dipoles point in x,y,z directions\n% - \"loose\" : Source variances of dipole components pointing tangentially to the cortical surfaces are multipled by OPTIONS.loose\n% - \"truncated\" : An SVD of the gain matrix for each source point is \n% used to remove the dipole component with least variance, which for\n% the Single Sphere Head Model, corresponds to the radialsilent component).\n% => For dealing with multiple source spaces with different types of orientation constraints use for example, \n% OPTION.SourceOrient{1}='fixed';\n% OPTION.SourceOrient{2}='free';\n% This has to correspond with the HeadModel Structure \n%\n% - The output HeadModel param is used here in return to save LOTS of memory in the bst_wmne function,\n% event if it seems to be absolutely useless. Having a parameter in both input and output have the\n% effect in Matlab of passing them \"by referece\". So please, do NOT remove it from the function description\n%\n% - sLORETA: Output values are multiplied by 1e12 for display in Brainstorm (time series and cortical maps).\n\n% @=============================================================================\n% This function is part of the Brainstorm software:\n% https://neuroimage.usc.edu/brainstorm\n% \n% Copyright (c) University of Southern California & McGill University\n% This software is distributed under the terms of the GNU General Public License\n% as published by the Free Software Foundation. Further details on the GPLv3\n% license can be found at http://www.gnu.org/copyleft/gpl.html.\n% \n% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED \"AS IS,\" AND THE\n% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY\n% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF\n% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY\n% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.\n%\n% For more information type \"brainstorm license\" at command prompt.\n% =============================================================================@\n%\n% Copyright (C) 2010 - Rey Rene Ramirez\n%\n% Authors: Rey Rene Ramirez, Ph.D. e-mail: rrramirez at mcw.edu\n% Francois Tadel, 2010-2013\n% John Mosher, 2013\n\n\n%% ===== DEFINE DEFAULT OPTIONS =====\nDef_OPTIONS.NoiseCov = [];\nDef_OPTIONS.InverseMethod = 'wmne';\nDef_OPTIONS.SNR = 3;\nDef_OPTIONS.diagnoise = 0;\n%Def_OPTIONS.SourceOrient= {'free'};\nDef_OPTIONS.SourceOrient= {'fixed'};\nDef_OPTIONS.loose = 0.2;\nDef_OPTIONS.depth = 1;\nDef_OPTIONS.weightexp = 0.5;\nDef_OPTIONS.weightlimit = 10;\nDef_OPTIONS.regnoise = 1;\nDef_OPTIONS.magreg = .1;\nDef_OPTIONS.gradreg = .1;\nDef_OPTIONS.eegreg = .1;\nDef_OPTIONS.ecogreg = .1;\nDef_OPTIONS.seegreg = .1;\nDef_OPTIONS.fMRI = [];\nDef_OPTIONS.fMRIthresh = [];\nDef_OPTIONS.fMRIoff = 0.1;\nDef_OPTIONS.pca = 1;\n% Return the default options\nif (nargin == 0)\n Results = Def_OPTIONS;\n return\nend\n% Make the default for all the leadfields\nnumL = size(HeadModel,2);\nDef_OPTIONS.SourceOrient = repmat(Def_OPTIONS.SourceOrient, [1 numL]);\n% Copy default options to OPTIONS structure (do not replace defined values)\nOPTIONS = struct_copy_fields(OPTIONS, Def_OPTIONS, 0);\n\n\n%% ===== CHECK FOR INVALID VALUES =====\ndisp(' ');\n% Detect if the input noise covariance matrix is or should be diagonal\nC_noise = OPTIONS.NoiseCov;\nvariances = diag(C_noise);\nif isequal(C_noise, diag(variances))\n OPTIONS.diagnoise = 1;\n disp('wMNE> Detected diagonal noise covariance: setting diagnoise to 1');\nend\n% If OPTIONS.diagnoise is 1, then OPTIONS.pca=0\nif OPTIONS.diagnoise\n OPTIONS.pca=0;\n disp('wMNE> If using diagonal noise covariance, PCA option should be off. Setting PCA option off.')\nend\nif isempty(OPTIONS.NoiseCov)\n error('You need to input the noise covariance in the NoiseCov field of OPTIONS.')\nend\nif (numL ~= length(OPTIONS.SourceOrient))\n error('The number of elements in the HeadModel structure should equal the length of the cell array OPTIONS.SourceOrient.')\nend\nif ~isempty(OPTIONS.loose) && (OPTIONS.loose>=1 || OPTIONS.loose<=0)\n error('loose value should be smaller than 1 and bigger than 0, or empty for no loose orientations.')\nend\nif OPTIONS.weightexp>1 || OPTIONS.weightexp<0\n error('weightexp should be a scalar between 0 and 1')\nend\nif OPTIONS.magreg>1 || OPTIONS.magreg<0\n error('magreg should be a scalar between 0 and 1')\nend\nif OPTIONS.eegreg>1 || OPTIONS.eegreg<0\n error('eegreg should be a scalar between 0 and 1')\nend\nif OPTIONS.ecogreg>1 || OPTIONS.ecogreg<0\n error('ecogreg should be a scalar between 0 and 1')\nend\nif OPTIONS.seegreg>1 || OPTIONS.seegreg<0\n error('seegreg should be a scalar between 0 and 1')\nend\n\n%% ===== NOISE COVARIANCE RANK =====\n% Get indices of MEG and EEG channels\niMeg = find(strncmpi(OPTIONS.ChannelTypes,'MEG',3));\niEeg = find(strncmpi(OPTIONS.ChannelTypes,'EEG',3));\niEcog = find(strncmpi(OPTIONS.ChannelTypes,'ECOG',3));\niSeeg = find(strncmpi(OPTIONS.ChannelTypes,'SEEG',3));\n% Diagonal noisecov\nif OPTIONS.diagnoise\n C_noise = diag(variances);\n rnkC_noise_meg = length(iMeg);\n rnkC_noise_eeg = length(iEeg);\n rnkC_noise_ecog = length(iEcog);\n rnkC_noise_seeg = length(iSeeg);\n disp('wMNE> Setting off diagonal elements of the noise covariance to zero.');\n disp(['wMNE> Rank of noise covariance is ' num2str(size(C_noise,1))]);\n% Full noisecov\nelse\n % Estimate noise covariance matrix rank separately for sensor types\n if ~isempty(iMeg) \n rnkC_noise_meg = rank(single(C_noise(iMeg,iMeg))); % Rey added this. Separate rank of MEG. 3/23/11\n disp(['wMNE> Rank of MEG part of noise covariance is ' num2str(rnkC_noise_meg)]);\n end\n if ~isempty(iEeg) \n rnkC_noise_eeg = rank(single(C_noise(iEeg,iEeg))); % Rey added this. Separate rank of EEG. 3/23/11\n disp(['wMNE> Rank of EEG part of noise covariance is ' num2str(rnkC_noise_eeg)]);\n end\n if ~isempty(iEcog) \n rnkC_noise_ecog = rank(single(C_noise(iEcog,iEcog))); % FT added 21-Feb-13\n disp(['wMNE> Rank of ECOG part of noise covariance is ' num2str(rnkC_noise_ecog)]);\n end\n if ~isempty(iSeeg) \n rnkC_noise_seeg = rank(single(C_noise(iSeeg,iSeeg))); % FT added 21-Feb-13\n disp(['wMNE> Rank of SEEG part of noise covariance is ' num2str(rnkC_noise_seeg)]);\n end\n % Sets off-diagonal terms to zero. Rey added this. 3/23/11\n C_noise_new = 0 * C_noise;\n if ~isempty(iMeg)\n C_noise_new(iMeg,iMeg) = C_noise(iMeg,iMeg);\n end \n if ~isempty(iEeg)\n C_noise_new(iEeg,iEeg) = C_noise(iEeg,iEeg);\n end \n if ~isempty(iEcog)\n C_noise_new(iEcog,iEcog) = C_noise(iEcog,iEcog);\n end \n if ~isempty(iSeeg)\n C_noise_new(iSeeg,iSeeg) = C_noise(iSeeg,iSeeg);\n end\n C_noise = C_noise_new;\nend\n\n\n%% ===== REGULARIZE NOISE COVARIANCE MATRIX ===== \n% Only if option is selected\nif OPTIONS.regnoise\n listTypes = unique(OPTIONS.ChannelTypes);\n % Loop on all the required data types (MEG MAG, MEG GRAD, EEG)\n for iType = 1:length(listTypes)\n % Get channel indices\n iChan = find(strcmpi(OPTIONS.ChannelTypes, listTypes{iType}));\n % Regularize noise covariance matrix\n switch listTypes{iType}\n case 'MEG GRAD', reg = OPTIONS.gradreg; \n case 'MEG MAG', reg = OPTIONS.magreg; \n case 'MEG', reg = OPTIONS.gradreg;\n case 'EEG', reg = OPTIONS.eegreg;\n case 'ECOG', reg = OPTIONS.ecogreg;\n case 'SEEG', reg = OPTIONS.seegreg; \n end\n % Original Line 4/5/13:\n % C_noise(iChan,iChan) = C_noise(iChan,iChan) + (reg * mean(variances(iChan)) * eye(length(iChan))); \n % JCM 4/5/13, mods just to be clear\n % mean of the diagonal variances\n % Options could be median, maximum, minimum, etc. Note, this is\n % not the eigenspectrum, but the homoskedastic spectrum.\n % TODO try other forms of matrix norms for noise regualarization\n LAMBDA_REGULARIZER = reg * mean(variances(iChan)); \n % Now add this Tikhonov regularizer to the noise diagonal.\n C_noise(iChan,iChan) = C_noise(iChan,iChan) + diag(zeros(length(iChan),1) + LAMBDA_REGULARIZER);\n\n end\nend\n\n\n%% ===== WHITENING OPERATOR =====\n% Rey added all of this, 3/23/11\n% Modified FT 21-Feb-2013\n% Whitening of each modality separately (MEG,EEG,ECOG,SEEG), which assumes \n% zero covariance between them (i.e., a block diagonal noise covariance). This\n% was recommended by Matti as EEG does not measure all the signals from the same\n% environmental noise sources as MEG.\nnChan = size(C_noise,2);\nW = zeros(0, nChan);\nif ~isempty(iMeg)\n W_meg = CalculateWhitener('MEG', C_noise, iMeg, rnkC_noise_meg, OPTIONS.pca);\n W_tmp = zeros(size(W_meg,1), nChan);\n W_tmp(:,iMeg) = W_meg;\n W = [W; W_tmp];\nend\nif ~isempty(iEeg)\n W_eeg = CalculateWhitener('EEG', C_noise, iEeg, rnkC_noise_eeg, OPTIONS.pca);\n W_tmp = zeros(size(W_eeg,1), nChan);\n W_tmp(:,iEeg) = W_eeg;\n W = [W; W_tmp];\nend\nif ~isempty(iEcog) \n W_ecog = CalculateWhitener('ECOG', C_noise, iEcog, rnkC_noise_ecog, OPTIONS.pca);\n W_tmp = zeros(size(W_ecog,1), nChan);\n W_tmp(:,iEcog) = W_ecog;\n W = [W; W_tmp];\nend\nif ~isempty(iSeeg)\n W_seeg = CalculateWhitener('SEEG', C_noise, iSeeg, rnkC_noise_seeg, OPTIONS.pca);\n W_tmp = zeros(size(W_seeg,1), nChan);\n W_tmp(:,iSeeg) = W_seeg;\n W = [W; W_tmp];\nend\n% Check for whitener integrity\nif any(isnan(W(:))) || any(isinf(W(:)))\n error('Invalid noise covariance matrix.')\nend\n% Display rank of the whitener\nrnkC_noise = size(W,1);\ndisplay(['wMNE> Total rank is ' num2str(rnkC_noise) '.'])\n\n\n%% ===== PROCESSING LEAD FIELD MATRICES, WEIGHTS, AREAS & ORIENTATIONS =====\n% Initializing.\nspl = zeros(numL,1);\nnumdipcomp = spl;\nfor k = 1:numL\n sL = size(HeadModel(k).Gain, 2);\n switch OPTIONS.SourceOrient{k}\n case 'fixed', numdipcomp(k)=1;\n case 'free', numdipcomp(k)=3;\n case 'loose', numdipcomp(k)=3;\n case 'truncated', numdipcomp(k)=2;\n end\n spl(k) = (sL / 3) * numdipcomp(k); % This is a vector with the total number of dipole components per source space.\nend\nsspl = sum(spl); % This is the total number of dipole components across all source spaces.\nL = zeros(rnkC_noise,sspl);\nw = ones(sspl,1);\nif isfield(HeadModel, 'area')\n areas = w;\nelse\n areas = [];\nend\nitangential = [];\nstart = 0;\nQ_Cortex = [];\nfor k = 1:numL\n start = start + 1;\n endd = start + spl(k) - 1;\n Lk = HeadModel(k).Gain; \n HeadModel(k).Gain = [];\n %% ===== COMPUTE POWER =====\n szL = size(Lk); \n if OPTIONS.depth\n display(['wMNE> Computing power of gain matrices at each source point for source space ' num2str(k) '.'])\n % Computing power\n % JCM 4/5/2013, this is squared Frobenius norm of the source\n % Options would be the matrix norm (largest singular value, or\n % squared).\n wk = squeeze(sum(sum((reshape(Lk,[szL(1) 3 szL(2)/3])) .^2,1),2)); \n wk = repmat(wk',[numdipcomp(k) 1]);\n wk = reshape(wk,[spl(k) 1]);\n w(start:endd) = wk;\n clear wk\n end \n switch OPTIONS.SourceOrient{k}\n case 'fixed'\n display('wMNE> Appying fixed dipole orientations.')\n Lk = bst_gain_orient(Lk,HeadModel(k).GridOrient);\n case 'free'\n display('wMNE> Using free dipole orientations. No constraints.') \n case 'loose'\n display('wMNE> Transforming lead field matrix to cortical coordinate system.')\n [Lk, Q_Cortex] = bst_xyz2lf(Lk, HeadModel(k).GridOrient');\n % Getting indices for tangential dipoles.\n itangentialtmp = start:endd; \n itangentialtmp(1:3:end) = []; \n itangential = [itangential itangentialtmp]; %#ok\n case 'truncated'\n display('wMNE> Truncating the dipole component pointing in the direction with least variance (i.e., silent component for single sphere head model.')\n [Lk, Q_Cortex] = bst_remove_silent(Lk); \n end\n %% ===== WHITEN LEAD FIELD MATRIX =====\n % Whiten lead field.\n display(['wMNE> Whitening lead field matrix for source space ' num2str(k) '.'])\n Lk = W * Lk;\n if isfield(HeadModel(k),'area') && ~isempty(HeadModel(k).area)\n areav = HeadModel(k).area;\n areav = repmat(areav', [numdipcomp(k) 1]);\n areav = reshape(areav, [spl(k) 1]);\n areas(start:endd) = areav; \n end\n L(:,start:endd) = Lk; \n start = endd;\nend\n% Computing reciprocal of power.\nw = 1 ./ w; \n% Clear memory\nclear Lk endd start itangentialtmp sL szL\n\n%% ===== APPLY AREAS =====\nif ~isempty(areas)\n display('wMNE> Applying areas to compute current source density.')\n areas = areas.^2;\n w = w .* areas;\nend\nclear areas \n\n%% ===== APPLY DEPTH WEIGHTHING =====\nif OPTIONS.depth\n % ===== APPLY WEIGHT LIMIT =====\n % Applying weight limit.\n display('wMNE> Applying weight limit.')\n weightlimit2 = OPTIONS.weightlimit .^ 2;\n %limit=min(w(w>min(w)*weightlimit2)); % This is the Matti way.\n limit = min(w) * weightlimit2; % This is the Rey way (robust to possible weight discontinuity).\n w(w>limit) = limit; %JCM note, 4/5/2013, w = min(w,limit);\n\n % ===== APPLY WEIGHT EXPONENT =====\n % Applying weight exponent.\n display('wMNE> Applying weight exponent.')\n w = w .^ OPTIONS.weightexp;\n clear limit weightlimit2\nend\n\n%% ===== APPLY LOOSE ORIENTATIONS =====\nif ~isempty(itangential)\n display(['wMNE> Applying loose dipole orientations. Loose value of ' num2str(OPTIONS.loose) '.']) \n w(itangential) = w(itangential) * (OPTIONS.loose);\nend\n\n%% ===== APPLY fMRI PRIORS =====\n% Apply fMRI Priors\nif ~isempty(OPTIONS.fMRI)\n display('wMNE> Applying fMRI priors.')\n ifmri = (OPTIONS.fMRI < OPTIONS.fMRIthresh); \n w(ifmri) = w(ifmri) * OPTIONS.fMRIoff;\nend\n\n%% ===== ADJUSTING SOURCE COVARIANCE MATRIX =====\n% Adjusting Source Covariance matrix to make trace of L*C_J*L' equal to number of sensors.\n% JCM 4/5/2013, i.e. average signal covariance is one, so trace is number\n% of sensors.\ndisplay('wMNE> Adjusting source covariance matrix.')\nC_J = speye(sspl, sspl);\nC_J = spdiags(w, 0, C_J);\ntrclcl = trace(L * C_J * L');\nC_J = C_J * (rnkC_noise / trclcl);\nRc = chol(C_J);\nLW = L * Rc;\nclear C_J trclcl sspl itangential rnkC_noise\n\n\n%% BEGIN SOURCE MODELING ROUTINES\n\n%% JCM 4/5/2013 GLS and other routines, using above setup\n\nif any(strcmpi(OPTIONS.InverseMethod, {'gls','gls_p','glsr','glsr_p'})),\n \n start = 0;\n Kernel = zeros(size(LW,2),size(LW,1)); % note transpose of LW\n lambda2 = OPTIONS.SNR^(-2); % for regularizing the GLS\n \n for k = 1:numL,\n start = start + 1;\n endd = start + spl(k) - 1;\n Lk = LW(:,start:endd); % this whitened gain matrix\n Rck = Rc(start:endd,start:endd); % covariance priors\n % Now process each source in the gain matrix for it's own inversion\n NumSources = size(Lk,2)/numdipcomp(k); % total number of sources\n \n for i = 1:NumSources,\n ndx = ((1-numdipcomp(k)):0)+i*numdipcomp(k); % next index\n % SVD the source\n [Ua,Sa,Va] = svd(Lk(:,ndx),0); % svd of this source\n Sa = diag(Sa);\n Tolerance_Source = size(Lk,1)*eps(single(Sa(1)));\n Rank_Source = sum(Sa > Tolerance_Source);\n % Trim decomposition\n Ua = Ua(:,1:Rank_Source);\n Sa = Sa(1:Rank_Source);\n Va = Va(:,1:Rank_Source);\n \n % calculate the weighted subspace\n Reg_Weights_Source = Sa.^2 ./ (Sa.^2 + lambda2*Sa(1)^2); % regularizer\n % now write the pseudoinverse results back into this same matrix\n \n switch OPTIONS.InverseMethod\n case 'gls'\n % The true pseudo-inverse\n Lk(:,ndx) = Ua * diag(1./Sa) * Va'*Rck(ndx,ndx);\n case 'gls_p'\n % The model performance\n % Model may be reduced rank\n Lk(:,ndx) = 0; % zero out\n Lk(:,ndx(1:size(Ua,2))) = Ua; % model performance\n case 'glsr'\n % Regularized\n Lk(:,ndx) = Ua * diag(Reg_Weights_Source./Sa) * Va'*Rck(ndx,ndx);\n case 'glsr_p'\n % Regularized model performance\n % Model may be reduced rank\n Lk(:,ndx) = 0; % zero out\n Lk(:,ndx(1:size(Ua,2))) = Ua * diag(sqrt(Reg_Weights_Source)); % model performance\n otherwise\n error('Bad Options String %s',OPTIONS.InverseMethod)\n end\n end\n \n % Now we have a matrix almost ready for use as an imaging kernel\n % Later, below, the whitener will be added\n \n Kernel(start:endd,:) = Lk';\n start = endd;\n end\n \nend % JCM GLS routine\n\nif any(strcmpi(OPTIONS.InverseMethod, {'mnej','mnej_p'})), %JCM Min Norm\n % mnej should be identical to Rey, but mnej_p is novel\n \n start = 0;\n Kernel = zeros(size(LW,2),size(LW,1)); % note transpose of LW\n lambda2 = OPTIONS.SNR^(-2); % for regularizing the MN\n \n for k = 1:numL,\n start = start + 1;\n endd = start + spl(k) - 1;\n Lk = LW(:,start:endd); % this whitened gain matrix\n Rck = Rc(start:endd,start:endd); % covariance priors\n \n % Setup the Min Norm\n % First, generate the population data covariance\n wCD = LW*LW' + (diag(zeros(size(LW,1),1) + lambda2)); % whitened data covariance\n \n % Decompose\n [Ud,Sd] = svd(wCD);\n \n % Data Whitener\n iWd = Ud*diag(1./sqrt(diag(Sd)))*Ud';\n \n % Now process each source in the gain matrix for it's own inversion\n NumSources = size(Lk,2)/numdipcomp(k); % total number of sources\n \n for i = 1:NumSources,\n ndx = ((1-numdipcomp(k)):0)+i*numdipcomp(k); % next index\n % SVD the data whitened source\n [Ua,Sa,Va] = svd(iWd*Lk(:,ndx),0); % svd of this source\n Sa = diag(Sa);\n Tolerance_Source = size(Lk,1)*eps(single(Sa(1)));\n Rank_Source = sum(Sa > Tolerance_Source);\n if Rank_Source < length(Sa),\n fprintf('%.0f ',i);\n end\n % Trim decomposition\n Ua = Ua(:,1:Rank_Source);\n Sa = Sa(1:Rank_Source);\n Va = Va(:,1:Rank_Source);\n \n SNR_Weights_Source = Sa.^2 ./ (1 - Sa.^2); % SNR\n % now write the pseudoinverse results back into this same matrix\n \n switch OPTIONS.InverseMethod\n case 'mnej'\n % The true solution\n Lk(:,ndx) = iWd * Ua * diag(Sa) * Va' * Rck(ndx,ndx);\n case 'mnej_p'\n % The model performance\n %Lk(:,ndx) = iWd * Ua * diag(sqrt(SNR_Weights_Source)); % model performance\n Lk(:,ndx) = iWd * Ua; % CHEAT model performance\n\n otherwise\n error('Bad Options String %s',OPTIONS.InverseMethod)\n end\n end\n \n % Now we have a matrix almost ready for use as an imaging kernel\n % Later, below, the whitener will be added\n \n Kernel(start:endd,:) = Lk';\n start = endd;\n end \n \nend %JCM Min norms\n\n\n%% The dSPM and sLORETA functions rely on 'wmne' being calculated\n\nif any(strcmpi(OPTIONS.InverseMethod, {'wmne','dspm','sloreta'}))\n \n %% ===== SINGULAR VALUE DECOMPOSITION =====\n % Set regularization parameter based on SNR\n lambda2 = OPTIONS.SNR ^ (-2);\n % Compute SVD.\n display('wMNE> Computing SVD of whitened and weighted lead field matrix.')\n [V,S,U] = svd(LW','econ'); % JCM 4/5/2013 transpose for greater speed\n s = diag(S);\n ss = s ./ (s.^2 + lambda2);\n clear LW lambda2 s\n \n %% ===== WHITENED MNE IMAGING KERNEL =====\n % Compute whitened MNE operator.\n Kernel = Rc * V * diag(ss) * U';\n clear Rc V ss U\nend\n\n\n%% ===== WHITENED dSPM IMAGING KERNEL =====\n% Compute dSPM operator.\nif strcmpi(OPTIONS.InverseMethod, 'dspm')\n display('wMNE> Computing dSPM inverse operator.')\n start = 0;\n for k = 1:numL\n start = start+1;\n endd = start + spl(k) - 1;\n dspmdiag = sum(Kernel(start:endd,:) .^2, 2);\n if (numdipcomp(k) == 1)\n dspmdiag = sqrt(dspmdiag);\n elseif (numdipcomp(k)==3 || numdipcomp(k)==2)\n dspmdiag = reshape(dspmdiag, [numdipcomp(k), spl(k)/numdipcomp(k)]);\n dspmdiag = sqrt(sum(dspmdiag)); % Taking trace and sqrt.\n dspmdiag = repmat(dspmdiag, [numdipcomp(k), 1]);\n dspmdiag = reshape(dspmdiag, [spl(k), 1]);\n end\n Kernel(start:endd,:) = bst_bsxfun(@rdivide, Kernel(start:endd,:), dspmdiag);\n start = endd;\n end\n \n %% ===== WHITENED sLORETA IMAGING KERNEL =====\n % Compute sLORETA operator.\nelseif strcmpi(OPTIONS.InverseMethod, 'sloreta')\n display('wMNE> Computing sLORETA inverse operator.')\n start=0;\n for k = 1:numL\n start = start + 1;\n endd = start + spl(k) - 1;\n if (numdipcomp(k) == 1)\n sloretadiag = sqrt(sum(Kernel(start:endd,:) .* L(:,start:endd)', 2));\n Kernel(start:endd,:) = bst_bsxfun(@rdivide, Kernel(start:endd,:), sloretadiag);\n elseif (numdipcomp(k)==3 || numdipcomp(k)==2)\n for spoint = start:numdipcomp(k):endd\n R = Kernel(spoint:spoint+numdipcomp(k)-1,:) * L(:,spoint:spoint+numdipcomp(k)-1);\n SIR = sqrtm(pinv(R));\n Kernel(spoint:spoint+numdipcomp(k)-1,:) = SIR * Kernel(spoint:spoint+numdipcomp(k)-1,:);\n end\n end\n start=endd;\n end\nend\ndisp(' ');\n\n%% JCM, 4/5/2013, this loose orientation may be compatible with GLS and others\n\n%% ===== LOOSE ORIENTATION: RE-ORIENT COMPONENTS =====\n% WARNING: Changing the orientations of the dipoles from MNE to Brainstorm\n% => Make \"Unconstrained\" and \"loose\"/\"truncated\" models directly comparable\nif ~isempty(Q_Cortex)\n % Creating a block diagonal matrix\n N = size(Kernel,1);\n Nout = N / numdipcomp * 3;\n iRow = reshape(repmat(reshape(1:Nout,3,[]), numdipcomp, 1), 1, []);\n iCol = reshape(repmat(1:N,3,[]), 1, []);\n Q_Cortex = sparse(iRow, iCol, Q_Cortex(:));\n % Applying orientations\n Kernel = Q_Cortex * Kernel;\nend\n\n\n%% ===== ASSIGN IMAGING KERNEL =====\n% Multiply inverse operator and whitening matrix, so no need to whiten data.\nKernel = Kernel * W;\n% Return results structure\nResults.ImagingKernel = Kernel;\nResults.ImageGridAmp = [];\nResults.Whitener = W;\nif (length(numdipcomp) > 1)\n Results.nComponents = 0;\nelse\n Results.nComponents = numdipcomp;\nend\n\nend\n\n\n%% ==============================================================================\n% ===== HELPER FUNCTIONS =======================================================\n% ==============================================================================\n% TODO JCM 4/5/2013: Cleanup the whitener to use SVD, reduced rank. isPCA\n% is actually for truncated SVD of the matrix for small values.\nfunction W = CalculateWhitener(Modality, C_noise, iChannel, rnkC_noise, isPca)\n [V,D] = eig(C_noise(iChannel,iChannel)); \n D = diag(D); \n [D,I] = sort(D,'descend'); \n V = V(:,I);\n % No PCA case.\n if ~isPca\n display(['wMNE> Not doing PCA for ' Modality '.'])\n D = 1./D;\n W = diag(sqrt(D)) * V';\n % Rey's approach. MNE has been changed to implement this.\n else\n display(['wMNE> Setting small ' Modality ' eigenvalues to zero.'])\n D = 1 ./ D; \n D(rnkC_noise+1:end) = 0;\n W = diag(sqrt(D)) * V';\n W = W(1:rnkC_noise,:); % This line will reduce the actual number of variables in data and leadfield to the true rank. This was not done in the original MNE C code.\n end\nend\n\n\n", "meta": {"author": "brainstorm-tools", "repo": "brainstorm3", "sha": "a892cfaabde1eaa2f9a3ac015c05b73f3739433a", "save_path": "github-repos/MATLAB/brainstorm-tools-brainstorm3", "path": "github-repos/MATLAB/brainstorm-tools-brainstorm3/brainstorm3-a892cfaabde1eaa2f9a3ac015c05b73f3739433a/toolbox/inverse/bst_wmne_mosher.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7490872131147276, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.3250899660133996}} {"text": "function [varargout]=mat2wfdb(varargin)\n%\n% [xbit]=mat2wfdb(X,fname,Fs,bit_res,adu,info,gain,sg_name,baseline,isquant, isdigital)\n%\n% Convert data from a matlab array into Physionet WFDB format file.\n%\n% Input Paramater are:\n%\n% X -(required) NxM matrix of M signals with N samples each. The\n% signals can be of type double.The signals are assumed to be\n% in physical units already and will be converted to\n% ADU.\n% fname -(required) String where the the header (*.hea) and data (*.dat)\n% files will be saved (one single name for both, with no sufix).\n% Fs -(Optional) 1x1 sampling frequency in Hz (all signals must have\n% been sampled at the same frquency). Default is 1 Hz.\n% bit_res -(Optional) 1xM (or Mx1):scalar determining the bit depth of the conversion for\n% each signal.\n% 1x1 : If all the signals should have the same bit depth\n% Options are: 8, 16, and 32 ( all are signed types). 16 is the default.\n% adu -(Optional) Describes the physical units (default is 'mV').\n% Three input formats:\n% - String delimited by forward slashes (e.g. 'V/mV/mmHg'), with\n% M-1 slash characters\n% - Single string (e.g. 'V'), in which case all signals will \n% have the same physical units.\n% - Cell array of strings, where the total units entered has to equal M \n% (number of channels).\n% info -(Optional) String that will be added to the comment section of the header file.\n% For multi-lined comments, use a cell array of strings. Each\n% cell will be output on a new line. Note that comments in the\n% header file are automatically prefixed with a pound symbol (#)\n% gain -(Required for digital only) Scalar or Mx1 array of floats indicating the difference in sample values \n% that would be observed if a step of one physical unit occurred in the original \n% analog signal. If the 'isdigital' field is 1, this field is mandatory. Otherwise,\n% this field is ignored if present. \n% baseline -(Required for digital only) Mx1 array of integers that specifies the sample value for each channel\n% corresponding to 0 physical units. Not to be confused with 'ADC zero' which \n% is currently always taken and written as 0 in this function. If\n% the 'isdigital' field is 1, this field is mandatory. Otherwise,\n% this field is ignored if present. \n% sg_name -(Optional) Cell array of strings describing signal names.\n%\n% isquant -(Optional) Logical value (default=0). Use this option if the\n% input signal is already quantitized and you want to remove round-off\n% error by mapping the original values to integers prior to fixed\n% point conversion. This field is only used for input physical\n% signals. If 'isdigital' is set to 1, this field is ignored.\n%\n% isdigital -(Optional) Logical value (default=0). Specifies whether the input signal is \n% digital or physical (default). If it is digital, the signal values will be \n% directly written to the file without scaling. If the signal is physical, \n% the optimal gain and baseline will be calculated and used to digitize the signal\n% to write the WFDB file. This flag also decides the allowed\n% input combinations of the 'gain' and 'baseline' fields.\n% Digital signals must have both, and physical signals must have\n% neither (as the ideal values will be automatically calculated). \n%\n% Ouput Parameter:\n%\n% xbit -(Optional) NxM the quantitized signals that written to file (possible\n% rescaled if no gain was provided at input). Useful for comparing\n% and estimating quatitization error with the input double signal X\n% (see examples below).\n%\n%\n% NOTE: The signals can have different amplitudes, they will all be scaled to\n% a reference gain, with the scaling factor saved in the *.hea file.\n%\n%Written by Ikaro Silva 2010\n%Modified by Louis Mayaud 2011, Alistair Johson 2016\n% Version 1.0\n%\n% Since 0.0.1\n% See also wrsamp, wfdbdesc\n%\n%%%%%%%%%% Example 1 %%%%%%%%%%%%\n%\n% display('***This example will write a Ex1.dat and Ex1.hea file to your current directory!')\n% s=input('Hit \"ctrl + c\" to quit or \"Enter\" to continue!');\n%\n% %Generate 3 different signals and convert them to signed 16 bit in WFDB format\n% clear all;clc;close all\n% N=1024;\n% Fs=48000;\n% tm=[0:1/Fs:(N-1)/Fs]';\n% adu='V/mV/V';\n% info='Example 1';\n%\n%\n% %First signal a ramp with 2^16 unique levels and is set to (+-) 2^15 (Volts)\n% %Thus the header file should have one quant step equal to (2^15-(-2^15))/(2^16) V.\n% sig1=double(int16(linspace(-2^15,2^15,N)'));\n%\n% %Second signal is a sine wave with 2^8 unique levels and set to (+-) 1 (mV)\n% %Thus the header file should one quant step equal a (1--1)/(2^8) adu step\n% sig2=double(int8(sin(2*pi*tm*1000).*(2^7)))./(2^7);\n%\n% %Third signal is a random binary signal set to to (+-) 1 (V) with DC (to be discarded)\n% %Thus the header file should have one quant step equal a 1/(2^15) adu step.\n% sig3=(rand(N,1) > 0.97)*2 -1 + 2^16;\n%\n% %Concatenate all signals and convert to WFDB format with default 16 bits (empty brackets)\n% sig=[sig1 sig2 sig3];\n% mat2wfdb(sig,'Ex1',Fs,[],adu,info)\n%\n% % %NOTE: If you have WFDB installed you can check the conversion by\n% % %uncomenting and this section and running (notice that all signals are scaled\n% % %to unit amplitude during conversion, with the header files keeping the gain info):\n%\n% % !rdsamp -r Ex1 > foo\n% % x=dlmread('foo');\n% % subplot(211)\n% % plot(sig)\n% % subplot(212)\n% % plot(x(:,1),x(:,2));hold on;plot(x(:,1),x(:,3),'k');plot(x(:,1),x(:,4),'r')\n%\n%%%%%%%% End of Example 1%%%%%%%%%\n\n%endOfHelp\nmachine_format='l'; % all wfdb formats are little endian except fmt 61 which this function does not support. Do NOT change this.\nskip=0;\n\n% Set default parameters\nparams={'x','fname','Fs','bit_res','adu','info','gain','sg_name','baseline','isquant', 'isdigital'};\nFs=1;\nadu=[];\ninfo=[];\nisquant=0;\nisdigital=0;\n%Use cell array for baseline and gain in case of empty conditions\nbaseline=[];\ngain=[];\nsg_name=[];\nx=[];\nfname=[];\n%Used to convert signal from double to appropiate type\nbit_res = 16 ;\nbit_res_suport=[8 16 32];\n\nfor i=1:nargin\n if(~isempty(varargin{i}))\n eval([params{i} '= varargin{i};']);\n end\nend\n\ndisp(isdigital);\n% Check valid gain and baseline combinations depending on whether the input is digital or physical.\nif isdigital % digital input signal\n if (isempty(gain) || isempty(baseline))\n error('Input digital signals are directly written to files without scaling. Must also input gain and baseline for correct interpretation of written file.'); \n end\n if (~isempty(find(baseline>2147483647))||~isempty(find(baseline<-2147483648))) % baseline stored as int in wfdb library. \n error('Baseline field must lie between 2^-31 and 2^31-1 for this WFDB version'); % Prevent bit overflow\n end\nelse % physical input signal\n if ( ~isempty(gain) || ~isempty(baseline)) % User inputs gain or baseline to map the physical to digital values.\n % Sorry, we cannot trust that they did it correctly... \n warning('Input gain and baseline fields ignored for physical input signal. This function automatically calculates and applies the ideal values');\n end\nend\n \nswitch bit_res % Write formats. \n case 8\n fmt='80';\n case 16\n fmt='16';\n case 32\n fmt='32';\nend\n\n[N,M]=size(x);\n\nif isempty(adu) % default unit: 'mV'\n adu=repmat({'mV'},[M 1]);\nelseif iscell(adu) \n % adu directly input as a cell array of strings\nelseif ischar(adu)\n if ~isempty(strfind(adu,'/'))\n adu=regexp(adu,'/','split');\n else\n adu = repmat({adu},[M,1]);\n end\nend\n\n% ensure we have the right number of units\nif numel(adu) ~= M\n error('adu:wrongNumberOfElements','adu cell array has incorrect number of elements');\nend\n\nif(isempty(gain))\n gain=cell(M,1); %Generate empty cells as default\nelseif(length(gain)==1)\n gain=repmat(gain,[M 1]);\nend\n% ensure gain is a cell array\nif isnumeric(gain)\n gain=num2cell(gain);\nend\n\nif(isempty(sg_name))\n sg_name=repmat({''},[M 1]);\nend\nif ~isempty(setdiff(bit_res,bit_res_suport))\n error(['Bit res should be one of: ' num2str(bit_res_suport)]);\nend\nif(isempty(baseline))\n baseline=cell(M,1); %Generate empty cells as default\nelseif(length(baseline)==1)\n baseline=repmat(baseline,[M 1]);\nend\n% ensure baseline is a cell array\nif isnumeric(baseline)\n baseline=num2cell(baseline);\nend\n\nif isempty(isquant)\n isquant = zeros(M,1);\nelseif numel(isquant)==1\n isquant = repmat(isquant,[M,1]);\nelseif numel(isquant)~=M\n error('isquant:wrongNumberOfElements','isquant array has incorrect number of elements');\nend\n\n\n%Head record specification line\nhead_str=cell(M+1,1);\nhead_str(1)={[fname ' ' num2str(M) ' ' num2str(Fs) ' ' num2str(N)]};\n\nswitch bit_res % Allocate space for digital signals\n case 8\n y=uint8(zeros(N,M));\n case 16\n y=int16(zeros(N,M));\n case 32\n y=int32(zeros(N,M));\nend\n\n%Loop through all signals, digitizing them and generating lines in header file\nfor m=1:M\n nameArray = regexp(fname,'/','split');\n if ~isempty(nameArray)\n fname = nameArray{end};\n end\n \n [tmp_bit1,bit_gain,baseline_tmp,ck_sum]=quant(x(:,m), ...\n bit_res, gain{m}, baseline{m}, isquant(m), isdigital);\n \n y(:,m)=tmp_bit1;\n \n % Header file signal specification lines\n % Should we specify precision of num2str(gain)?\n head_str(m+1)={[fname '.dat ' fmt ' ' num2str(bit_gain) '(' ...\n num2str(baseline_tmp) ')/' adu{m} ' ' num2str(bit_res) ' 0 ' num2str(tmp_bit1(1)) ' ' num2str(ck_sum) ' 0 ' sg_name{m}]};\nend\nif(length(y)<1)\n error(['Converted data is empty. Exiting without saving file...']);\nend\n\n%Write *.dat file\nfid = fopen([fname '.dat'],'wb',machine_format);\nif(~fid)\n error(['Could not create data file for writing: ' fname]);\nend\n\nif (bit_res==8)\n count=fwrite(fid, y','uint8',skip,machine_format);\nelse\n count=fwrite(fid, y',['int' num2str(bit_res)],skip,machine_format);\nend\n\nif(~count)\n fclose(fid);\n error(['Could not data write to file: ' fname]);\nend\n\nfprintf(['Generated *.dat file: ' fname '\\n']);\nfclose(fid);\n\n%Write *.hea file\nfid = fopen([fname '.hea'],'w');\nfor m=1:M+1\n if(~fid)\n error(['Could not create header file for writing: ' fname]);\n end\n fprintf(fid,'%s\\n',head_str{m});\nend\n\nif(~isempty(info))\n if ischar(info)\n fprintf(fid,'#%s\\n',info);\n elseif iscell(info)\n for m=1:numel(info)\n fprintf(fid,'#%s\\n',info{m});\n end\n end\nend\n\nif(nargout==1)\n varargout(1)={y};\nend\nfprintf(['Generated *.hea file: ' fname '\\n']);\nfclose(fid);\n\nend\n\n%%%End of Main %%%%\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%Helper function\nfunction [y,adc_gain,baseline,check_sum]=quant(x, bit_res, gain, baseline, isquant, isdigital)\n\nmin_x=min(x(~isnan(x)));\nmax_x=max(x(~isnan(x)));\nnan_ind=isnan(x);\nrg=max_x-min_x;\n\nif(isdigital) \n % Digital input signal. Do not scale or shift the signal. The gain/baseline will only \n % be used to write the header file to interpret the output wfdb record.\n if ((min_x < -2^(bit_res-1)+1) || (max_x > (2^(bit_res-1)-1 )))\n error(['Digital input signal exceeds allowed range of specified output format: {' num2str(-2^(bit_res-1)+1) ' < x < ' num2str(2^(bit_res-1)-1) '}']);\n end\n adc_gain=gain;\n y=x;\n \nelse\n % Physical input signal - calculate the gain and baseline to minimize\n % the detail loss during ADC conversion: y = gain*x + baseline. Ignore any input gain or baseline\n \n % Calculate the adc_gain, baseline, and map the signal to digital\n % Make sure baseline doesn't go beyond 4 byte integer range\n \n if rg==0 % Flatline signal. Manually set adc_gain or it will be infinite.\n baseline=-(2^(bit_res-1))+1; % Set baseline to minimum value of bit res\n if x(1)==0\n adc_gain=1; % Arbitrary gain=1 for all 0 input signal. All values stored as baseline. \n else\n adc_gain=-baseline/x(1); % Set gain as inverse to store all values as exactly 0. \n end\n \n else % Non flatline signal: adc_gain = (range of encoding / range of Data) -- remember 1 quant level is for storing NaN\n % Constraint - baseline must be stored as a 4 byte integer for the WFDB library. \n if ((min_x>0) && (bit_res==32)) % All values are +ve, map with baseline = -2^31+1\n adc_gain=((2^32)-2)/max_x; \n baseline=-2147483647;\n if isquant==0 % Only display warning message if not recalculating later\n disp('Due to baseline constraints, output precision may be slightly less than 32 bits for the positive channel.');\n end\n elseif((max_x<0) && (bit_res==32)) % All values are -ve, map with baseline = 2^31-1\n adc_gain=((2^32)-2)/abs(min_x);\n baseline=2147483647;\n if isquant==0 % Only display warning message if not recalculating later\n disp('Due to baseline constraints, output precision may be slightly less than 32 bits for the negative channel.');\n end\n else % Signal has both +ve and -ve values or fmt is not 32. Use full range of bits. \n adc_gain=((2^bit_res)-2)/rg;\n baseline=round(-(2^(bit_res-1))+1-min_x*adc_gain);\n \n end\n if(isquant)\n % The (non flatline) input signal was already quantitized. Remove round-off error \n % by setting the original values to integers prior to fixed point conversion\n \n xvalues=sort(unique(x(~isnan(x)))); % All the values of x\n incmin=min(diff(xvalues)); % An estimate of the smallest possible increment in the input signal\n quantlevels=rg/incmin; % The estimated number of quantization levels in the input signal\n \n % We want to map 1 increment to 1 digital unit. First make sure\n % the full increment range is less than the 2^N-2 increments able to be encoded\n % by the chosen bit resolution. The incmin estimate will always\n % be equal to or larger than the true incmin, so it won't\n % wrongly trigger errors in this validation step. \n \n if (quantlevels>2^bit_res-2)\n if bit_res==32\n disp(['The input signal has more quantization levels than 32 bits -1. ' ...\n 'Cannot directly map all input values to integers. Up to 1 bit of roundoff error may occur. Continuing...']);\n calcquant=0; % Skip the integer matching and keep the old baseline/gain calculated. \n else\n error(['The input signal has more quantization levels than the chosen bit resolution. ' ...\n 'Please choose a higher resolution or remove the isquant option to allow up to 1 bit of roundoff error']);\n end\n else\n calcquant=1;\n end\n \n % Calculate gain+offset. Baseline must be stored as a 4 byte integer for the WFDB library.\n if calcquant\n if ((min_x>0) && (bit_res==32)) % 32 bit +ve quant mapping\n adc_gain=1/incmin;\n baseline=round(2147483647-adc_gain*max_x); % map max_x to 2^31-1. \n if (baseline<-2147483647) % Check if baseline goes below -2^31-1. If so, no quant. Recalculate gain and base. \n adc_gain=((2^32)-2)/max_x; \n baseline=-2147483647;\n disp('Due to baseline constraints, the channel will not be quantized. Output precision may be less than 32 bits for the positive channel.');\n end\n elseif((max_x<0) && (bit_res==32)) % 32 bit -ve quant mapping\n adc_gain=1/incmin;\n baseline=round(-2147483647-adc_gain*min_x); % map min_x to -2^31+1. \n if (baseline>2147483647) % Check if baseline goes above 2^31-1. If so, no quant. Recalculate gain and base. \n adc_gain=((2^32)-2)/abs(min_x); \n baseline=2147483647;\n disp('Due to baseline constraints, channel will not be quantized. Output precision may be less than 32 bits for the negative channel.');\n end\n else % Signal has both +ve and -ve values or fmt is not 32. Can use full range of bits.\n adc_gain=1/incmin; % 1 digital unit corresponds to the smallest physical increment.\n baseline=round(-(2^(bit_res-1))+1-min_x*adc_gain); % xmin still maps to ymin. xmax will not go beyond y limit, baseline should not go beyond 32 bit limits. \n end\n end\n end\n % Check for 8 and 16 bit format 'baseline' field overflow. VERY\n % uncommon situation. Occurs if entire signal is +ve or -ve\n % with very high magnitude.\n if (baseline>2147483647) % Signal is all negative with large magnitude.\n warning('Large offset input channel entered. Output precision may be less than specified format for the negative channel.');\n baseline=2147483647; % Baseline is max int value, min_x maps to min bitres value. \n adc_gain=(-(2^(bit_res-1))+1-baseline)/min_x;\n elseif (baseline<-2147483647) % Signal is all positive with large magnitude.\n warning('Large offset input channel entered. Output precision may be less than specified format for the positive channel.');\n baseline=-2147483647; % Baseline is min int value, max_x maps to max bitres value.\n adc_gain=(2^(bit_res-1)-1-baseline)/max_x;\n end\n end\n\n y=x*adc_gain+baseline;\n \nend % signal is in digital range. adc_gain and baseline have been calculated. \n\n% Convert signals to appropriate integer type, and shift any WFDB NaN int values to \n% a higher value so that they will not be read as NaN's by WFDB\nswitch bit_res % WFDB will interpret the smallest value as nan. \n case 8\n WFDBNAN=-128;\n y=int8(y); \n case 16\n WFDBNAN=-32768;\n y=int16(y);\n case 32\n WFDBNAN=-2147483648;\n y=int32(y);\nend\niswfdbnan=find(y==WFDBNAN); \nif(~isempty(iswfdbnan))\n y(iswfdbnan)=WFDBNAN+1;\nend\n\n%Set original NaNs to WFDBNAN\ny(nan_ind)=WFDBNAN;\n\n%Calculate the 16-bit signed checksum of all samples in the signal\ncheck_sum=sum(y);\nM=check_sum/(2^15);\nif(M<0)\n check_sum=mod(check_sum,-2^15);\n if(~check_sum && abs(M)<1)\n check_sum=-2^15;\n elseif (mod(ceil(M),2))\n check_sum=2^15 + check_sum;\n end\nelse\n check_sum=mod(check_sum,2^15);\n if(mod(floor(M),2))\n check_sum=-2^15+check_sum;\n end\nend\n\n% Note that checksum must be calculated on actual digital samples for format 80,\n% not the shifted ones. Therefore we only convert to real format now. \nif bit_res==8\n y=uint8(int16(y)+128); % Convert into unsigned for writing byte offset format. \nend\n\n% Signal is ready to be written to dat file. \n\nend\n\n\nfunction y=get_names(str,deli)\n\ny={};\nold=1;\nind=regexp(str,deli);\nind(end+1)=length(str)+1;\nfor i=1:length(ind)\n y(end+1)={str(old:ind(i)-1)};\n old=ind(i)+1;\nend\n\nend\n\n\n", "meta": {"author": "ikarosilva", "repo": "wfdb-app-toolbox", "sha": "6e81e0d4e7e275418bc13def7c29d6a4464a519b", "save_path": "github-repos/MATLAB/ikarosilva-wfdb-app-toolbox", "path": "github-repos/MATLAB/ikarosilva-wfdb-app-toolbox/wfdb-app-toolbox-6e81e0d4e7e275418bc13def7c29d6a4464a519b/mcode/mat2wfdb.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.3246290063682356}} {"text": "function varargout = OregonatorGUI(varargin)\n% OREGONATORGUI M-file for OregonatorGUI.fig\n% OREGONATORGUI, by itself, creates a new OREGONATORGUI or raises the existing\n% singleton*.\n%\n% H = OREGONATORGUI returns the handle to a new OREGONATORGUI or the handle to\n% the existing singleton*.\n%\n% OREGONATORGUI('CALLBACK',hObject,eventData,handles,...) calls the local\n% function named CALLBACK in OREGONATORGUI.M with the given input arguments.\n%\n% OREGONATORGUI('Property','Value',...) creates a new OREGONATORGUI or raises the\n% existing singleton*. Starting from the left, property value pairs are\n% applied to the GUI before OregonatorGUI_OpeningFunction gets called. An\n% unrecognized property name or invalid value makes property application\n% stop. All inputs are passed to OregonatorGUI_OpeningFcn via varargin.\n%\n% *See GUI Options on GUIDE's Tools menu. Choose \"GUI allows only one\n% instance to run (singleton)\".\n%\n% See also: GUIDE, GUIDATA, GUIHANDLES\n\n% Copyright 2002-2003 The MathWorks, Inc.\n\n% Edit the above text to modify the response to help OregonatorGUI\n\n% Last Modified by GUIDE v2.5 02-Dec-2005 23:24:01\n\n% Begin initialization code - DO NOT EDIT\ngui_Singleton = 1;\ngui_State = struct('gui_Name', mfilename, ...\n 'gui_Singleton', gui_Singleton, ...\n 'gui_OpeningFcn', @OregonatorGUI_OpeningFcn, ...\n 'gui_OutputFcn', @OregonatorGUI_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 OregonatorGUI is made visible.\nfunction OregonatorGUI_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 OregonatorGUI (see VARARGIN)\n\n% Choose default command line output for OregonatorGUI\nhandles.output = hObject;\n\n% Update handles structure\nguidata(hObject, handles);\n\n% UIWAIT makes OregonatorGUI 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 = OregonatorGUI_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 button press in pushbutton1.\nfunction pushbutton1_Callback(hObject, eventdata, handles)\n% hObject handle to pushbutton1 (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\n% --- Executes on button press in pushbutton2.\nfunction pushbutton2_Callback(hObject, eventdata, handles)\n% hObject handle to pushbutton2 (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\nx0=[1 1 1];\n\n[t,x]=ode15s(@oregonator,[0 600],x0);\n\naxes(handles.axes1);\nplot(t,x(:,1),'r');\naxis([300,600,0,100]);\ntitle('figure1');\nXlabel('temps');\nYlabel('x(1)');\n\naxes(handles.axes2);\nplot(t,x(:,2),'g');\naxis([300,600,0,3]);\ntitle('figure2');\nXlabel('temps');\nYlabel('x(2)');\n\naxes(handles.axes3);\nplot(t,x(:,3),'m');\naxis([300,600,0,100]);\ntitle('figure3');\nXlabel('temps');\nYlabel('x(3)');\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/9305-lotka-volterra-oregonator-using-gui/OregonatorGUI.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.32462899948420604}} {"text": "% GCI_creak_postproc.m\n% Function to do the post-processing step to remove false positive GCIs\n% detected in creaky voice regions\n%\n% Octave compatible\n%\n% Description\n% Function to do the post-processing step to remove false positive GCIs\n% detected in creaky voice regions\n%\n% Inputs\n% GCI : [samples] [Mx1] Glottal closure instants\n% creak : [binary] [Nx1] Creak decision \n% search_reg : [integer] [1x1] Search factor\n% rep : [samples] [Nx1] Resonator output\n% removeThresh : [integer] [1x1] Threshold for false GCI removal\n% repNum : [integer] [1x1] number of repititions\n%\n% Outputs\n% GCI : [samples] [Mx1] Glottal closure instants\n%\n% Example\n% GCI = GCI_creak_postproc(GCI,creak,search_reg,rep,removeThresh,repNum)\n%\n% References\n% [1] Kane, J., Gobl, C., (2013) `Evaluation of glottal closure instant \n% detection in a range of voice qualities', Speech Communication \n% 55(2), pp. 295-314.\n%\n% Copyright (c) 2013 Trinity College Dublin\n%\n% License\n% This code is a part of the Voice Analysis Toolkit with the following\n% licence:\n% The software product (and any modifications thereof) is distributed under \n% a dual licence: an open source license for individual, non-commercial \n% purposes, and a commercial license. The opensource licence under which \n% the product is distributed is GNU GPL v2. For individual users, this \n% licence suits their use as these are not distributing proprietary \n% modifications, additions to, or derivatives of the product and don't \n% require legal protection of a commercial licence. For commercial users, \n% where open source does not meet their requirements, we offer commercial \n% licensing of the product. A commercial license permits customers to \n% modify, add or produce derivative products without the obligation of \n% making the subsequent code open source. For more information regarding \n% our commercial licence, please contact john.whelan@tcd.ie\n%\n% This function is part of the Covarep project: http://covarep.github.io/covarep\n% \n% Author \n% John Kane kanejo@tcd.ie\n%\n% $Id $\n\nfunction GCI = GCI_creak_postproc(GCI,creak,search_reg,rep,removeThresh,repNum)\n\n% Separate GCIs detected in creaky voice regions from other regions\ncreak_GCI=GCI(creak(GCI)==1);\nGCI(creak(GCI)==1)=[];\n \nfor m=1:repNum\n n=2;\n while n < length(creak_GCI)\n cur_rep_max = abs(min(rep(creak_GCI(n)-round(search_reg):creak_GCI(n)+round(search_reg))));\n\n if mean([abs(rep(creak_GCI(n-1))) abs(rep(creak_GCI(n+1)))])*removeThresh > cur_rep_max\n creak_GCI(n)=NaN;\n n=n+2;\n else n=n+1;\n end\n end\n creak_GCI(isnan(creak_GCI))=[];\nend\n \nGCI=sort(unique([GCI(:)' creak_GCI(:)']));", "meta": {"author": "covarep", "repo": "covarep", "sha": "5a2be5d6b776f14a0b275c69fde90eb13849e60d", "save_path": "github-repos/MATLAB/covarep-covarep", "path": "github-repos/MATLAB/covarep-covarep/covarep-5a2be5d6b776f14a0b275c69fde90eb13849e60d/glottalsource/se_vq/private/GCI_creak_postproc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5851011686727231, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.32442131704285415}} {"text": "function [x, output] = findExtremePathway(fbaModel, obj)\n% Finds an extreme ray\n%\n% USAGE:\n%\n% [x, output] = findExtremePathway(fbaModel, obj)\n%\n% INPUT:\n% fbaModel: FBA type model\n%\n% OPTIONAL INPUT:\n% obj: default = random vector with size depending on fbaModel.S\n%\n% OUTPUTS:\n% x: vector from `result`, where `result` is an output of `solveCobraLP` function\n% output: `output.objval` contains `result.obj`\n%\n% .. $Revision: 0.1 $ $Date: 2011/05/01 $\n\nA = fbaModel.S;\n[nmet,nrxn] = size(A);\n\n% Convert model to conic form\nif isfield(fbaModel, 'ub') && isfield(fbaModel, 'lb')\n revRxns = fbaModel.lb < 0 & fbaModel.ub > 0;\nelse\n error('missing fields: revRxns or ub and lb\\n');\nend\n\nA = [A, -A(:,revRxns)];\n[~, n] = size(A);\n\nif nargin < 2\n obj = rand(n,1);\nend\n\n% Set required model components\nLPProblem = struct();\nLPProblem.A = sparse([A; ones(1,n)]);\nLPProblem.c = obj;\nLPProblem.csense = repmat('E',nmet+1,1);\nLPProblem.b = [zeros(nmet,1); 1];\n% Set optional model components\nLPProblem.osense= -1;\nLPProblem.lb = 0* ones(n,1);\nLPProblem.ub = inf* ones(n,1);\n\nresult = solveCobraLP(LPProblem); % Find extreme ray (be aware, that this can easily be a loop of a reversible reaction.\n\nx = result.full(1:nrxn);\nx(revRxns) = x(revRxns) - result.full(nrxn+1:end);\n\noutput.objval = result.obj;\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/src/analysis/topology/extremeRays/optimalRays/findExtremePathway.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.32434608088512}} {"text": "classdef AMICO_WATERFREE\n\nproperties\n id, name % id and name of the model\n dPar % parallel diffusivity of the tensors [units of mm^2/s]\n dPer % perpendicular diffusivities of the tensors [units of mm^2/s]\n dIso % isotropic diffusivities [units of mm^2/s]\n OUTPUT_names % suffix of the output maps\n OUTPUT_descriptions % description of the output maps\nend\n\n\nmethods\n\n % =================================\n % Setup the parameters of the model\n % =================================\n\tfunction obj = AMICO_WATERFREE()\n global CONFIG\n\n % set the parameters of the model\n obj.id = 'WATERFREE';\n obj.name = 'Water free';\n obj.dPar = 1.7 * 1E-3;\n obj.dIso = [2.0 3.0] * 1E-3;\n obj.dPer = linspace(0.1,1.0,10) * 1E-3;\n\n obj.OUTPUT_names = { 'ICVF', 'ISOVF' };\n obj.OUTPUT_descriptions = {'Intra-cellular volume fraction', 'Isotropic volume fraction'};\n\n % set the parameters to fit it\n CONFIG.OPTIMIZATION.SPAMS_param.mode = 2;\n CONFIG.OPTIMIZATION.SPAMS_param.pos = true;\n CONFIG.OPTIMIZATION.SPAMS_param.lambda = 0; % l1 regularization\n CONFIG.OPTIMIZATION.SPAMS_param.lambda2 = 1e-3; % l2 regularization\n end\n\n\n % ==================================================================\n % Generate high-resolution kernels and rotate them in harmonic space\n % ==================================================================\n function GenerateKernels( obj, ATOMS_path, schemeHR, AUX, idx_IN, idx_OUT )\n global CONFIG AMICO_data_path\n\n % Tensor compartments\n % ===================\n idx = 1;\n for i = 1:numel(obj.dPer)\n TIME = tic();\n fprintf( '\\t\\t- A_%03d... ', idx );\n\n % generate\n D = diag( [obj.dPer(i) obj.dPer(i) obj.dPar] );\n signal = obj.TensorSignal( D, schemeHR.camino );\n\n % rotate and save\n lm = AMICO_RotateKernel( signal, AUX, idx_IN, idx_OUT, false );\n save( fullfile( ATOMS_path, sprintf('A_%03d.mat',idx) ), '-v6', 'lm' )\n idx = idx + 1;\n\n fprintf( '[%.1f seconds]\\n', toc(TIME) );\n end\n\n\n % Isotropic compartments\n % ======================\n for i = 1:numel(obj.dIso)\n TIME = tic();\n fprintf( '\\t\\t- A_%03d... ', idx );\n\n % generate\n D = diag( [obj.dIso(i) obj.dIso(i) obj.dIso(i)] );\n signal = obj.TensorSignal( D, schemeHR.camino );\n\n % resample and save\n lm = AMICO_RotateKernel( signal, AUX, idx_IN, idx_OUT, true );\n save( fullfile( ATOMS_path, sprintf('A_%03d.mat',idx) ), '-v6', 'lm' )\n idx = idx + 1;\n\n fprintf( '[%.1f seconds]\\n', toc(TIME) );\n end\n\n end\n\n\n % ==============================================\n % Project kernels from harmonic to subject space\n % ==============================================\n function ResampleKernels( obj, ATOMS_path, idx_OUT, Ylm_OUT )\n global CONFIG AMICO_data_path KERNELS\n\n % Setup the KERNELS structure\n % ===========================\n n1 = numel(obj.dPer);\n n2 = numel(obj.dIso);\n KERNELS = {};\n KERNELS.nS = CONFIG.scheme.nS;\n KERNELS.nA = n1 + n2; % number of atoms\n KERNELS.A1 = zeros( [KERNELS.nS n1 181 181], 'single' );\n KERNELS.A2 = zeros( [KERNELS.nS n2], 'single' );\n\n\n % Tensors\n % =======\n idx = 1;\n for i = 1:n1\n TIME = tic();\n fprintf( '\\t- A_%03d... ', idx );\n\n load( fullfile( ATOMS_path, sprintf('A_%03d.mat',idx) ), 'lm' );\n KERNELS.A1(:,i,:,:) = AMICO_ResampleKernel( lm, idx_OUT, Ylm_OUT, false );\n idx = idx + 1;\n\n fprintf( '[%.1f seconds]\\n', toc(TIME) );\n end\n\n\n % Isotropic\n % =========\n for i = 1:n2\n TIME = tic();\n fprintf( '\\t- A_%03d... ', idx );\n\n load( fullfile( ATOMS_path, sprintf('A_%03d.mat',idx) ), 'lm' );\n KERNELS.A2(:,i,:,:) = AMICO_ResampleKernel( lm, idx_OUT, Ylm_OUT, true );\n idx = idx + 1;\n\n fprintf( '[%.1f seconds]\\n', toc(TIME) );\n end\n\n end\n\n\n % ===========================\n % Fit the model to each voxel\n % ===========================\n function [DIRs, MAPs] = Fit( obj )\n global CONFIG\n global niiSIGNAL niiMASK\n global KERNELS bMATRIX\n\n % setup the output files\n MAPs = zeros( [CONFIG.dim(1:3) numel(obj.OUTPUT_names)], 'single' );\n DIRs = zeros( [CONFIG.dim(1:3) 3], 'single' );\n niiY = niiSIGNAL;\n \n n1 = numel(obj.dPer);\n n2 = numel(obj.dIso);\n\n fprintf( '\\n-> Fitting \"%s\" model to data:\\n', obj.name );\n TIME = tic();\n for iz = 1:niiSIGNAL.hdr.dime.dim(4)\n for iy = 1:niiSIGNAL.hdr.dime.dim(3)\n for ix = 1:niiSIGNAL.hdr.dime.dim(2)\n if niiMASK.img(ix,iy,iz)==0, continue, end\n\n % read the signal\n b0 = mean( squeeze( niiSIGNAL.img(ix,iy,iz,CONFIG.scheme.b0_idx) ) );\n if ( b0 < 1e-3 ), continue, end\n y = double( squeeze( niiSIGNAL.img(ix,iy,iz,:) ) ./ ( b0 + eps ) );\n y( y < 0 ) = 0; % [NOTE] this should not happen!\n\n % build the DICTIONARY\n [ i1, i2 ] = AMICO_Dir2idx( Vt );\n A = double( [ KERNELS.A1(CONFIG.scheme.dwi_idx,:,i1,i2) KERNELS.A2(CONFIG.scheme.dwi_idx,:) ] );\n\n % fit AMICO\n y = y(CONFIG.scheme.dwi_idx);\n yy = [ 1 ; y ];\n AA = [ ones(1,size(A,2)) ; A ];\n\n % estimate CSF partial volume and remove it\n x = full( mexLasso( yy, AA, CONFIG.OPTIMIZATION.SPAMS_param ) );\n \n % STORE results\t\n DIRs(ix,iy,iz,:) = Vt; % fiber direction\n\n MAPs(ix,iy,iz,1) = sum( x(1:n1) ) / ( sum(x) + eps ); % intracellular volume fraction\n\n MAPs(ix,iy,iz,2) = 1 - MAPs(ix,iy,iz,1); % isotropic volume fraction\n \n x(n1+1:end) = 0;\n niiY.img(ix,iy,iz,CONFIG.scheme.dwi_idx) = AA(2:end,:)*x*b0;\n \n end\n end\n end\n save_untouch_nii(niiY, 'dwi_fw_corrected.nii');\n TIME = toc(TIME);\n fprintf( ' [ %.0fh %.0fm %.0fs ]\\n', floor(TIME/3600), floor(mod(TIME/60,60)), mod(TIME,60) )\n\n % compute MAPS\n n1 = numel(obj.dPer);\n MAPs = zeros( [1 numel(obj.OUTPUT_names)], 'single' );\n MAPs(1) = sum( x(1:n1) ) / ( sum(x) + eps ); % intracellular volume fraction\n MAPs(2) = 1 - MAPs(1); % isotropic volume fraction\n end\n\n\n % ================================================================\n % Simulate signal according to tensor model (1 fiber along z-axis)\n % ================================================================\n function [ signal ] = TensorSignal( obj, D, XYZB )\n nDIR = size( XYZB, 1 );\n signal = zeros( nDIR, 1 );\n for d = 1:nDIR\n signal(d) = exp(-XYZB(d,4) * XYZB(d,1:3) * D * XYZB(d,1:3)');\n end\n end\n\nend\n\nend\n", "meta": {"author": "qMRLab", "repo": "qMRLab", "sha": "036ff20b47e939877f746940a969494b55911636", "save_path": "github-repos/MATLAB/qMRLab-qMRLab", "path": "github-repos/MATLAB/qMRLab-qMRLab/qMRLab-036ff20b47e939877f746940a969494b55911636/External/AMICO/AMICO_matlab/models/AMICO_WATERFREE.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.32434608088512}} {"text": "function [results, success, raw] = dcopf_solver(om, mpopt)\n%DCOPF_SOLVER Solves a DC optimal power flow.\n%\n% [RESULTS, SUCCESS, RAW] = DCOPF_SOLVER(OM, MPOPT)\n%\n% Inputs are an OPF model object and a MATPOWER options struct.\n%\n% Outputs are a RESULTS struct, SUCCESS flag and RAW output struct.\n%\n% RESULTS is a MATPOWER case struct (mpc) with the usual baseMVA, bus\n% branch, gen, gencost fields, along with the following additional\n% fields:\n% .order see 'help ext2int' for details of this field\n% .x final value of optimization variables (internal order)\n% .f final objective function value\n% .mu shadow prices on ...\n% .var\n% .l lower bounds on variables\n% .u upper bounds on variables\n% .lin\n% .l lower bounds on linear constraints\n% .u upper bounds on linear constraints\n%\n% SUCCESS 1 if solver converged successfully, 0 otherwise\n%\n% RAW raw output in form returned by MINOS\n% .xr final value of optimization variables\n% .pimul constraint multipliers\n% .info solver specific termination code\n% .output solver specific output information\n%\n% See also OPF, OPT_MODEL/SOLVE.\n\n% MATPOWER\n% Copyright (c) 2000-2020, Power Systems Engineering Research Center (PSERC)\n% by Ray Zimmerman, PSERC Cornell\n% and Carlos E. Murillo-Sanchez, PSERC Cornell & Universidad Nacional de Colombia\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%%----- initialization -----\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[GEN_BUS, PG, QG, QMAX, QMIN, VG, MBASE, GEN_STATUS, PMAX, PMIN, ...\n MU_PMAX, MU_PMIN, MU_QMAX, MU_QMIN, PC1, PC2, QC1MIN, QC1MAX, ...\n QC2MIN, QC2MAX, RAMP_AGC, RAMP_10, RAMP_30, RAMP_Q, APF] = idx_gen;\n[F_BUS, T_BUS, BR_R, BR_X, BR_B, RATE_A, RATE_B, RATE_C, ...\n TAP, SHIFT, BR_STATUS, PF, QF, PT, QT, MU_SF, MU_ST, ...\n ANGMIN, ANGMAX, MU_ANGMIN, MU_ANGMAX] = idx_brch;\n[PW_LINEAR, POLYNOMIAL, MODEL, STARTUP, SHUTDOWN, NCOST, COST] = idx_cost;\n\n%% unpack data\nmpc = om.get_mpc();\n[baseMVA, bus, gen, branch, gencost] = ...\n deal(mpc.baseMVA, mpc.bus, mpc.gen, mpc.branch, mpc.gencost);\ncp = om.params_legacy_cost();\nBf = om.get_userdata('Bf');\nPfinj = om.get_userdata('Pfinj');\n[vv, ll] = om.get_idx();\n\n%% problem dimensions\nnb = size(bus, 1); %% number of buses\nnl = size(branch, 1); %% number of branches\nny = om.getN('var', 'y'); %% number of piece-wise linear costs\n\n%% options\nmodel = om.problem_type();\nopt = mpopt2qpopt(mpopt, model);\nif strcmp(opt.alg, 'OSQP')\n opt.x0 = []; %% disable provided starting point for OSQP\nend\n\n%% try to select an interior initial point, unless requested not to\nif mpopt.opf.start < 2 && ...\n (strcmp(opt.alg, 'MIPS') || strcmp(opt.alg, 'IPOPT'))\n [x0, xmin, xmax] = om.params_var(); %% init var & bounds\n s = 1; %% set init point inside bounds by s\n lb = xmin; ub = xmax;\n lb(xmin == -Inf) = -1e10; %% replace Inf with numerical proxies\n ub(xmax == Inf) = 1e10;\n x0 = (lb + ub) / 2; %% set x0 mid-way between bounds\n k = find(xmin == -Inf & xmax < Inf); %% if only bounded above\n x0(k) = xmax(k) - s; %% set just below upper bound\n k = find(xmin > -Inf & xmax == Inf); %% if only bounded below\n x0(k) = xmin(k) + s; %% set just above lower bound\n Varefs = bus(bus(:, BUS_TYPE) == REF, VA) * (pi/180);\n x0(vv.i1.Va:vv.iN.Va) = Varefs(1); %% angles set to first reference angle\n if ny > 0\n ipwl = find(gencost(:, MODEL) == PW_LINEAR);\n c = gencost(sub2ind(size(gencost), ipwl, NCOST+2*gencost(ipwl, NCOST))); %% largest y-value in CCV data\n x0(vv.i1.y:vv.iN.y) = max(c) + 0.1 * abs(max(c));\n end\n opt.x0 = x0;\nend\n\n%%----- run opf -----\n[x, f, eflag, output, lambda] = om.solve(opt);\nsuccess = (eflag == 1);\n\n%%----- calculate return values -----\nif ~any(isnan(x))\n %% update solution data\n Va = x(vv.i1.Va:vv.iN.Va);\n Pg = x(vv.i1.Pg:vv.iN.Pg);\n\n %% update voltages & generator outputs\n bus(:, VM) = ones(nb, 1);\n bus(:, VA) = Va * 180/pi;\n gen(:, PG) = Pg * baseMVA;\n\n %% compute branch flows\n branch(:, [QF, QT]) = zeros(nl, 2);\n branch(:, PF) = (Bf * Va + Pfinj) * baseMVA;\n branch(:, PT) = -branch(:, PF);\nend\n\n%% package up results\nmu_l = lambda.mu_l;\nmu_u = lambda.mu_u;\nmuLB = lambda.lower;\nmuUB = lambda.upper;\n\n%% update Lagrange multipliers\nil = find(branch(:, RATE_A) ~= 0 & branch(:, RATE_A) < 1e10);\nbus(:, [LAM_P, LAM_Q, MU_VMIN, MU_VMAX]) = zeros(nb, 4);\ngen(:, [MU_PMIN, MU_PMAX, MU_QMIN, MU_QMAX]) = zeros(size(gen, 1), 4);\nbranch(:, [MU_SF, MU_ST]) = zeros(nl, 2);\nbus(:, LAM_P) = (mu_u(ll.i1.Pmis:ll.iN.Pmis) - mu_l(ll.i1.Pmis:ll.iN.Pmis)) / baseMVA;\nif ~isempty(il)\n branch(il, MU_SF) = mu_u(ll.i1.Pf:ll.iN.Pf) / baseMVA;\n branch(il, MU_ST) = mu_l(ll.i1.Pf:ll.iN.Pf) / baseMVA;\nend\ngen(:, MU_PMIN) = muLB(vv.i1.Pg:vv.iN.Pg) / baseMVA;\ngen(:, MU_PMAX) = muUB(vv.i1.Pg:vv.iN.Pg) / baseMVA;\npimul = [\n mu_l - mu_u;\n -ones(ny>0, 1); %% dummy entry corresponding to linear cost row in A (in MINOS)\n muLB - muUB\n];\n\nmu = struct( ...\n 'var', struct('l', muLB, 'u', muUB), ...\n 'lin', struct('l', mu_l, 'u', mu_u) );\n\nresults = mpc;\n[results.bus, results.branch, results.gen, ...\n results.om, results.x, results.mu, results.f] = ...\n deal(bus, branch, gen, om, x, mu, f);\n\nraw = struct('xr', x, 'pimul', pimul, 'info', eflag, 'output', output);\n", "meta": {"author": "MATPOWER", "repo": "matpower", "sha": "7da926d978824bf675a71e0a5cb91f8967f97007", "save_path": "github-repos/MATLAB/MATPOWER-matpower", "path": "github-repos/MATLAB/MATPOWER-matpower/matpower-7da926d978824bf675a71e0a5cb91f8967f97007/lib/dcopf_solver.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7279754607093178, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.3243345685300411}} {"text": "%% DEMO_febio_0029_contact_friction_benchmark_boxes\n% Below is a demonstration for a FEBio demo presented at the FEBio workshop at\n% WCB 2018. Four cubes are stacked on top of each other. Sliding-elastic\n% contact with friction is defined between them. The top cube is forced\n% downwards in a rotation motion thereby compressing the other cubes and\n% also transferring some twist due to frictional forces. \n%\n% The demo includes \n% * Building geometry for 4 cubes with hexahedral elements \n% * Defining the boundary conditions \n% * Coding the febio structure\n% * Running the model\n% * Importing and visualizing the displacement results\n\n%% Keywords\n%\n% * febio_spec version 3.0\n% * febio, FEBio\n% * indentation\n% * contact, sliding, sliding-elastic, friction\n% * rigid body constraints\n% * hexahedral elements, hex8\n% * quadrilateral elements, quad4\n% * static, solid\n% * displacement logfile\n% * stress logfile\n\n%%\n\nclear; close all; clc;\n\n%% Plot settings\nfontSize=15;\nfaceAlpha1=0.8;\nfaceAlpha2=0.3;\nmarkerSize=40;\nmarkerSize2=20;\nlineWidth=3;\n\n%% Control parameters\n\n% Path names\ndefaultFolder = fileparts(fileparts(mfilename('fullpath')));\nsavePath=fullfile(defaultFolder,'data','temp');\n\n% Defining file names\nfebioFebFileNamePart='tempModel';\nfebioFebFileName=fullfile(savePath,[febioFebFileNamePart,'.feb']); %FEB file name\nfebioLogFileName=fullfile(savePath,[febioFebFileNamePart,'.txt']); %FEBio log file name\nfebioLogFileName_disp=[febioFebFileNamePart,'_disp_out.txt']; %Log file name for exporting displacement\nfebioLogFileName_strainEnergy=[febioFebFileNamePart,'_fsed_out.txt']; %Log file name for exporting strain energy density\n\n%Specifying dimensions and number of elements for slab\nsampleHeight=2; %Height\nsampleWidth=sampleHeight; %Width \nsampleThickness=sampleHeight; %Thickness \n \nnumElementsWidth=[4 3 5 4]; %Number of elemens in dir 1\nnumElementsThickness=numElementsWidth; %Number of elemens in dir 2\nnumElementsHeight=numElementsWidth; %Number of elemens in dir 3\n\n%Material parameter set\nyoungsModuli = [0.3 10 0.3 10 ];\npoissonsRatios = [0.4 0.1 0.4 0.1]; \n\n% FEA control settings\nnumTimeSteps=10; %Number of time steps desired\nmax_refs=25; %Max reforms\nmax_ups=0; %Set to zero to use full-Newton iterations\nopt_iter=25; %Optimum number of iterations\nmax_retries=10; %Maximum number of retires\ndtmin=(1/numTimeSteps)/10; %Minimum time step size\ndtmax=1/numTimeSteps; %Maximum time step size\n\n%Contact parameters\ncontactInitialOffset=0;\nboxOffsets=sampleHeight+contactInitialOffset;\n\n%Prescribed displacement\nprescribedDisplacement_Z=-2; \nprescribedRotation_Z=pi/2;\n\n%% Creating model geometry and mesh\n% A box is created with tri-linear hexahedral (hex8) elements using the\n% |hexMeshBox| function. The function offers the boundary faces with\n% seperate labels for the top, bottom, left, right, front, and back sides.\n% As such these can be used to define boundary conditions on the exterior. \n\nE=[];\nelementMaterialID=[];\nV=[];\nFb=[];\nCb=[];\nfor q=1:1:4\n \n % Create a box with hexahedral elements\n beamDimensions=[sampleWidth sampleThickness sampleHeight]; %Dimensions\n beamElementNumbers=[numElementsWidth(q) numElementsThickness(q) numElementsHeight(q)]; %Number of elements\n outputStructType=2; %A structure compatible with mesh view\n [meshStruct]=hexMeshBox(beamDimensions,beamElementNumbers,outputStructType);\n \n %Access elements, nodes, and faces from the structure\n E1=meshStruct.elements; %The elements\n V1=meshStruct.nodes; %The nodes (vertices)\n Fb1=meshStruct.facesBoundary; %The boundary faces\n Cb1=meshStruct.boundaryMarker; %The \"colors\" or labels for the boundary faces\n elementMaterialIndices=ones(size(E1,1),1); %Element material indices\n\n V1(:,3)=V1(:,3)+(q-1)*boxOffsets;\n \n E=[E;E1+size(V,1)];\n Fb=[Fb;Fb1+size(V,1)];\n V=[V;V1]; \n colorOffset=max(Cb(:));\n if isempty(colorOffset)\n colorOffset=0;\n end\n Cb=[Cb;Cb1+colorOffset];\n \n elementMaterialID=[elementMaterialID;q*ones(size(E1,1),1)];\n \nend\nV(:,3)=V(:,3)-min(V(:,3)); %Shift so bottom is at 0\n\n%% \n% Plotting model boundary surfaces and a cut view\n\nhFig=cFigure; \nhold on; \ntitle('Model boundary surfaces and labels','FontSize',fontSize);\ngpatch(Fb,V,Cb,'k',faceAlpha1); \ncolormap(gjet(250)); icolorbar;\naxisGeom(gca,fontSize);\ndrawnow;\n\n%%\n\nlogicTops=false(size(Cb,1),4);\nlogicBottoms=false(size(Cb,1),4);\nfor q=1:1:4\n logicTops(:,q)=Cb==6+(6*(q-1)); \n logicBottoms(:,q)=Cb==5+(6*(q-1)); \nend\n\n\n%% \n% Plotting model boundary surfaces \n\nhFig=cFigure; \nhold on; \ntitle('Contact faces','FontSize',fontSize);\ngpatch(Fb,V,'kw','none',0.2);\nfor q=1:1:size(logicTops,2)-1\n gpatch(Fb(logicTops(:,q),:),V,q*ones(nnz(logicTops(:,q)),1),'g',1);\n gpatch(Fb(logicBottoms(:,q+1),:),V,q*ones(nnz(logicBottoms(:,q+1)),1),'y',1);\nend\n\ncolormap(gjet(250)); icolorbar;\naxisGeom(gca,fontSize);\ndrawnow;\n\n%% Define boundary conditions\n\nF_support=Fb(logicBottoms(:,1),:);\n\nF_rigidBody=Fb(logicTops(:,end),:);\nindNodesRigidBody=unique(F_rigidBody(:));\ncenter_of_mass=mean(V(indNodesRigidBody,:),1);\n\n%Supported nodes\nbcSupportList=unique(F_support(:));\n\n%Visualize BC's\nhf=cFigure;\ntitle('Boundary conditions model','FontSize',fontSize);\nxlabel('X','FontSize',fontSize); ylabel('Y','FontSize',fontSize); zlabel('Z','FontSize',fontSize);\nhold on;\n\ngpatch(Fb,V,'kw','none',faceAlpha2); \nhl(1)=gpatch(F_rigidBody,V,'rw','k',1); \nhl(2)=plotV(V(bcSupportList,:),'k.','MarkerSize',markerSize);\nhl(3)=plotV(center_of_mass,'r.','MarkerSize',50);\n\nlegend(hl,{'Rigid body','BC support','Rigid body center of mass'});\n\naxisGeom(gca,fontSize);\ncamlight headlight;\ndrawnow;\n\n%% Defining the FEBio input structure\n% See also |febioStructTemplate| and |febioStruct2xml| and the FEBio user\n% manual.\n\n%Get a template with default settings \n[febio_spec]=febioStructTemplate;\n\n%febio_spec version \nfebio_spec.ATTR.version='3.0'; \n\n%Module section\nfebio_spec.Module.ATTR.type='solid'; \n\n%Control section\nfebio_spec.Control.analysis='STATIC';\nfebio_spec.Control.time_steps=numTimeSteps;\nfebio_spec.Control.step_size=1/numTimeSteps;\nfebio_spec.Control.solver.max_refs=max_refs;\nfebio_spec.Control.solver.max_ups=max_ups;\nfebio_spec.Control.solver.symmetric_stiffness=0;\nfebio_spec.Control.time_stepper.dtmin=dtmin;\nfebio_spec.Control.time_stepper.dtmax=dtmax; \nfebio_spec.Control.time_stepper.max_retries=max_retries;\nfebio_spec.Control.time_stepper.opt_iter=opt_iter;\n\n%Material section\nfor q=1:1:numel(youngsModuli)\n materialNameNow=['Material',num2str(q)];\n febio_spec.Material.material{q}.ATTR.name=materialNameNow;\n febio_spec.Material.material{q}.ATTR.type='neo-Hookean';\n febio_spec.Material.material{q}.ATTR.id=q;\n febio_spec.Material.material{q}.E=youngsModuli(q);\n febio_spec.Material.material{q}.v=poissonsRatios(q);\nend\n\nmaterialNameRigid='RigidMaterial';\nmatIdRigid=numel(youngsModuli)+1;\nfebio_spec.Material.material{matIdRigid}.ATTR.name=materialNameRigid;\nfebio_spec.Material.material{matIdRigid}.ATTR.type='rigid body';\nfebio_spec.Material.material{matIdRigid}.ATTR.id=numel(youngsModuli)+1;\nfebio_spec.Material.material{matIdRigid}.density=1;\nfebio_spec.Material.material{matIdRigid}.center_of_mass=center_of_mass;\n\n%Mesh section\n% -> Nodes\nfebio_spec.Mesh.Nodes{1}.ATTR.name='nodeSet_all'; %The node set name\nfebio_spec.Mesh.Nodes{1}.node.ATTR.id=(1:size(V,1))'; %The node id's\nfebio_spec.Mesh.Nodes{1}.node.VAL=V; %The nodel coordinates\n\n% -> Elements\nn=1;\nfor q=1:1:numel(youngsModuli)\n logicMaterialNow=(elementMaterialID==q); \n partNameNow=['Part',num2str(q)];\n febio_spec.Mesh.Elements{q}.ATTR.name=partNameNow; %Name of this part\n febio_spec.Mesh.Elements{q}.ATTR.type='hex8'; %Element type of this set \n febio_spec.Mesh.Elements{q}.elem.ATTR.id=(n:1:(n-1+nnz(logicMaterialNow)))'; %Element id's\n febio_spec.Mesh.Elements{q}.elem.VAL=E(logicMaterialNow,:); \n n=n+nnz(logicMaterialNow);\nend\n\npartNameRigid='RigidPart';\nn=max(febio_spec.Mesh.Elements{end}.elem.ATTR.id);\nfebio_spec.Mesh.Elements{numel(youngsModuli)+1}.ATTR.name=partNameRigid; %Name of this part\nfebio_spec.Mesh.Elements{numel(youngsModuli)+1}.ATTR.type='quad4'; %Element type of this set\nfebio_spec.Mesh.Elements{numel(youngsModuli)+1}.ATTR.mat=numel(youngsModuli)+1; %material index for this set\nfebio_spec.Mesh.Elements{numel(youngsModuli)+1}.elem.ATTR.id=(n:1:(n-1+size(F_rigidBody,1)))'; %Element id's\nfebio_spec.Mesh.Elements{numel(youngsModuli)+1}.elem.VAL=F_rigidBody;\n\n% -> NodeSets\nnodeSetName1='bcSupportList';\nfebio_spec.Mesh.NodeSet{1}.ATTR.name=nodeSetName1;\nfebio_spec.Mesh.NodeSet{1}.node.ATTR.id=bcSupportList(:);\n\n%MeshDomains section\nfor q=1:1:numel(youngsModuli)\n partNameNow=['Part',num2str(q)];\n materialNameNow=['Material',num2str(q)];\n febio_spec.MeshDomains.SolidDomain{q}.ATTR.name=partNameNow;\n febio_spec.MeshDomains.SolidDomain{q}.ATTR.mat=materialNameNow;\nend\n\nfebio_spec.MeshDomains.ShellDomain.ATTR.name=partNameRigid;\nfebio_spec.MeshDomains.ShellDomain.ATTR.mat=materialNameRigid;\n\n% -> Surfaces\nfebio_spec.Mesh.Surface=[];\nfor q=1:1:numel(youngsModuli)-1 \n F_contact_now=Fb(logicTops(:,q),:);\n c=numel(febio_spec.Mesh.Surface)+1;\n febio_spec.Mesh.Surface{c}.ATTR.name=['contact_',num2str(c)];\n febio_spec.Mesh.Surface{c}.quad4.ATTR.id=(1:1:size(F_contact_now,1))';\n febio_spec.Mesh.Surface{c}.quad4.VAL=F_contact_now;\n \n F_contact_now=Fb(logicBottoms(:,q+1),:);\n c=numel(febio_spec.Mesh.Surface)+1;\n febio_spec.Mesh.Surface{c}.ATTR.name=['contact_',num2str(c)];\n febio_spec.Mesh.Surface{c}.quad4.ATTR.id=(1:1:size(F_contact_now,1))';\n febio_spec.Mesh.Surface{c}.quad4.VAL=F_contact_now; \nend\n\n% -> Surface pairs\nsurfaceIndices=reshape(1:(2*(numel(youngsModuli)-1)),2,3)'; %Indices for surface pairs\nfor q=1:1:numel(youngsModuli)-1\n febio_spec.Mesh.SurfacePair{q}.ATTR.name=['Contact_',num2str(q)];\n \n numElements1=size(febio_spec.Mesh.Surface{surfaceIndices(q,1)}.quad4.VAL,1);\n numElements2=size(febio_spec.Mesh.Surface{surfaceIndices(q,2)}.quad4.VAL,1);\n if numElements1>numElements2\n febio_spec.Mesh.SurfacePair{q}.primary = febio_spec.Mesh.Surface{surfaceIndices(q,1)}.ATTR.name;\n febio_spec.Mesh.SurfacePair{q}.secondary = febio_spec.Mesh.Surface{surfaceIndices(q,2)}.ATTR.name;\n else\n febio_spec.Mesh.SurfacePair{q}.primary = febio_spec.Mesh.Surface{surfaceIndices(q,2)}.ATTR.name;\n febio_spec.Mesh.SurfacePair{q}.secondary = febio_spec.Mesh.Surface{surfaceIndices(q,1)}.ATTR.name;\n end\nend\n\n%Boundary condition section \n% -> Fix boundary conditions\nfebio_spec.Boundary.bc{1}.ATTR.type='fix';\nfebio_spec.Boundary.bc{1}.ATTR.node_set=nodeSetName1;\nfebio_spec.Boundary.bc{1}.dofs='x,y,z';\n\n% %Rigid section \n% -> Prescribed rigid body boundary conditions\nfebio_spec.Rigid.rigid_constraint{1}.ATTR.name='RigidFix_1';\nfebio_spec.Rigid.rigid_constraint{1}.ATTR.type='fix';\nfebio_spec.Rigid.rigid_constraint{1}.rb=matIdRigid;\nfebio_spec.Rigid.rigid_constraint{1}.dofs='Rx,Ry,Ru,Rv';\n\nfebio_spec.Rigid.rigid_constraint{2}.ATTR.name='RigidPrescribe';\nfebio_spec.Rigid.rigid_constraint{2}.ATTR.type='prescribe';\nfebio_spec.Rigid.rigid_constraint{2}.rb=matIdRigid;\nfebio_spec.Rigid.rigid_constraint{2}.dof='Rz';\nfebio_spec.Rigid.rigid_constraint{2}.value.ATTR.lc=1;\nfebio_spec.Rigid.rigid_constraint{2}.value.VAL=prescribedDisplacement_Z;\nfebio_spec.Rigid.rigid_constraint{2}.relative=0;\n\nfebio_spec.Rigid.rigid_constraint{3}.ATTR.name='RigidPrescribe';\nfebio_spec.Rigid.rigid_constraint{3}.ATTR.type='prescribe';\nfebio_spec.Rigid.rigid_constraint{3}.rb=matIdRigid;\nfebio_spec.Rigid.rigid_constraint{3}.dof='Rw';\nfebio_spec.Rigid.rigid_constraint{3}.value.ATTR.lc=1;\nfebio_spec.Rigid.rigid_constraint{3}.value.VAL=prescribedRotation_Z;\nfebio_spec.Rigid.rigid_constraint{3}.relative=0;\n\n%Contact section\nfor q=1:1:numel(youngsModuli)-1\n febio_spec.Contact.contact{q}.ATTR.surface_pair=febio_spec.Mesh.SurfacePair{q}.ATTR.name;\n febio_spec.Contact.contact{q}.ATTR.type='sliding-elastic'; \n febio_spec.Contact.contact{q}.two_pass=1;\n febio_spec.Contact.contact{q}.laugon=1;\n febio_spec.Contact.contact{q}.tolerance=0.2;\n febio_spec.Contact.contact{q}.gaptol=0;\n febio_spec.Contact.contact{q}.minaug=1;\n febio_spec.Contact.contact{q}.maxaug=10;\n febio_spec.Contact.contact{q}.search_tol=0.01;\n febio_spec.Contact.contact{q}.search_radius=0.1*sqrt(sum((max(V,[],1)-min(V,[],1)).^2,2)); \n febio_spec.Contact.contact{q}.symmetric_stiffness=0;\n switch q\n case 1\n febio_spec.Contact.contact{q}.auto_penalty=1;\n febio_spec.Contact.contact{q}.penalty=5;\n febio_spec.Contact.contact{q}.fric_coeff=1;\n case 2\n febio_spec.Contact.contact{q}.auto_penalty=1;\n febio_spec.Contact.contact{q}.penalty=0.1;\n febio_spec.Contact.contact{q}.fric_coeff=0.08;\n case 3\n febio_spec.Contact.contact{q}.auto_penalty=1;\n febio_spec.Contact.contact{q}.penalty=0.1;\n febio_spec.Contact.contact{q}.fric_coeff=0.08;\n end\nend\n\n%LoadData section\n% -> load_controller\nfebio_spec.LoadData.load_controller{1}.ATTR.id=1;\nfebio_spec.LoadData.load_controller{1}.ATTR.type='loadcurve';\nfebio_spec.LoadData.load_controller{1}.interpolate='LINEAR';\nfebio_spec.LoadData.load_controller{1}.points.point.VAL=[0 0; 1 1];\n\n%Output section \n% -> log file\nfebio_spec.Output.logfile.ATTR.file=febioLogFileName;\nfebio_spec.Output.logfile.node_data{1}.ATTR.file=febioLogFileName_disp;\nfebio_spec.Output.logfile.node_data{1}.ATTR.data='ux;uy;uz';\nfebio_spec.Output.logfile.node_data{1}.ATTR.delim=',';\n\nfebio_spec.Output.logfile.element_data{1}.ATTR.file=febioLogFileName_strainEnergy;\nfebio_spec.Output.logfile.element_data{1}.ATTR.data='sed';\nfebio_spec.Output.logfile.element_data{1}.ATTR.delim=',';\n\n%% Quick viewing of the FEBio input file structure\n% The |febView| function can be used to view the xml structure in a MATLAB\n% figure window. \n\n%%\n% |febView(febio_spec); %Viewing the febio file|\n\n%% Exporting the FEBio input file\n% Exporting the febio_spec structure to an FEBio input file is done using\n% the |febioStruct2xml| function. \n\nfebioStruct2xml(febio_spec,febioFebFileName); %Exporting to file and domNode\n\n%% Running the FEBio analysis\n% To run the analysis defined by the created FEBio input file the\n% |runMonitorFEBio| function is used. The input for this function is a\n% structure defining job settings e.g. the FEBio input file name. The\n% optional output runFlag informs the user if the analysis was run\n% succesfully. \n\nfebioAnalysis.run_filename=febioFebFileName; %The input file name\nfebioAnalysis.run_logname=febioLogFileName; %The name for the log file\nfebioAnalysis.disp_on=1; %Display information on the command window\nfebioAnalysis.runMode='external';%'internal';\n\n[runFlag]=runMonitorFEBio(febioAnalysis);%START FEBio NOW!!!!!!!!\n\n%% Import FEBio results \n\nif runFlag==1 %i.e. a succesful run\n \n %% \n % Importing nodal displacements from a log file\n dataStruct=importFEBio_logfile(fullfile(savePath,febioLogFileName_disp),1,1);\n \n %Access data\n N_disp_mat=dataStruct.data; %Displacement\n timeVec=dataStruct.time; %Time\n \n %Create deformed coordinate set\n V_DEF=N_disp_mat+repmat(V,[1 1 size(N_disp_mat,3)]);\n \n %%\n % Importing element stress from a log file\n dataStruct=importFEBio_logfile(fullfile(savePath,febioLogFileName_strainEnergy),1,1);\n \n %Access data\n E_energy=dataStruct.data;\n \n %% \n % Plotting the simulated results using |anim8| to visualize and animate\n % deformations \n \n [CV]=faceToVertexMeasure(E,V,E_energy(:,:,end));\n \n % Create basic view and store graphics handle to initiate animation\n hf=cFigure; %Open figure \n gtitle([febioFebFileNamePart,': Press play to animate']);\n title('$\\sigma_{zz}$ [MPa]','Interpreter','Latex')\n hp=gpatch(Fb,V_DEF(:,:,end),CV,'k',1); %Add graphics object to animate\n hp.Marker='.';\n hp.MarkerSize=markerSize2;\n hp.FaceColor='interp';\n hp2=gpatch(F_rigidBody,V_DEF(:,:,end),'w','k',1); %A static graphics object\n \n axisGeom(gca,fontSize); \n colormap(gjet(250)); colorbar;\n caxis([min(E_energy(:)) max(E_energy(:))]/2); \n axis(axisLim(V_DEF)); %Set axis limits statically \n camlight headlight; \n \n % Set up animation features\n animStruct.Time=timeVec; %The time vector \n for qt=1:1:size(N_disp_mat,3) %Loop over time increments \n \n [CV]=faceToVertexMeasure(E,V,E_energy(:,:,qt));\n \n %Set entries in animation structure\n animStruct.Handles{qt}=[hp hp hp2]; %Handles of objects to animate\n animStruct.Props{qt}={'Vertices','CData','Vertices'}; %Properties of objects to animate\n animStruct.Set{qt}={V_DEF(:,:,qt),CV,V_DEF(:,:,qt)}; %Property values for to set in order to animate\n end \n anim8(hf,animStruct); %Initiate animation feature \n drawnow;\n \nend\n\n%% \n%\n% <>\n% \n% _*GIBBON*_ \n% \n% \n% _Kevin Mattheus Moerman_, \n \n%% \n% _*GIBBON footer text*_ \n% \n% License: \n% \n% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for\n% image segmentation, image-based modeling, meshing, and finite element\n% analysis.\n% \n% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n", "meta": {"author": "gibbonCode", "repo": "GIBBON", "sha": "8178520664a6148db939eaea87e75b3cba4f2b4f", "save_path": "github-repos/MATLAB/gibbonCode-GIBBON", "path": "github-repos/MATLAB/gibbonCode-GIBBON/GIBBON-8178520664a6148db939eaea87e75b3cba4f2b4f/docs/DEMO_febio_0029_contact_friction_benchmark_boxes.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.32424669288441366}} {"text": "function [p,priors]=create_parameters12(ncp_shocks,start_at_mode)\nif nargin<2\n start_at_mode=false;\n if nargin<1\n ncp_shocks=false;\n end\nend\n\np=struct();\n\np.beta = 0.99;\np.mu = 0.34;\np.gam = 2;\np.phi_d = 0.001;\np.delta = 0.025;\np.alpha = 0.36;\np.theta = 1.05;\np.omega = 0.10;\n\nif ncp_shocks\n p.mss_H = 0.9997;\n p.mss_F = 0.9997;\n p.m_hf_ss=1;\n p.zss_H = 1.0045;\nelse\n p.mss_H = 0.9;\n p.mss_F = 0.9;\n p.zss_H = 1.0042;\nend\n\np.zss_F = p.zss_H;\np.vss_H = 1.0004;\np.vss_F = p.vss_H;\np.z_hf_ss = 1;\np.v_hf_ss = 1;\np.gss_H = 0.20;\np.gss_F = 0.20;\np.rho_m_HF = 0;\np.rho_m_FH = 0;\np.rho_z_HF = 0;\np.rho_z_FH = 0;\np.rho_g_HF = 0;\np.rho_g_FH = 0;\np.rho_v_HF = 0;\np.rho_v_FH = 0;\n\npriors=struct();\n\nif start_at_mode\n priors.theta = {1.5709,0,5};\n \n priors.philtr = {17.113/100,0,3};\n priors.phiktr = {2.971/100,0,3};\n \n if ncp_shocks\n priors.kappamhtr = {0.0077294,0,3};\n priors.kappa_m_F = {8.0501e-06,0,3};\n end\n priors.kappazhtr = {0.002383,0,3};\n priors.kappa_z_F = {1.6159e-05,0,3};\n \n priors.kappavhtr = {0.017416,0,3};\n priors.kappa_v_F = {sqrt(eps),0,3};\n \n priors.rho_m_HH = {0.9671,0,1};\n priors.rho_m_FF = {0.9924,0,1};\n \n priors.rho_z_HH = {0.1752,0,1};\n priors.rho_z_FF = {0.35979,0,1};\n \n priors.rho_v_HH = {0.15793,0,1};\n priors.rho_v_FF = {0.9834,0,1};\n \n priors.rho_g_HH = {0.9695,0,1};\n priors.rho_g_FF = {0.9414,0,1};\n \n priors.sig_m_H = {0.017084,0,2};\n priors.sig_m_F = {0.0063409,0,2};\n \n priors.sig_z_H = {0.01176,0,2};\n priors.sig_z_F = {0.0085657,0,2};\n \n priors.sig_v_H = {0.01436,0,2};\n priors.sig_v_F = {0.00060192,0,2};\n \n priors.sig_g_H = {0.018465,0,2};\n priors.sig_g_F = {0.0098922,0,2};\nelse\n thetatr = 1.5709;\n priors.theta = {abs(thetatr),0,5};\n \n priors.philtr = {17.1310/100,0,3};\n priors.phiktr = {2.7056/100,0,3};\n \n if ncp_shocks\n kappamftr = 0.0010;\n priors.kappamhtr = {0.0077,0,3};\n priors.kappa_m_F = {abs(kappamftr),0,3};\n end\n\n priors.kappazhtr = {0.0018,0,3};\n kappazftr = 0.0010;\n priors.kappa_z_F = {abs(kappazftr),0,3};\n \n priors.kappavhtr = {0.0089,0,3};\n kappavftr = 0.0010;\n priors.kappa_v_F = {abs(kappavftr),0,3};\n \n rhomhhtr = sqrt(0.9671/(1-0.9671));\n priors.rho_m_HH = {rhomhhtr^2/(1+rhomhhtr^2),0,1};\n rhomfftr = sqrt(0.9924/(1-0.9924));\n priors.rho_m_FF = {rhomfftr^2/(1+rhomfftr^2),0,1};\n \n rhozhhtr = sqrt(0.1752/(1-0.1752));\n priors.rho_z_HH = {rhozhhtr^2/(1+rhozhhtr^2),0,1};\n rhozfftr = sqrt(0.3598/(1-0.3598));\n priors.rho_z_FF = {rhozfftr^2/(1+rhozfftr^2),0,1};\n \n rhovhhtr = sqrt(0.1581/(1-0.1581));\n priors.rho_v_HH = {rhovhhtr^2/(1+rhovhhtr^2),0,1};\n rhovfftr = sqrt(0.9834/(1-0.9834));\n priors.rho_v_FF = {rhovfftr^2/(1+rhovfftr^2),0,1};\n \n rhoghhtr = sqrt(0.9695/(1-0.9695));\n priors.rho_g_HH = {rhoghhtr^2/(1+rhoghhtr^2),0,1};\n rhogfftr = sqrt(0.9414/(1-0.9414));\n priors.rho_g_FF = {rhogfftr^2/(1+rhogfftr^2),0,1};\n \n sigmhtr = 0.01;\n priors.sig_m_H = {abs(sigmhtr),0,2};\n sigmftr = 0.01;\n priors.sig_m_F = {abs(sigmftr),0,2};\n \n sigzhtr = 0.01;\n priors.sig_z_H = {abs(sigzhtr),0,2};\n sigzftr = 0.01;\n priors.sig_z_F = {abs(sigzftr),0,2};\n \n sigvhtr = 0.01;\n priors.sig_v_H = {abs(sigvhtr),0,2};\n sigvftr = 0.01;\n priors.sig_v_F = {abs(sigvftr),0,2};\n \n sigghtr = 0.01;\n priors.sig_g_H = {abs(sigghtr),0,2};\n siggftr = 0.01;\n priors.sig_g_F = {abs(siggftr),0,2};\nend\n\n% add the initial conditions of the priors to the parameters\n%------------------------------------------------------------\nfields=fieldnames(priors);\nfor ip=1:numel(fields)\n name=fields{ip};\n p.(name)=priors.(name){1};\nend\n\nend", "meta": {"author": "jmaih", "repo": "RISE_toolbox", "sha": "1b2edfa27830c6d522f9d7d2335d33c3e4d84285", "save_path": "github-repos/MATLAB/jmaih-RISE_toolbox", "path": "github-repos/MATLAB/jmaih-RISE_toolbox/RISE_toolbox-1b2edfa27830c6d522f9d7d2335d33c3e4d84285/examples/VariousModels/PeterIreland/sgusea_JEEA2013/create_parameters12.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.3241265495139945}} {"text": "function MDP = DEMO_MDP_maze\n% Demo of mixed continuous and discrete state space modelling\n%__________________________________________________________________________\n%\n% This demonstration of active inference focuses on navigation and planning\n% in a fairly complicated maze. The idea is to demonstrate how epistemic\n% foraging and goal (target) directed behaviour are integrated in the\n% minimisation of expected free energy. In this illustration, and 8 x 8\n% maze is learned through novelty driven evidence accumulation - to learn\n% the likelihood mapping between hidden states (locations in the maze) and\n% outcomes (whether the current location is open or closed). This\n% accumulated experience is then used to plan a path from a start to an end\n% (target location) under a task set specified by prior preferences over\n% locations. These priors are based upon a simple diffusion (CF backwards\n% induction) heuristic that specifies subgoals. The subgoals (i.e.,\n% locations) contain the most paths from the target within the horizon of\n% the current policy.\n%\n% We will first illustrate the novelty driven epistemic foraging that\n% efficiently scans the maze to learn its structure. We then simulate\n% planning of (shortest path) trajectory to the target under the assumption\n% the maze has been previously learned. Finally, we consider exploration\n% under prior preferences to simulate behaviour when both epistemic and\n% goal directed imperatives are in play. The focus on this demo is on\n% behavioural and electrophysiological responses over moves.\n%\n% A key aspect of this formulation is the hierarchical decomposition of\n% goal directed behaviour into subgoals that are within the horizon of a\n% limited policy - here, to moves that correspond to a trial. The prior\n% preferences then contextualise each policy or trial to ensure that the\n% ultimate goal is achieved.\n%\n% Empirically, this sort of construction suggests the existence of Path\n% cells; namely, cells who report the initial location of any subsequence\n% and continue firing until the end of the local path. This is illustrated\n% by plotting simulated activity as a function of trajectories during \n% exploration.\n%\n% see also: spm_MPD_VB_X.m\n%__________________________________________________________________________\n% Copyright (C) 2005 Wellcome Trust Centre for Neuroimaging\n\n% Karl Friston\n% $Id: DEMO_MDP_maze.m 7766 2020-01-05 21:37:39Z karl $\n\n% set up and preliminaries: first level\n%--------------------------------------------------------------------------\nrng('default')\n\n% generative model at the sensory level (DEM): continuous states\n%==========================================================================\n% the generative model has two outcome modalities; namely, what (open\n% versus closed) and where (the current location in a maze). These outcomes\n% are generated from a single hidden factor (location), where the structure\n% of the maze is encoded in the likelihood of observation mapping (that can\n% be learned through experience). Allowable actions include for moves (up,\n% down, left, right) and staying at the current location. These induce five\n% transition matrices that play the role of empirical priors. Finally,\n% prior preferences are based upon allowable transitions (that are function\n% of learned accumulated likelihood), which are used to define attractive\n% locations within the horizon of two-move policies. These priors implement\n% a task set and are returned by a subfunction below: spm_maze_cost\n%--------------------------------------------------------------------------\nlabel.factor = {'where'};\nlabel.modality = {'what','where'};\nlabel.outcome{1} = {'open','closed'};\n\nMAZE = [...\n 1 1 1 1 1 1 1 1;\n 1 0 0 0 0 0 0 1;\n 1 1 1 0 1 1 0 1;\n 1 1 0 0 0 1 0 1;\n 1 1 0 1 0 0 0 1;\n 1 1 0 1 1 1 0 1;\n 1 0 0 0 0 0 0 1;\n 1 0 1 1 1 1 1 1];\nEND = sub2ind(size(MAZE),5,5); % goal or target location\nSTART = sub2ind(size(MAZE),8,2); % first or start location\n\n% prior beliefs about initial states: D \n%--------------------------------------------------------------------------\nD{1} = zeros(numel(MAZE),1);\nNs = numel(D{1});\n\n% probabilistic mapping from hidden states to outcomes: A\n%--------------------------------------------------------------------------\nA{1} = [1 - MAZE(:), MAZE(:)]'; % what\nA{2} = eye(Ns,Ns); % where\nNg = numel(A);\nfor g = 1:Ng\n No(g) = size(A{g},1);\nend\n\n% controlled transitions: B (up, down, left, right, stay)\n%--------------------------------------------------------------------------\nu = [1 0; -1 0; 0 1; 0 -1; 0 0]; % allowable actions\nnu = size(u,1); % number of actions\nB{1} = zeros(Ns,Ns,nu);\n[n,m] = size(MAZE);\nfor i = 1:n\n for j = 1:m\n \n % allowable transitions from state s to state ss\n %------------------------------------------------------------------\n s = sub2ind([n,m],i,j);\n for k = 1:nu\n try\n ss = sub2ind([n,m],i + u(k,1),j + u(k,2));\n B{1}(ss,s,k) = 1;\n catch\n B{1}(s, s,k) = 1;\n end\n end\n end\nend\n\n% allowable policies (2 moves): V\n%--------------------------------------------------------------------------\nV = [];\nfor i = 1:nu\n for j = 1:nu\n V(:,end + 1) = [i;j];\n end\nend\n\n% priors: (negative cost) C:\n%--------------------------------------------------------------------------\nfor g = 1:Ng\n C{g} = zeros(No(g),1);\nend\n\n% basic MDP structure\n%--------------------------------------------------------------------------\nmdp.V = V; % allowable policies\nmdp.A = A; % observation model or likelihood\nmdp.B = B; % transition probabilities\nmdp.C = C; % preferred outcomes\nmdp.D = D; % prior over initial states\n\nmdp.label = label;\nmdp = spm_MDP_check(mdp);\n\n\n% exploratory (32 trial) sequence (no experience or task set)\n%==========================================================================\n% These simulations use a subroutine (spm_maze_search) to perform recursive\n% variational inversions of the active inference scheme under different\n% levels of experience and prior preferences\n%--------------------------------------------------------------------------\nSDP = spm_maze_search(mdp,32,START,END,0,0);\n\n% show results - behavioural\n%--------------------------------------------------------------------------\nspm_figure('GetWin','Figure 1'); clf\nspm_maze_plot(SDP,END)\n\n% show results - electrophysiological\n%--------------------------------------------------------------------------\nspm_figure('GetWin','Figure 2'); clf\nspm_MDP_VB_LFP(SDP);\n\n% exploratory (8 trial) sequence (with experience and task set)\n%==========================================================================\nMDP = spm_maze_search(mdp,8,START,END,128,1);\n\n% show results in terms of path\n%--------------------------------------------------------------------------\nspm_figure('GetWin','Figure 3'); clf\nspm_maze_plot(MDP,END)\n\n% and implicit subgoals\n%--------------------------------------------------------------------------\nfor i = 1:8\n subplot(8,2,(i - 1)*2 + 2);\n c = spm_softmax(MDP(i).C{2}(:,1));\n imagesc(spm_unvec(c,MAZE))\n axis image off, title(sprintf('%s %i','Trial',i))\nend\n\n% evidence accumulation under task set\n%==========================================================================\nMDP = mdp;\nfor i = 1:4\n \n % return to start\n %----------------------------------------------------------------------\n MDP = spm_maze_search(MDP(end),8,START,END,0,1);\n \n % show results in terms of path\n %----------------------------------------------------------------------\n spm_figure('GetWin',sprintf('%s %i','Search',i)); clf\n spm_maze_plot(MDP,END)\n \n % and electrophysiological responses\n %----------------------------------------------------------------------\n spm_figure('GetWin',sprintf('%s %i','Responses',i)); clf\n spm_MDP_VB_game(MDP(1:8));\n subplot(6,1,3), set(gca,'YLim',[-1 1]/3);\n subplot(6,1,4), set(gca,'YLim',[0 1]);\n \nend\n\n% in silico psychophysical experiment\n%==========================================================================\n% Here, we return to the exploratory simulation above and probe each level\n% of experience by asking the subject to execute a path to target. The\n% behaviour is then assessed in terms of the latency with which the target\n% will go is required - and the number of mistakes or exploratory\n% excursions into closed locations.\n%--------------------------------------------------------------------------\nN = [];\nM = [];\nT = [];\nfor i = 1:2:numel(SDP)\n \n % execute path to target with increasing experience\n %----------------------------------------------------------------------\n MDP = spm_maze_search(SDP(i),8,START,END,0,1);\n \n % record behaviour\n %----------------------------------------------------------------------\n s = spm_cat({MDP.s}); s(3:3:end) = [];\n s = [s,END];\n N = [N,find(s == END,1)]; % latency\n M = [M,sum(MAZE(s))]; % mistakes\n T = [T,i/2]; % exposure to maze\n \nend\n\n% show results\n%--------------------------------------------------------------------------\nspm_figure('GetWin','Figure 4'); clf\nsubplot(2,1,1), bar([M;N]'), xlabel('Exposure (seconds)'), axis square \ntitle('Performance','FontSize',16),legend({'Mistakes','Latency'})\n\n% place and direction specific responses\n%==========================================================================\nspm_figure('GetWin','Figure 5'); clf\n\n% illustrate simulated responses (first eight subsequences)\n%--------------------------------------------------------------------------\nspm_MDP_VB_LFP(SDP(1:8))\n\n% extract simulated responses\n%--------------------------------------------------------------------------\n[u,v] = spm_MDP_VB_LFP(SDP); % responses\nE = kron(eye(32*3),pinv(ones(16,1))); % expectation matrix\nv = E*spm_cat(v); % firing rates (hidden states)\nu = E*spm_cat({SDP.un})'; % firing rates (policies)\ns = spm_cat({SDP.s})'; % location\n\n% Position\n%--------------------------------------------------------------------------\n[X,Y] = ndgrid(1:8,1:8);\nL = [X(:),Y(:)];\nX = L(s,:);\n\n% accumulate responses at each location\n%--------------------------------------------------------------------------\nPC = zeros(8,8,size(v,2));\nfor i = 1:size(v,1)\n for j = 1:size(v,2)\n PC(X(i,1),X(i,2),j) = PC(X(i,1),X(i,2),j) + v(i,j);\n end\nend\nQC = zeros(8,8,size(u,2));\nfor i = 1:size(u,1)\n for j = 1:size(u,2)\n QC(X(i,1),X(i,2),j) = QC(X(i,1),X(i,2),j) + u(i,j);\n end\nend\n\n% identify path and place cells that fire above threshold (U)\n%--------------------------------------------------------------------------\nU = .8;\njpath = [];\njplac = [];\nfor i = 1:64\n if sum(spm_vec(PC(:,:,i)) > U) > 2\n jpath(end + 1) = i;\n end\nend\nfor i = (1:64) + 128;\n if sum(spm_vec(PC(:,:,i)) > U) > 0\n jplac(end + 1) = i;\n end\nend\n\n% and plot as a function of trajectory in space\n%--------------------------------------------------------------------------\nx = spm_conv(X + randn(size(X))/8,2,0);\nfor i = 1:64\n col{i} = spm_softmax(randn(3,1));\nend\n\n% path cells\n%--------------------------------------------------------------------------\nsubplot(4,2,3)\nplot(x(:,2),x(:,1),'r:'), hold on\nfor i = 1:size(x,1)\n for j = 1:3:length(jpath)\n if v(i,jpath(j)) > .80\n plot(x(i,2),x(i,1),'.','MarkerSize',32,'Color',col{j})\n end\n end\nend\naxis([0 9 0 9]), axis ij square, hold off\ntitle('Path cell responses','fontsize',16)\n\n% please cells\n%--------------------------------------------------------------------------\nsubplot(4,2,4)\nplot(x(:,2),x(:,1),'r:'), hold on\nfor i = 1:size(x,1)\n for j = 1:3:length(jpath)\n if v(i,jplac(j)) > .80\n plot(x(i,2),x(i,1),'.','MarkerSize',32,'Color',col{j})\n end\n end\nend\naxis([0 9 0 9]), axis ij square, hold off\ntitle('Place cell responses','fontsize',16)\n\n\nreturn\n\n\n\nfunction MDP = spm_maze_search(mdp,N,START,END,alpha,beta)\n% FORMAT MDP = spm_maze_search(mdp,N,START,END,alpha,beta)\n% mdp - MDP structure\n% N - number of trials (i.e., policies: default 8)\n% START - index of intial state (default 1)\n% END - index of target state (default 1)\n% alpha - prior concentration parameter for likelihood (default 128)\n% beta - precision of prior preference (default 0)\n%the argument is\n% MDP - MDP structure array\n\n% preliminaries\n%--------------------------------------------------------------------------\ntry, N; catch, N = 8; end\ntry, START; catch, START = 1; end\ntry, END; catch, END = 1; end\ntry, alpha; catch, alpha = 128; end\ntry, beta; catch, beta = 0; end\n\n% initialise concentration parameters: a (if unspecified)\n%--------------------------------------------------------------------------\nif ~isfield(mdp,'a')\n mdp.a{1} = ones(size(mdp.A{1}))/8 + mdp.A{1}*alpha;\n mdp.a{2} = mdp.A{2}*128;\nend\nif ~isfield(mdp,'o')\n mdp.o = [];\nend\nif ~isfield(mdp,'u')\n mdp.u = [];\nend\nmdp.s = START;\n\n% Evaluate a sequence of moves - recomputing prior preferences at each move\n%==========================================================================\nfor i = 1:N\n \n % Evaluate preferred states (subgoals) on the basis of current beliefs\n %----------------------------------------------------------------------\n mdp.C{2} = spm_maze_cost(mdp,END)*beta;\n \n % proceed with subsequent trial\n %----------------------------------------------------------------------\n MDP(i) = spm_MDP_VB_X(mdp);\n mdp = MDP(i);\n mdp.s = mdp.s(:,end);\n mdp.D{1} = MDP(i).X{1}(:,end);\n mdp.o = [];\n mdp.u = [];\n \nend\n\nreturn\n\n\nfunction C = spm_maze_cost(MDP,END)\n% Evaluate subgoals using graph Laplacian\n%==========================================================================\nSTART = MDP.s(1);\nif isfield(MDP,'a')\n Q = MDP.a{1};\nelse\n Q = MDP.A{1};\nend\nQ = Q/diag(sum(Q));\nQ = Q(1,:); % open states\nP = diag(Q)*any(MDP.B{1},3); % allowable transitions\nns = length(Q); % number of states\nX = zeros(ns,1);X(START) = 1; % initial state\nY = zeros(ns,1);Y(END) = 1; % target state\n\n\n% Preclude transitions to closed states and evaluate graph Laplacian\n%--------------------------------------------------------------------------\nP = P - diag(diag(P));\nP = P - diag(sum(P));\nP = expm(P);\n\n% evaluate (negative) cost as a path integral conjunctions\n%--------------------------------------------------------------------------\nfor t = 1:size(MDP.V,1)\n X = P*X;\nend\nX = X > exp(-3);\nC = log(X.*(P*Y) + exp(-32));\n\nreturn\n\n\n\nfunction spm_maze_plot(MDP,END)\n% illustrate search graphically\n%--------------------------------------------------------------------------\nA = spm_vec(MDP(1).A{1}(1,:));\nns = numel(A);\nni = sqrt(ns);\nA = reshape(A,ni,ni);\nsubplot(2,2,1), imagesc(A), axis image\ntitle('Scanpath','fontsize',16);\n\n% Cycle of the trials\n%--------------------------------------------------------------------------\nh = [];\nMS = {};\nMC = {};\nfor p = 1:numel(MDP)\n \n % current beliefs and preferences: A likelihood\n %----------------------------------------------------------------------\n if isfield(MDP,'a')\n Q = MDP(p).a{1};\n else\n Q = MDP(p).A{1};\n end\n Q = Q/diag(sum(Q));\n Q = Q(1,:);\n a = reshape(Q(:),ni,ni);\n subplot(2,2,2), imagesc(a), axis image\n title('Likelihood','fontsize',16);\n \n % current beliefs and preferences: B transitions\n %----------------------------------------------------------------------\n try\n b = diag(Q)*any(MDP(p).B{1},3);\n catch\n b = diag(Q)*any(MDP(p).B{1},3);\n end\n subplot(2,2,4), imagesc(-b), axis image\n title('Allowable transitions','fontsize',16);\n \n % current beliefs and preferences: C preferences\n %----------------------------------------------------------------------\n C = MDP(p).C{2}(:,1);\n C = spm_softmax(C);\n C = reshape(C,ni,ni);\n subplot(2,2,3), imagesc(C), axis image\n title('Preferences','fontsize',16);\n try\n [i,j] = ind2sub([ni,ni],MDP(p).s(1)); hold on\n plot(j,i,'.','MarkerSize',32,'Color','g');\n [i,j] = ind2sub([ni,ni],END);\n plot(j,i,'.','MarkerSize',32,'Color','r'); hold off\n end\n \n % cycle over short-term searches\n %----------------------------------------------------------------------\n subplot(2,2,1),hold on\n s = MDP(p).s;\n for t = 1:numel(s)\n \n % location\n %------------------------------------------------------------------\n [i,j] = ind2sub([ni,ni],s(t));\n h(end + 1) = plot(j,i,'.','MarkerSize',32,'Color','r');\n try\n set(h(end - 1),'Color','m','MarkerSize',16);\n j = [get(h(end - 1),'Xdata'), get(h(end),'Xdata')];\n i = [get(h(end - 1),'Ydata'), get(h(end),'Ydata')];\n plot(j,i,':r');\n end\n \n % save\n %------------------------------------------------------------------\n if numel(MS)\n MS(end + 1) = getframe(gca);\n else\n MS = getframe(gca);\n end\n \n end\n \n % save\n %----------------------------------------------------------------------\n subplot(2,2,3)\n if numel(MC)\n MC(end + 1) = getframe(gca);\n else\n MC = getframe(gca);\n end\n \nend\n\n% save movie\n%--------------------------------------------------------------------------\nsubplot(2,2,1)\nxlabel('click axis for movie')\nset(gca,'Userdata',{MS,16})\nset(gca,'ButtonDownFcn','spm_DEM_ButtonDownFcn')\n\nsubplot(2,2,3)\nxlabel('click axis for movie')\nset(gca,'Userdata',{MC,16})\nset(gca,'ButtonDownFcn','spm_DEM_ButtonDownFcn')\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/toolbox/DEM/DEMO_MDP_maze.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6584175139669997, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.3240652887253384}} {"text": "function volumeRendering(command)\n% Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team.\n% \n% This file is part of The Computational Environment for Radiotherapy Research (CERR).\n% \n% CERR development has been led by: Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy.\n% \n% CERR has been financially supported by the US National Institutes of Health under multiple grants.\n% \n% CERR is distributed under the terms of the Lesser GNU Public License. \n% \n% This version of CERR is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% CERR is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;\n% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n% See the GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with CERR. If not, see .\n\nglobal planC stateS;\nindexS = planC{end};\n\n[origin, spacing, center] = getScanOriginSpacing(planC{indexS.scan}(stateS.scanSet));\n\nscanData = planC{indexS.scan}(stateS.scanSet).scanArray;\n%scanData = planC{indexS.dose}(stateS.doseSet).doseArray;\n% spacing = [1 1 3];\n\nswitch upper(command)\n \n case 'MIP'\n colormap = [];\n% scanData=GPReduce2(scanData,2,0);\n sampleRatio = 2;\n scanData = scanData(1:sampleRatio:end, 1:sampleRatio:end, 1:sampleRatio:end);\n Render3D_MIP(uint16(permute(scanData,[3,1,2])),colormap', 1, [spacing(3),spacing(1),spacing(2)]*10, 1);\n \n case 'MIP2'\n colormap = [];\n cData3M = scanDoseFusion();\n cData3M = permute(cData3M, [4,1,2,3]);\n [m,n,o,p] = size(cData3M);\n cData3M = reshape(cData3M, [n,o,p*m]);\n alphaRatio = 30;\n Render3D_MIP(uint16(cData3M),colormap', 2, spacing*10, alphaRatio);\n \n case 'VR1'\n% colormap = [ 0.0 0.0 0.0 0.0 0.0; ...\n% 200.0 0 0 0.8 0.02; ...\n% 400.0 0.0 1.0 0.0 .8; ...\n% 600.0 1.0 1.0 0.0 .6; ...\n% 800.0 1.0 0.0 0.0 .7; ...\n% 1000.0 0.0 1.0 1.0 1; ]; \n\n [strVol, colormap] = generateStructVolume();\n sagOn = 0;\n axOn = 1; \n corOn = 1;\n skinOn = 0;\n boneOn = 1;\n sagPos = 130; \n axPos = 30;\n corPos = 100;\n tRange1 = 2500;\n tRange2 = 1500;\n tRange3 = 1500;\n skinAlpha = 0.3;\n boneAlpha = 0.8;\n Render3D_S(uint16(strVol(:,:,20:end)),colormap', 2, spacing, ...\n sagOn, axOn, corOn, skinOn, boneOn, sagPos, axPos, corPos, tRange1, tRange2, tRange3, skinAlpha, boneAlpha);\n \n case 'VR2'\n colormap = [ 0 1 1 1 .0 ...\n 255 1 1 1 .0 ...\n 800 .9 .9 .9 .1 ...\n 1000 .9 .9 .3 .1 ...\n 1010 1 1 1 1 ...\n 1020 1 1 1 1 ...\n 1030 1 1 1 1 ...\n 1040 1 1 1 1 ...\n 1050 .6 .0 .6 .7 ...\n 1060 .6 .0 .6 .7 ...\n 1070 .6 .0 .6 .7 ...\n 1080 .0 .9 .0 1 ...\n 1090 .0 .6 .0 1 ...\n 1100 .0 .3 .0 1 ...\n 1150 .0 .8 .0 .1 ...\n 1200 .0 .4 .0 .9 ...\n 1500 .0 .6 .0 .9 ...\n 2000 .0 .8 .8 .9 ...\n 4000 1 1 1 1.0 ];\n \n% scanData = smooth3(scanData, 'gaussian');\n Render3D_V(uint16(scanData(:,:,40:end)),colormap', 2, spacing);\n \nend ", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/CERR_core/3D/volumeRendering.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.668880247169804, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.3239922704953198}} {"text": "classdef comp2periodz < ZmapHGridFunction\n % COMP2PERIODZ compares seismicity rates for two time periods\n % The differences are as z- and beta-values and as percent change.\n \n properties\n periodA_start datetime % start time for period 1\n periodA_end datetime % end time for period 1\n periodB_start datetime % start time for period 2\n periodB_end datetime % end time for period 2\n binsize duration = ZmapGlobal.Data.bin_dur;\n end\n \n properties(Constant)\n PlotTag = 'comp2periodz';\n ReturnDetails = cell2table({ ... VariableNames, VariableDescriptions, VariableUnits\n ...\n ... % these are returned by the calculation function\n 'z_value', 'z-value', '';... #1 'valueMap'\n 'pct_change', 'percent change', 'pct';... #2 'per'\n 'beta_value', 'Beta value map', '';... #3 'beta_map'\n 'Number_of_Events_1', 'Number of events in first period', '';... #4\n 'Number_of_Events_2', 'Number of events in second period', '';... #5\n ...\n }, 'VariableNames', {'Names','Descriptions','Units'})\n \n CalcFields={...\n 'z_value', 'pct_change', 'beta_value',...\n 'Number_of_Events_1', 'Number_of_Events_2'}\n \n ParameterableProperties = [\"periodA_start\" \"periodA_end\" \"periodB_start\" \"periodB_end\" \"binsize\"];\n \n References=\"\";\n end\n \n methods\n function obj=comp2periodz(zap, varargin)\n % COMP2PERIODZ compares seismicity rates for two time periods.\n % The differences are as z- and beta-values and as percent change.\n % Stefan Wiemer 1/95\n % Rev. R.Z. 4/2001\n \n obj@ZmapHGridFunction(zap, 'z_value');\n report_this_filefun();\n \n t0b = min(obj.RawCatalog.Date);\n teb = max(obj.RawCatalog.Date);\n obj.periodA_start = t0b;\n obj.periodB_end = teb;\n obj.periodA_end = t0b + (teb-t0b)/2;\n obj.periodB_start = obj.periodA_end+minutes(0.01);\n \n obj.parseParameters(varargin);\n \n obj.StartProcess();\n \n end\n \n function InteractiveSetup(obj)\n \n % get two time periods, along with grid and event parameters\n zdlg=ZmapDialog();\n zdlg.AddHeader('Please define two time periods to compare');\n zdlg.AddEdit('periodA_start','start period 1', obj.periodA_start,'start time for period 1');\n zdlg.AddEdit('periodA_end', 'end period 1', obj.periodA_end,'end time for period 1');\n zdlg.AddEdit('periodB_start','start period 2', obj.periodB_start,'start time for period 2');\n zdlg.AddEdit('periodB_end', 'end period 2', obj.periodB_end,'end time for period 2');\n zdlg.AddDurationEdit('binsize','Bin Size', obj.binsize,'number of days in each bin',@days);\n obj.AddDialogOption(zdlg,'EventSelector');\n zdlg.Create('Name', 'Please choose rate change estimation option','WriteToObj',obj,'OkFcn',@obj.doIt);\n end\n \n function results=Calculate(obj)\n \n assert(obj.periodA_start < obj.periodA_end,'Period 1 starts before it ends');\n assert(obj.periodB_start < obj.periodB_end,'Period 2 starts before it ends');\n \n % make grid, calculate start- endtime etc. ...\n \n lt = (obj.RawCatalog.Date >= obj.periodA_start & obj.RawCatalog.Date < obj.periodA_end) ...\n | (obj.RawCatalog.Date >= obj.periodB_start & obj.RawCatalog.Date <= obj.periodB_end);\n obj.RawCatalog = obj.RawCatalog.subset(lt);\n \n \n interval1_bins = obj.periodA_start : obj.binsize : obj.periodA_end; % starts\n interval2_bins = obj.periodB_start : obj.binsize : obj.periodB_end; % starts\n interval1_edges = [interval1_bins, interval1_bins(end)+obj.binsize];\n interval2_edges = [interval2_bins, interval2_bins(end)+obj.binsize];\n \n \n obj.gridCalculations(@calculation_function);\n \n obj.Result.period1.dateRange=[obj.periodA_start obj.periodA_end];\n obj.Result.period2.dateRange=[obj.periodB_start obj.periodB_end];\n \n if nargout\n results=obj.Result.values;\n end\n % save data\n \n % plot the results\n % old and valueMap (initially ) is the z-value matrix\n \n \n %det = 'ast';\n %ZG.shading_style = 'interp';\n % View the b-value map: view_ratecomp.m\n % which could create a topography overlay ala dramap_z.m\n %\n %\n \n function out=calculation_function(catalog)\n % calulate values at a single point\n % calculate distance from center point and sort wrt distance\n \n idx_back = catalog.Date >= obj.periodA_start & catalog.Date < obj.periodA_end ;\n [cumu1, ~] = histcounts(catalog.Date(idx_back),interval1_edges);\n \n idx_after = catalog.Date >= obj.periodB_start & catalog.Date <= obj.periodB_end ;\n [cumu2, ~] = histcounts(catalog.Date(idx_after),interval2_edges);\n \n mean1 = mean(cumu1); % mean seismicity rate in first interval\n mean2 = mean(cumu2); % mean seismicity rate in second interval\n sum1 = sum(cumu1); % number of earthquakes in the first interval\n sum2 = sum(cumu2); % number of earthquakes in the second interval\n var1 = cov(cumu1); % variance of cumu1\n var2 = cov(cumu2); % variance of cumu2\n % remark (db): cov and var calculate the same value when applied to a vector\n ncu1 = length(interval1_bins); % number of bins in first interval\n ncu2 = length(interval2_bins); % number of bins in second interval\n \n % compute the z value \"as\":\n as = (mean1 - mean2)/ sqrt(var1/ncu1 +var2/ncu2);\n \n % calculate the percentage\n per = -((mean1-mean2)./mean1)*100;\n \n % beta nach reasenberg & simpson 1992, time of second interval normalised by time of first interval\n bet = (sum2-sum1*ncu2/ncu1)/sqrt(sum1*(ncu2/ncu1));\n \n out = [as per bet sum1 sum2];\n \n end\n end\n function ModifyGlobals(obj)\n obj.ZG.bvg = obj.Result.values;\n end\n end %methods\n \n methods(Static)\n function h = AddMenuItem(parent, zapFcn, varargin)\n % create a menu item\n label = 'Compare two periods (z, beta, probabilty)';\n h = uimenu(parent, 'Label', label,...\n 'MenuSelectedFcn', @(~,~)XYfun.comp2periodz(zapFcn()),...\n varargin{:});\n end\n end % static methods\nend % classdef\n\n", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/src/+XYfun/comp2periodz.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.668880247169804, "lm_q2_score": 0.4843800842769844, "lm_q1q2_score": 0.3239922704953198}} {"text": "%%% void show_results(matrix,matrix,matrix,matrix,int,int,int)\n% I - Input sequence\n% L - Low-rank sequence\n% S - Sparse sequence\n% O - Outliers sequence\n% nFrame - Number of frames\n% vidHeight - Video height\n% vidWidth - Video width\n%\nfunction show_results(I,L,S,O,nFrame,vidHeight,vidWidth)\n warning('off','all');\n clf;\n for i = 1:nFrame\n Input = reshape(I(:,i),vidHeight,vidWidth);\n %Input = uint8(Input);\n \n if(size(L) == size(I))\n LowRank = reshape(L(:,i),vidHeight,vidWidth);\n %LowRank1 = reshape(L(:,i),vidHeight,vidWidth);\n %LowRank = mat2gray(LowRank1);\n %LowRank = im2uint8(LowRank);\n else\n LowRank = uint8(zeros(size(Input)));\n end\n\n if(size(S) == size(I))\n Sparse = reshape(S(:,i),vidHeight,vidWidth);\n %Sparse1 = reshape(S(:,i),vidHeight,vidWidth);\n %Sparse = mat2gray(Sparse1);\n %Sparse = im2uint8(Sparse);\n else\n Sparse = uint8(zeros(size(Input)));\n end\n\n if(~isempty(O))\n Outlier = reshape(O(:,i),vidHeight,vidWidth);\n %Outlier1 = reshape(O(:,i),vidHeight,vidWidth);\n %Outlier = mat2gray(Outlier1);\n %Outlier = im2uint8(Outlier);\n %Outlier = medfilt2(Outlier, [5 5]);\n else\n Outlier = uint8(zeros(size(Input)));\n end\n\n subplot(2,3,1), imshow(Input,[]), title('Input (I)');\n subplot(2,3,2), imshow(LowRank,[]), title('Low Rank (L)');\n subplot(2,3,3), imshow(Sparse,[]), title('Sparse (S)');\n subplot(2,3,4), imshow(Outlier,[]), title('Outliers (O)');\n subplot(2,3,5), imshow(medfilt2(Outlier, [5 5]),[]), title('Filtered Outliers');\n %disp(i);\n pause(0.01);\n end\n warning('on','all');\nend\n\n", "meta": {"author": "andrewssobral", "repo": "lrslibrary", "sha": "06d457349cb5f1fc56a583cd61af9f1d5150e3a1", "save_path": "github-repos/MATLAB/andrewssobral-lrslibrary", "path": "github-repos/MATLAB/andrewssobral-lrslibrary/lrslibrary-06d457349cb5f1fc56a583cd61af9f1d5150e3a1/utils/show_results.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.32378165597412156}} {"text": "% Simulating Transducer Field Patterns Example\n%\n% This example demonstrates the use of k-Wave to compute the field pattern\n% generated by a curved single element transducer in two dimensions. It\n% builds on the Monopole Point Source In A Homogeneous Propagation Medium\n% Example.\n%\n% author: Bradley Treeby\n% date: 10th December 2009\n% last update: 24th August 2014\n% \n% This function is part of the k-Wave Toolbox (http://www.k-wave.org)\n% Copyright (C) 2009-2014 Bradley Treeby and Ben Cox\n\n% This file is part of k-Wave. k-Wave is free software: you can\n% redistribute it and/or modify it under the terms of the GNU Lesser\n% General Public License as published by the Free Software Foundation,\n% either version 3 of the License, or (at your option) any later version.\n% \n% k-Wave is distributed in the hope that it will be useful, but WITHOUT ANY\n% WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n% FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for\n% more details. \n% \n% You should have received a copy of the GNU Lesser General Public License\n% along with k-Wave. If not, see . \n\nclear all;\n\n% =========================================================================\n% SIMULATION\n% =========================================================================\n\n% create the computational grid\nNx = 216; % number of grid points in the x (row) direction\nNy = 216; % number of grid points in the y (column) direction\ndx = 50e-3/Nx; \t% grid point spacing in the x direction [m]\ndy = dx; % grid point spacing in the y direction [m]\nkgrid = makeGrid(Nx, dx, Ny, dy);\n\n% define the properties of the propagation medium\nmedium.sound_speed = 1500; % [m/s]\nmedium.alpha_power = 1.5; % [dB/(MHz^y cm)]\nmedium.alpha_coeff = 0.75; % [dB/(MHz^y cm)]\n\n% create the time array\n[kgrid.t_array, dt] = makeTime(kgrid, medium.sound_speed);\n\n% define a curved transducer element\nsource.p_mask = makeCircle(Nx, Ny, 61, 61, 60, pi/2);\n\n% define a time varying sinusoidal source\nsource_freq = 0.25e6; % [Hz]\nsource_mag = 0.5; % [Pa]\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% create a display mask to display the transducer\ndisplay_mask = source.p_mask;\n\n% create a sensor mask covering the entire computational domain using the\n% opposing corners of a rectangle\nsensor.mask = [1, 1, Nx, Ny].';\n\n% set the record mode capture the final wave-field and the statistics at\n% each sensor point \nsensor.record = {'p_final', 'p_max', 'p_rms'};\n\n% assign the input options\ninput_args = {'DisplayMask', display_mask, 'PMLInside', false, 'PlotPML', false};\n\n% run the simulation\nsensor_data = kspaceFirstOrder2D(kgrid, medium, source, sensor, input_args{:});\n\n% =========================================================================\n% VISUALISATION\n% =========================================================================\n\n% add the source mask onto the recorded wave-field\nsensor_data.p_final(source.p_mask ~= 0) = 1;\nsensor_data.p_max(source.p_mask ~= 0) = 1;\nsensor_data.p_rms(source.p_mask ~= 0) = 1;\n\n% plot the final wave-field\nfigure;\nsubplot(1, 3, 1), imagesc(kgrid.y_vec*1e3, kgrid.x_vec*1e3, sensor_data.p_final, [-1 1]);\ncolormap(getColorMap);\nylabel('x-position [mm]');\nxlabel('y-position [mm]');\naxis image;\ntitle('Final Wave Field');\n\n% plot the maximum recorded pressure\nsubplot(1, 3, 2), imagesc(kgrid.y_vec*1e3, kgrid.x_vec*1e3, sensor_data.p_max, [-1 1]);\ncolormap(getColorMap);\nylabel('x-position [mm]');\nxlabel('y-position [mm]');\naxis image;\ntitle('Maximum Pressure');\n\n% plot the rms recorded pressure\nsubplot(1, 3, 3), imagesc(kgrid.y_vec*1e3, kgrid.x_vec*1e3, sensor_data.p_rms, [-1 1]);\ncolormap(getColorMap);\nylabel('x-position [mm]');\nxlabel('y-position [mm]');\naxis image;\ntitle('RMS Pressure');\nscaleFig(2, 1);", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/K-wave/k-Wave/examples/example_tvsp_transducer_field_patterns.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6513548511303338, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.32313312244170794}} {"text": "function [afresults, AfAnalysisWindows, AFfile] = PerformAFdetection(subjectID,trr,rr,sqi,HRVparams) \n% PerformAFdetection(subjectID,trr,rr,HRVparams) \n%\n%\tOVERVIEW:\n% Perform Atrial Fibrillation (AF) detection \n%\n% INPUT:\n% subjectID : string containing the identifier of the subject to be analyze \n% trr : (seconds)a single row of time of the rr interval \n% data \n% rr : (seconds) a single row of peak to peak interval\n% data \n% sqi : Signal Quality Index; Requires a matrix with\n% at least two columns. Column 1 should be timestamps \n% should be timestamps of each sqi measure, and Column 2 \n% should be SQI on a scale from 0 to 1.\n% HRVparam : struct of settings for hrv_toolbox analysis\n%\n% OUTPUT:\n% afresults : a single row containing a flag (1) when AF is\n% dettected in a window and 0 if no AF \n%\n% DEPENDENCIES & LIBRARIES:\n% PhysioNet Cardiovascular Signal Toolbox\n% https://github.com/cliffordlab/PhysioNet-Cardiovascular-Signal-Toolbox\n%\n% REFERENCE: \n% Vest et al. \"An Open Source Benchmarked HRV Toolbox for Cardiovascular \n% Waveform and Interval Analysis\" Physiological Measurement (In Press), 2018. \n%\n%\tREPO: \n% https://github.com/cliffordlab/PhysioNet-Cardiovascular-Signal-Toolbox\n% ORIGINAL SOURCE AND AUTHORS: \n% Written by Giulia Da Poian (giulia.dap@gmail.com) on Sep 6, 2017.\n% Dependent scripts written by various authors \n% (see functions for details) \n%\tCOPYRIGHT (C) 2018 \n% LICENSE: \n% This software is offered freely and without warranty under \n% the GNU (v3 or later) public license. See license file for\n% more information\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \n% Modified on 02.14.2018 to include SQI check before evaluating AF; if a\n% windows contains low SQI signal do not compute AF and mark the window\n% as NaN\n\n\nif isempty(sqi) \n sqi(:,1) = trr;\n sqi(:,2) = ones(length(trr),1);\nend\n\n% 1. Calculate AF Features\nAfAnalysisWindows = CreateWindowRRintervals(trr,rr,HRVparams,'af');\nNNsamps = rr .* HRVparams.Fs;\n\nAFtest = nan(length(AfAnalysisWindows),1);\n\nfor idx = 1:length(AfAnalysisWindows)\n tstart = AfAnalysisWindows(idx);\n \n if ~isnan(tstart) \n \n idxInWin = find(trr >= tstart & trr< tstart + HRVparams.af.windowlength);\n \n % Added by Giulia: exclude from the Analysis low quality\n % segments (SQI< SQI_threshold)\n sqiWin = sqi(sqi(:,1) >= tstart & sqi(:,1) < tstart + HRVparams.af.windowlength,2);\n LowQualityIdxs = find(sqiWin < HRVparams.sqi.LowQualityThreshold); \n \n % If enough data has an adequate SQI, perform the calculations\n cond1 = (numel(LowQualityIdxs)/length(sqiWin)) < HRVparams.RejectionThreshold; \n % RR interval time series must be > 12 ans <60 to extract feautures\n cond2 = (length(NNsamps(idxInWin)) > 12 && length(NNsamps(idxInWin)) < 60);\n \n if (cond1 && cond2)\n features_af = AF_features(NNsamps(idxInWin),HRVparams.Fs);\n AFtest(idx) = SVM_AFdetection_withoutTrainingModel(features_af,1); \n end\n end \nend\n\n\n% 2. Export AF Data as CSV File\n\nafresults = AFtest(:);\nafcol_titles = {'AFtest'};\n\noutputType = 'AF';\nAFfile = SaveHRVoutput(subjectID,AfAnalysisWindows,afresults, ...\n afcol_titles, outputType, HRVparams, trr, rr);\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/PerformAFdetection.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.32274516616268606}} {"text": "function AAM = build_model_2d_from_files(directory, varargin)\n% AAM = build_model_2d_from_files(directory)\n% AAM = build_model_2d_from_files(directory, 'triangulation', triangulation)\n%\n% FIXME: Mostly a cut/paste from build_model_2d, but this\n% method was needed to avoid out-of-memory issues when dealing with large training\n% sets.\n%\n% Builds an Active Appearance Model using shape and appearance data retrieved from\n% the given directory.\n% Based on the 'Active Appearance Models Revisited' paper by Iain Matthews and Simon Baker.\n%\n% PARAMETERS\n%\n% directory Path to a directory containing shape and appearance data in the appropriate format.\n% See the examples to see what this format is, or use one of the provided datasets.\n%\n% OPTIONAL PROPERTIES\n%\n% 'triangulation' A matrix property providing a triangular mesh over the\n% shape (in the same format as the one returned by delaunay).\n% If not provided, a triangulation will be determined using\n% delaunay on the mean shape.\n%\n%\n% RETURN VALUE\n%\n% AAM is a structure with the following fields:\n%\n% \ts0 The mean shape as a column vector [i1 i2 i3 ... j1 j2 j3 ...]'.\n%\n% s The matrix of base shapes with each shape stored on a column vector\n% with the same structure as s0\n%\n% s_star The basis for the global normalizing transform. They are four column\n% vectors whose linear combination allow for translation, scale and\n% rotation of the base shape\n%\n% shape_eiv The eigenvalues associated to each shape principal\n% component\n%\n% warp_map A modelh-by-modelw lookup table for determining to which\n% triangle warp_map(i,j) the pixel (i,j) belongs. If 0, the\n% pixel is outside the mean shape\n%\n% shape_mesh The triangles indexed by warp_map. It is a Tx3 matrix\n% containing indices to vertices in the shape. Look at\n% the delaunay function for further information\n%\n% alpha_coords An image containing the alpha barycentric coordinate\n% for pixel (i,j) wrt of the triangle given by\n% shape_mesh(warp_map(i,j),:). Value is undefined if\n% warp_map(i,j) is 0\n%\n% beta_coords An image containing the beta barycentric coordinate\n% for pixel (i,j) wrt of the triangle given by\n% shape_mesh(warp_map(i,j),:). Value is undefined if\n% warp_map(i,j) is 0\n%\n% adj_list Array of N cells containing indices to the triangles sharing\n% a given vertex. Such that for the k-th cell, the list will\n% contain the indices to the triangles in shape_mesh sharing\n% the k-th vertex.\n%\n% A0 Mean appearance as a column vector, sorted firstly by color\n% component, then j coordinate and finally i coordinate\n% Example:\n% X1 = [ 1 2; 3 4];\n% X2 = [ 5 6; 7 8];\n% X3 = [ 9 10; 11 12];\n% X(:,:,1)=X1;\n% X(:,:,2)=X2;\n% X(:,:,3)=X3;\n% reshape(X,[],1) =>\n% _________\n% 1 j==1\n% 3 _____ C1\n% 2 j==2\n% 4 _________\n% 5 j==1\n% 7 _____ C2\n% 6 j==2\n% 8 _________\n% 9 j==1\n% 11 _____ C3\n% 10 j==2\n% 12 _________\n%\n% A The matrix of base appearances, with each appearance stored on\n% the colomuns in the same manner as A0\n%\n% app_eiv The eigenvalues associated to each appearance principal\n% component\n%\n% dA0 The gradient of the mean appearance stored such that for pixel (i,j),\n% dA0(i,j,c,1) gives the i direction of the gradient for color c\n% and dA0(i,j,c,2) gives the j direction of the gradient for color c\n%\n% dW_dp Jacobian of the warp with respect to the shape parameters p\n%\n% dN_dq Jacobian of the global normalizing warp with respect of the\n% global transform parameters q\n%\n% SD Steepest descent images. They are stored as row vectors (of the same length\n% as A0). The first 4 images are associated with the q\n% paramenters, the other are associated with the p parameters\n%\n% H The hessian, it's a square NxN matrix where N is the number of steepest\n% descent images (or, equivalently, the sum of the number of p and\n% q parameters)\n%\n% invH Inverse hessian, it's a square NxN matrix where N is the number of steepest\n% descent images (or, equivalently, the sum of the number of p and\n% q parameters)\n%\n% R Simply the product between the inverse hessian and the steepest descent images,\n% invH * SD. Encodes the linear relationship between the error image and the incremental\n% parameters.\n%\n% Author: Luca Vezzaro (elvezzaro@gmail.com)\n\n\tshape_triangles = zeros(0, 3, 'uint32');\n\n\ti = 1;\n\twhile i < numel(varargin)\n\t\tif strcmp(varargin{i}, 'triangulation')\n\t\t\t% Be sure the triangle indices are unsigned integers.\n\t\t\tshape_triangles = uint32(varargin{i+1});\n\t\telse\n\t\t\terror(sprintf('Unsupported property: %s.', varargin{i}));\n\t\tend\n\n\t\ti = i + 2;\n\tend\n\n\ttic;\n\n\tlandmark_files = dir(sprintf('%s/*.mat', directory));\n\tdisp 'Number of shapes:'\n\t% size of training set\n\tns = numel(landmark_files)\n\n\tfor j=1:ns\n\t\t% Load associated landmarks\n\t\tload(sprintf('%s/%s', directory, landmark_files(j).name));\n\t\tinfo = imfinfo(sprintf('%s/%s', directory, landmark_files(j).name(1:end-4)));\n\t\tshape_data(:,:,j) = xy2ij(annotations, info.Height);\n\tend\n\n\t% number of points\n\tnp = size(shape_data, 1);\n\n\t% use first shape as initial mean\n\tmean_shape = shape_data(:,:,1);\n\n\treference_shape = mean_shape;\n\n\t% Matrix containing the aligned shapes\n\taligned_data = shape_data;\n\n\n\t% Less iterations should be enough, but better safe than sorry, efficiency\n\t% is not an issue here\n\tfor it=1:100\n\t\tfor i=1:ns\n\t\t\t% Align each shape to the mean\n\t\t\t[ D Y ] = procrustes(mean_shape, aligned_data(:,:,i));\n\t\t\taligned_data(:,:,i) = Y;\n\t\tend\n\n\t\t% New mean shape, store in a different variable so we can compare it to\n\t\t% the old one\n\t\tnew_mean_shape = mean(aligned_data, 3);\n\t\t[ D Y ] = procrustes(reference_shape, new_mean_shape);\n\t\tnew_mean_shape = Y;\n\n\t\tmean_shape = new_mean_shape;\n\tend\n\n\tmean_shape = mean(aligned_data, 3);\n\n\t% Determine the region of interest\n\tmini = min(mean_shape(:,1));\n\tminj = min(mean_shape(:,2));\n\tmaxi = max(mean_shape(:,1));\n\tmaxj = max(mean_shape(:,2));\n\n\t% Place the origin in the upper left corner of the rectangle\n\t% representing the bounding box of the mean shape. Add a 1\n\t% pixel offset to avoid artifacts in gradient computations.\n\tmean_shape = mean_shape - repmat([mini - 2, minj - 2], [np, 1]);\n\n\tdisp 'Width of model:'\n\t% Determine width and height of the model, add 1 pixel offset\n\t% to avoid gradient artifacts\n\tmodelw = ceil(maxj - minj + 3)\n\tdisp 'Height of model:'\n\tmodelh = ceil(maxi - mini + 3)\n\n\tdisp 'Time required for shape data alignment:'\n\n\ttoc\n\n\t%%\n\t%% DEBUG STUFF\n\t%%\n%\tfor i=1:ns\n%\t\tplot(aligned_data(:,2,i), aligned_data(:,1,i), 'o');\n%\t\thold on;\n%\t\tpause;\n%\tend\n%\tplot(mean_shape(:,2), mean_shape(:,1), 'rx');\n%\thold off;\n%\treturn;\n\n\t%%\n\t%% END OF DEBUG STUFF\n\t%%\n\n\ttic\n\n\t% Definitive mean shape for AAM, stored on a column vector [i1 i2 i3 ... j1 j2 j3 ...]'\n\tAAM.s0 = reshape(mean_shape, 2*np, 1);\n\n\t% Prepare shape data for PCA\n\tshape_matrix = reshape(aligned_data, [2*np ns]) - repmat(AAM.s0, [1 ns]);\n\tclear aligned_data;\n\n\t% Get modes covering 98% of variation\n\t[pc eiv] = var_pca(shape_matrix, 0.98);\n\tclear shape_matrix;\n\n\tdisp 'Number of Shape Modes:'\n\tsize(pc, 2)\n\n\tAAM.shape_eiv = eiv;\n\n\t% Build the basis for the global shape transform, we do it here because\n\t% they are used to orthonormalize the shape principal vectors\n\t% It is done differently to the paper as we're using a different coordinate\n\t% frame. Here u -> i, v -> j\n\ts1_star = AAM.s0;\n\ts2_star(1:np) = -AAM.s0(np+1:end);\n\ts2_star(np+1:2*np) = AAM.s0(1:np);\n\ts3_star(1:np) = ones(np,1);\n\ts3_star(np+1:2*np) = zeros(np,1);\n\ts4_star(1:np) = zeros(np,1);\n\ts4_star(np+1:2*np) = ones(np,1);\n\n\t% Stack the basis we found before with the shape basis so\n\t% we can orthonormalize\n\ts_star_pc(:,1) = s1_star;\n\ts_star_pc(:,2) = s2_star;\n\ts_star_pc(:,3) = s3_star;\n\ts_star_pc(:,4) = s4_star;\n\n\ts_star_pc(:,5:size(pc,2)+4) = pc;\n\n\n\t% Orthogonalize the basis (should already be close to orthogonal)\n\ts_star_pc = gs_orthonorm(s_star_pc);\n\n\t% Basis for the global shape transform\n\tAAM.s_star = s_star_pc(:,1:4);\n\t% Basis for the shape model\n\tAAM.s = s_star_pc(:,5:end);\n\n\tdisp 'Time required for building shape model:'\n\ttoc\n\n\t%%\n\t%% DEBUG STUFF\n\t%%\n\n%\tdisp 'Plotting principal vectors as deformation directions of the mean...'\n%\n%\tplot_s0 = reshape(AAM.s0, [np 2]);\n%\n%\tfor i=1:size(AAM.s, 2)\n%\t\thold off;\n%\t\tplot(plot_s0(:,2), plot_s0(:,1), 'o');\n%\t\thold on;\n%\n%\t\tfprintf('Principal vector %d\\n.', i);\n%\n%\t\tdelta_s = reshape(AAM.s(:,i), [np 2]);\n%\t\tplot_s = plot_s0 + delta_s * 16;\n%\n%\t\tfor j=1:5\n%\t\t\tplot(plot_s(:,2), plot_s(:,1), 'r.');\n%\t\t\tplot_s = plot_s + delta_s * 16;\n%\t\tend\n%\t\thold off;\n%\t\tdisp 'Waiting for keypress...'\n%\t\tpause;\n%\tend\n%\treturn;\n\n\t%%\n\t%% END OF DEBUG STUFF\n\t%%\n\n\ttic\n\n\t% Check if a triangulation was already provided\n\tif size(shape_triangles, 1) == 0\n\t\t% Triangle mesh used for warping. We determine it on the base shape.\n\t\t% Returned result is double, convert to unsigned integer.\n\t\tshape_triangles = delaunay(AAM.s0(np+1:2*np)', AAM.s0(1:np)');\n\t\t%triplot(shape_triangles, AAM.s0(1:np)', AAM.s0(np+1:2*np)');\n\tend\n\n\t% Bitmap mapping pixels to the triangle they belong to (the triangle used\n\t% for warping)\n\twarp_map = zeros(modelh, modelw, 'uint32');\n\n\t% Bitmap containing the first barycentric coordinate of each pixel wrt to the\n\t% triangle specified by warp_map\n\talpha_coords = zeros(modelh, modelw);\n\n\t% Bitmap containing the second barycentric coordinate of each pixel wrt to the\n\t% triangle specified by warp_map\n\tbeta_coords = zeros(modelh, modelw);\n\n\t% For each pixel, find the triangle it belongs to\n\tfor j=1:modelw\n\t\tfor i=1:modelh\n\t\t\t% For each triangle\n\t\t\tfor k=1:size(shape_triangles, 1)\n\t\t\t\tt = shape_triangles(k,:);\n\n\t\t\t\t% Vertices of the triangle in the mean shape\n\t\t\t\ti1 = AAM.s0(t(1));\n\t\t\t\tj1 = AAM.s0(np + t(1));\n\t\t\t\ti2 = AAM.s0(t(2));\n\t\t\t\tj2 = AAM.s0(np + t(2));\n\t\t\t\ti3 = AAM.s0(t(3));\n\t\t\t\tj3 = AAM.s0(np + t(3));\n\n\t\t\t\t% Compute the two barjcentric coordinates\n\t\t\t\tden = (i2 - i1) * (j3 - j1) - (j2 - j1) * (i3 - i1);\n\t\t\t\talpha = ((i - i1) * (j3 - j1) - (j - j1) * (i3 - i1)) / den;\n\t\t\t\tbeta = ((j - j1) * (i2 - i1) - (i - i1) * (j2 - j1)) / den;\n\n\t\t\t\tif alpha >= 0 && beta >= 0 && (alpha + beta) <= 1\n\t\t\t\t\t% Found the triangle, save data to the bitmaps and break\n\t\t\t\t\twarp_map(i,j) = k;\n\t\t\t\t\talpha_coords(i,j) = alpha;\n\t\t\t\t\tbeta_coords(i,j) = beta;\n\t\t\t\t\tbreak;\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\tend\n\n\t% Build adjacency list\n\tAAM.adj_list = cell(np, 1);\n\n\tfor i=1:size(shape_triangles, 1)\n\t\tfor j=1:3\n\t\t\tv = shape_triangles(i,j);\n\t\t\tAAM.adj_list{v} = [AAM.adj_list{v} i];\n\t\tend\n\tend\n\n\t% IMPORTANT: If the datatype is changed from 'uint32', the mex-file will\n\t% need to be changed!\n\tAAM.warp_map = uint32(warp_map);\n\tAAM.shape_mesh = uint32(shape_triangles);\n\tAAM.alpha_coords = alpha_coords;\n\tAAM.beta_coords = beta_coords;\n\n\tdisp 'Time required for warp pre-computations:'\n\ttoc\n\n\t%%\n\t%% DEBUG STUFF\n\t%%\n%\tcolor_map = rand(max(max(warp_map)), 3);\n%\tfigure(1)\n%\timshow(warp_map, color_map);\n%\n%\tfigure(2)\n%\timshow(alpha_coords);\n%\n%\tfigure(3)\n%\timshow(beta_coords);\n%\n%\treturn;\n\n\t%%\n\t%% END OF DEBUG STUFF\n\t%%\n\n\ttic\n\n\t% FIXME: This is somewhat of an hack, but the code is so slow when matrices grow inside loops...\n\tapp = double(imread(sprintf('%s/%s', directory, landmark_files(1).name(1:end-4)))) / 255;\n\tapp_matrix = zeros(modelw*modelh*size(app,3), ns);\n\n\tdisp 'Color components:'\n\tnc = size(app, 3)\n\n\tfor i=1:ns\n\t\t% Prepare appearance data\n\t\tapp = double(imread(sprintf('%s/%s', directory, landmark_files(i).name(1:end-4)))) / 255;\n\t\t%app = convn(convn(app, exp(-(-5:5).^2)./sum(exp(-(-5:5).^2)), 'same'), exp(-(-5:5).^2)./sum(exp(-(-5:5).^2))', 'same');\n\n\t\tapp_matrix(:,i) = reshape(pa_warp(AAM, shape_data(:,:,i), app), [(modelw*modelh*nc) 1]);\n\tend\n\n\tdisp 'Time required for warping all input appearances:'\n\ttoc\n\n\tclear app;\n\tclear landmark_files;\n\n\t%%\n\t%% DEBUG STUFF\n\t%%\n\n%disp 'Displaying warped images...'\n%\n%for i=1:ns\n%\tfprintf('Image %d\\n.', i);\n%\n%\timshow(reshape(app_matrix(:,i), [modelh modelw nc]));\n%\n%\thold on;\n%\n%\ttriplot(shape_triangles, AAM.s0(np+1:2*np)', AAM.s0(1:np)');\n%\thold off;\n%\n%\tdisp 'Waiting for keypress...'\n%\tpause;\n%end\n%hold off;\n%return;\n\n\t%%\n\t%% END OF DEBUG STUFF\n\t%%\n\n\n\ttic\n\n\t% FIXME: Should we normalize pixel values like done by Stegmann to\n\t% improve the generalization of the model?\n\n\t% Mean appearance as a column vector, sorted firstly by color\n\t% component, then j coordinate and finally i coordinate\n\t%Example:\n\t% X1 = [ 1 2; 3 4];\n\t% X2 = [ 5 6; 7 8];\n\t% X3 = [ 9 10; 11 12];\n\t% X(:,:,1)=X1;\n\t% X(:,:,2)=X2;\n\t% X(:,:,3)=X3;\n\t% reshape(X,[],1) =>\n\t% _________\n\t% 1 j==1\n\t% 3 _____ C1\n\t% 2 j==2\n\t% 4 _________\n\t% 5 j==1\n\t% 7 _____ C2\n\t% 6 j==2\n\t% 8 _________\n\t% 9 j==1\n\t% 11 _____ C3\n\t% 10 j==2\n\t% 12 _________\n\n\tAAM.A0 = mean(app_matrix, 2);\n\tmean_app = reshape(AAM.A0, [modelh modelw nc]);\n\n\t%app_size = modelw * modelh * nc;\n\n\t% Prepare apperances for PCA\n\tapp_matrix = app_matrix - repmat(AAM.A0, [1 ns]);\n\n\t% FIXME: Goes out of memory without 'econ' flag, look at \"An Introduction to Active\n\t% Shape Models\" by Cootes for an optimized PCA\n\t%[pc eiv] = var_pca(app_matrix, 0.95);\n [pc eiv] = app_pca(app_matrix, 0.95);\n\n\tclear app_matrix;\n\n\tdisp 'Number of Appearance Modes:'\n\tsize(pc, 2)\n\n\tAAM.A = pc;\n\tAAM.app_eiv = eiv;\n\n\tdisp 'Time required for building apperance model:'\n\ttoc\n\n\t%%\n\t%% DEBUG STUFF\n\t%%\n\n% disp 'Displaying results of PCA on appearances...'\n%\n%\tfor i=1:size(AAM.A,2)\n% cur_app = reshape(AAM.A(:,i), [modelh modelw nc]);\n%\n%\t\tfprintf('Showing mean appearance and sums of mean and principal component %d with increasing weight\\n.', i);\n%\n%\t\tsubplot(1,3,1), imshow(mean_app)\n%\t\tsubplot(1,3,2), imshow(mean_app + cur_app*sqrt(eiv(i))*3)\n%\t\tsubplot(1,3,3), imshow(mean_app - cur_app*sqrt(eiv(i))*3)\n%\t\t%subplot(1,4,4), imshow(mean_app + cur_app*sqrt(eiv(i))*3)\n%\n%\t\tdisp 'Waiting for keypress...'\n%\t\tpause;\n%\tend\n%\thold off;\n%\treturn;\n\t%%\n\t%% END OF DEBUG STUFF\n\t%%\n\n\ttic\n\n\t% Now we get into the interesting (and tricky) stuff\n\n\tfor i=1:nc\n\t\t% For each color, estimate the gradient of the mean appearance.\n\t\t% dcol is the estimated derivative wrt to columns (which for us is the\n\t\t% j coordinate), drow is wrt to rows (which for us is the i coordinate)\n\t\t[di dj] = gradient_2d(mean_app(:,:,i), AAM.warp_map);\n\t\tmean_app_gradient(:,:,i,1) = di;\n\t\tmean_app_gradient(:,:,i,2) = dj;\n\tend\n\n\tAAM.dA0 = mean_app_gradient;\n\n\t%%\n\t%% DEBUG STUFF\n\t%%\n%\tfigure(1)\n%imshow(mean_app);\n%\tmn = min(min(min(min(AAM.dA0))));\n%\tmx = max(max(max(max(AAM.dA0))));\n%\n%\tplot_dA0 = (AAM.dA0 - repmat(mn, [modelh modelw nc 2])) / (mx - mn);\n%\tfigure(2)\n%\timshow(plot_dA0(:,:,:,1));\n%\tfigure(3);\n%\timshow(plot_dA0(:,:,:,2));\n%\treturn;\n\t%%\n\t%% END OF DEBUG STUFF\n\t%%\n\n\tdisp 'Time required for calculating image gradient:'\n\ttoc\n\n\ttic\n\n\tdW_dp = zeros(modelh, modelw, 2, size(AAM.s,2));\n\tdN_dq = zeros(modelh, modelw, 2, 4);\n\n\tfor j=1:modelw\n\t\tfor i=1:modelh\n\t\t\tif warp_map(i,j) ~= 0\n\t\t\t\t% Only the vertices of the triangle containing the pixel are of relevance\n\t\t\t\t% in determining the Jacobian.\n\t\t\t\tt = shape_triangles(warp_map(i,j),:);\n\n\t\t\t\t% FIXME: this is not how it should be done, there is a way to juggle\n\t\t\t\t% with the barycentric coordinates we already computed to do the same\n\t\t\t\tfor k=1:3\n\t\t\t\t\t% Derivative of vertex 'k' wrt to the shape parameters\n\t\t\t\t\tdik_dp = AAM.s(t(k),:);\n\t\t\t\t\tdjk_dp = AAM.s(t(k)+np,:);\n\n\t\t\t\t\t% Derivative of vertex 'k' wrt to the global transformation parameters\n\t\t\t\t\tdik_dq = AAM.s_star(t(k),:);\n\t\t\t\t\tdjk_dq = AAM.s_star(t(k)+np,:);\n\n\t\t\t\t\t% Now we need the barycentric coordinates of (i,j) computed using\n\t\t\t\t\t% point 'k' as the origin. So we rearrange the order of the vertices\n\t\t\t\t\t% (it doesn't matter if the result has clockwise or counterclockwise\n\t\t\t\t\t% winding)\n\t\t\t\t\tt2 = t;\n\t\t\t\t\tt2(1) = t(k);\n\t\t\t\t\tt2(k) = t(1);\n\n\t\t\t\t\t\t% Vertices of the triangle in the mean shape\n\t\t\t\t\ti1 = AAM.s0(t2(1));\n\t\t\t\t\tj1 = AAM.s0(np + t2(1));\n\t\t\t\t\ti2 = AAM.s0(t2(2));\n\t\t\t\t\tj2 = AAM.s0(np + t2(2));\n\t\t\t\t\ti3 = AAM.s0(t2(3));\n\t\t\t\t\tj3 = AAM.s0(np + t2(3));\n\n\t\t\t\t\t% Compute the two barycentric coordinates\n\t\t\t\t\tden = (i2 - i1) * (j3 - j1) - (j2 - j1) * (i3 - i1);\n\t\t\t\t\talpha = ((i - i1) * (j3 - j1) - (j - j1) * (i3 - i1)) / den;\n\t\t\t\t\tbeta = ((j - j1) * (i2 - i1) - (i - i1) * (j2 - j1)) / den;\n\n\n\t\t\t\t\t% Nonzero portion of the Jacobian of the warp wrt to the vertex 'k'.\n\t\t\t\t\t% TODO: Isn't this the third barycentric coordinate? It should be\n\t\t\t\t\t% easier and faster to compute it directly.\n\t\t\t\t\tdW_dij = 1 - alpha - beta;\n\n\t\t\t\t\t% This is how it's formulated on the paper (dW_dq is similar):\n\t\t\t\t\t% dW_dp = dW_dp + [dW_dij; 0] * dik_dp + [0; dW_dij] * djk_dp;\n\t\t\t\t\t% MATLAB does weird things with dimensions here, so we need squeeze()\n\t\t\t\t\t% to make sure the submatrix is actually a 2xn matrix and not a\n\t\t\t\t\t% 1x1x2xn\n\t\t\t\t\tdW_dp(i,j,:,:) = squeeze(dW_dp(i,j,:,:)) + dW_dij * [dik_dp; djk_dp];\n\t\t\t\t\tdN_dq(i,j,:,:) = squeeze(dN_dq(i,j,:,:)) + dW_dij * [dik_dq; djk_dq];\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\tend\n\n\tdisp 'Time required for calculating warp Jacobians:'\n\ttoc\n\n\t%%\n\t%% DEBUG STUFF\n\t%%\n% disp 'Displaying the warp Jacobian...'\n%\n%\tfor i=1:size(dW_dp,4)\n%\t jacobian_i = dW_dp(:,:,1,i);\n%\t jacobian_j = dW_dp(:,:,2,i);\n%\n%\n%\t\tfprintf('Showing warp jacobian i and j components for parameter %d\\n.', i);\n%\n%\t\tsubplot(1,2,1), imshow(jacobian_i)\n%\t\tsubplot(1,2,2), imshow(jacobian_j)\n%\n%\t\tdisp 'Waiting for keypress...'\n%\t\tpause;\n%\tend\n%\treturn;\n\t%%\n\t%% END OF DEBUG STUFF\n\t%%\n\n\ttic\n\n\tapp_modes = reshape(AAM.A, [modelh modelw nc size(AAM.A, 2)]);\n\n\tSD = zeros(modelh, modelw, nc, 4 + size(dW_dp, 4));\n\n\t% Compute steepest descent images for the 4 global transformation parameters\n\t% TODO: the loops over c are probably optimizable, but the number of dimensions involved\n\t% are starting to hurt my head...\n\t% TODO: test me\n\tfor i=1:4\n\t\tprj_diff = zeros(nc, size(AAM.A, 2));\n\t\tfor j=1:size(AAM.A, 2)\n\t\t\tfor c=1:nc\n\t\t\t\tprj_diff(c,j) = sum(sum(app_modes(:,:,c,j) .* (AAM.dA0(:,:,c,1) .* dN_dq(:,:,1,i) + AAM.dA0(:,:,c,2) .* dN_dq(:,:,2,i))));\n\t\t\tend\n\t\tend\n\n\t\tfor c=1:nc\n\t\t\tSD(:,:,c,i) = AAM.dA0(:,:,c,1) .* dN_dq(:,:,1,i) + AAM.dA0(:,:,c,2) .* dN_dq(:,:,2,i);\n\t\tend\n\n\t\tfor j=1:size(AAM.A, 2)\n\t\t\tfor c=1:nc\n\t\t\t\tSD(:,:,c,i) = SD(:,:,c,i) - prj_diff(c,j) * app_modes(:,:,c,j);\n\t\t\tend\n\t\tend\n\tend\n\n\t% Compute steepest descent images for the shape parameters\n\t% TODO: the loops over c are probably optimizable, but the number of dimensions involved\n\t% are starting to hurt my head...\n\t% TODO: test me\n\tfor i=1:size(dW_dp, 4)\n\t\tprj_diff = zeros(nc, size(AAM.A, 2));\n\t\tfor j=1:size(AAM.A, 2)\n\t\t\tfor c=1:nc\n\t\t\t\tprj_diff(c,j) = sum(sum(app_modes(:,:,c,j) .* (AAM.dA0(:,:,c,1) .* dW_dp(:,:,1,i) + AAM.dA0(:,:,c,2) .* dW_dp(:,:,2,i))));\n\t\t\tend\n\t\tend\n\n\t\tfor c=1:nc\n\t\t\tSD(:,:,c,i+4) = AAM.dA0(:,:,c,1) .* dW_dp(:,:,1,i) + AAM.dA0(:,:,c,2) .* dW_dp(:,:,2,i);\n\t\tend\n\n\t\tfor j=1:size(AAM.A, 2)\n\t\t\tfor c=1:nc\n\t\t\t\tSD(:,:,c,i+4) = SD(:,:,c,i+4) - prj_diff(c,j) * app_modes(:,:,c,j);\n\t\t\tend\n\t\tend\n\tend\n\n\tAAM.SD = zeros(size(SD, 4), size(AAM.A,1));\n\n\t% FIXME: A posteriori optimization fix, integrate it more nicely with the code.\n\tfor i=1:size(SD, 4)\n\t\tAAM.SD(i,:) = reshape(SD(:,:,:,i), 1, []);\n\tend\n\n\t%%\n\t%% DEBUG STUFF\n\t%%\n%\tmn = min(min(min(min(SD))));\n%\tmx = max(max(max(max(SD))));\n%\tSD = (SD - repmat(mn, [modelh modelw nc size(SD, 4)])) / (mx - mn);\n%\tfor i=1:size(SD,4)\n%\t\th=figure(i+1);\n%\t\timshow(SD(:,:,:,i));\n%\tend\n\t%%\n\t%% END OF DEBUG STUFF\n\t%%\n\n\tclear SD;\n\n\tdisp 'Time required for calculating steepest descent images:'\n\ttoc\n\n\ttic\n\n\t% Compute the Hessian, still not sure if this is the right\n\t% way to treat the color information (using greyscale images\n\t% give pretty much the same matching results so it should be ok)\n\tAAM.H = AAM.SD * AAM.SD';\n\n\tAAM.invH = inv(AAM.H);\n\n\tAAM.R = AAM.invH * AAM.SD;\n\n\tdisp 'Time required for determining and inverting Jacobian and calculating invH*SD:'\n\ttoc\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/32704-icaam-inverse-compositional-active-appearance-models/icaam/build_model_2d_from_files.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6113819591324416, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.32239180914670773}} {"text": "% Q = vbfa(D, Y, W_module, X_module, noise_module, ...)\n% \n% Variational Bayesian (VB) factor analysis (FA) learning algorithm with\n% changeable modules for the latent variables.\n%\n% Optional parameters:\n% 'maxiter' 100\n% 'update_x' 1\n% 'update_w' 1\n% 'update_noise' 1\n% 'rotate' 1\n% 'rotation_checkgrad' false\n% 'rotation_show' false\n% 'rotation_maxiter' 10\n% 'debug' false\n% 'autosave' false\n% 'autosavefile' 'vbfa_autosave'\n\nfunction Q = vbfa(D, Y, W_module, X_module, noise_module, varargin)\n\n[M,N] = size(Y);\n\noptions = struct('maxiter', 100, ...\n 'update_x', 1, ...\n 'update_w', 1, ...\n 'update_noise', 1, ...\n 'initialize_x', true, ...\n 'initialize_w', true, ...\n 'initialize_noise', true, ...\n 'rotate', 1, ...\n 'rotation_checkgrad', false, ...\n 'rotation_show', false, ...\n 'rotation_maxiter', 10, ...\n 'loglikelihood', true, ...\n 'debug', false, ...\n 'autosave', false,...\n 'autosavefile', 'vbfa_autosave');\n\n[options, errmsg] = argparse(options, varargin{:});\nerror(errmsg);\n\n% Initialize\ndisp('Initializing variables..')\nif options.initialize_w\n [Q.W,Q.CovW,Q.rhow] = W_module.initialize(D,M);\nelse\n QW = W_module.get_struct();\n Q.W = QW.X;\n Q.CovW = QW.CovX;\n Q.rhow = QW.rho;\nend\nif options.initialize_x\n [Q.X,Q.CovX,Q.rhox] = X_module.initialize(D,N);\nelse\n QX = W_module.get_struct();\n Q.X = QX.X;\n Q.CovX = QX.CovX;\n Q.rhox = QX.rho;\nend\nif options.initialize_noise\n [Q.Tau] = noise_module.initialize(M,N);\nelse\n QTau = noise_module.get_struct();\n Q.Tau = QTau.Tau;\nend\n%Q.W_module = W_module;\n%Q.X_module = X_module;\n%Q.noise_module = noise_module;\n\n\n% Observed values\nObs = ~isnan(Y);\nMN_obs = sum(Obs(:));\n\n%%\n%% VB learning\n\nloglikelihood_old = -inf;\nQ.loglikelihood = nan(options.maxiter,1);\n\nQ.Y = Y;\n\n% Replace missing values with zeros for computational reasons\nY(~Obs) = 0;\n\nKL_W = -inf;\nKL_X = -inf;\nKL_Tau = -inf;\n\n% Debugging stuff:\nklw = nan(options.maxiter,1);\nklx = nan(options.maxiter,1);\nkltau = nan(options.maxiter,1);\nloglike = nan(options.maxiter,1);\n\n\n%f = zeros(4,options.maxiter);\n\ndisp('Starting the VB iteration..')\nfor ind=1:options.maxiter\n Q.ind = ind;\n \n startitercpu = cputime;\n \n %\n % Update variables\n %\n \n Tau = Q.Tau;\n Tau(~Obs) = 0;\n \n if index_selected(Q.ind, options.update_x)\n if index_selected(Q.ind, options.debug)\n disp('Update X')\n end\n %[U,Z] = projection(Y,Obs,W,CovW,Tau);\n [Q.X,Q.CovX,Q.rhox,logrhox,KL_X] = X_module.update(Q.ind, Y, Obs, Q.W, ...\n Q.CovW, Q.rhow, Tau);\n end\n \n if index_selected(Q.ind, options.update_w)\n if index_selected(Q.ind, options.debug)\n disp('Update W')\n end\n %[U,Z] = projection(Y',Obs',X,CovX,Tau');\n [Q.W,Q.CovW,Q.rhow,logrhow,KL_W] = W_module.update(Q.ind, Y', Obs', Q.X, ...\n Q.CovX, Q.rhox, Tau');\n end\n \n % Compute squared errors <(y_mn-w_m*x_n)^2>\n % (used by noise update and loglikelihood)\n E2 = zeros(size(Y));\n Yh = Q.W'*Q.X;\n E2 = Y.*Y;\n E2 = E2 - 2*Y.*Yh;\n E2 = spdiag(Q.rhow)*E2*spdiag(Q.rhox);\n if ndims(Q.CovW) == 2 && ndims(Q.CovX) == 2\n E2 = E2 ...\n + spdiag(Q.rhow)*(Yh.^2)*spdiag(Q.rhox) ...\n + spdiag(Q.rhow)*(Q.W'.^2)*Q.CovX ...\n + Q.CovW'*(Q.X.^2)*spdiag(Q.rhox) ...\n + Q.CovW'*Q.CovX;\n elseif ndims(Q.CovW) == 3 && ndims(Q.CovX) == 3\n xx = bsxfun(@times, reshape(Q.X*spdiag(Q.rhox),[D,1,N]), reshape(Q.X,[1,D,N])) ...\n + Q.CovX;\n xx = reshape(xx, [D*D,N]);\n ww = bsxfun(@times, reshape(Q.W*spdiag(Q.rhow),[D,1,M]), reshape(Q.W,[1,D,M])) ...\n + Q.CovW;\n ww = reshape(ww, [D*D,M]);\n E2 = E2 + ww'*xx;\n else\n % TODO: Optimize this..\n warning('Optimize this.. and is rho properly here??');\n for m=1:M\n for n=1:N\n if Obs(m,n)\n if ndims(Q.CovW) == 2\n ww = Q.W(:,m)*Q.W(:,m)' + diag(Q.CovW(:,m));\n else\n ww = Q.W(:,m)*Q.W(:,m)' + Q.CovW(:,:,m);\n end\n if ndims(Q.CovX) == 2\n xx = Q.X(:,n)*Q.X(:,n)' + diag(Q.CovX(:,n));\n else\n xx = Q.X(:,n)*Q.X(:,n)' + Q.CovX(:,:,n);\n end\n %WX_WX = WX_WX + traceprod(ww, xx);\n E2(m,n) = E2(m,n) + traceprod(ww, xx);\n end\n end\n end\n end\n E2(~Obs) = 0;\n\n if index_selected(Q.ind, options.update_noise)\n if index_selected(Q.ind, options.debug)\n disp('Update Tau')\n end\n \n [Q.Tau,LogTau,KL_Tau] = noise_module.update(Q.ind, E2, Obs);\n% [Tau,lowerbound] = noise_module.update(Y, Obs, v_W, W, CovW, v_X, X, CovX);\n end\n \n\n %\n % Rotate\n %\n \n if index_selected(Q.ind, options.rotate)\n \n % TODO: You could optimize the hyperparameters at the same time?\n disp('Rotating..')\n A = eye(D);\n \n if index_selected(Q.ind, options.rotation_checkgrad)\n mycheckgrad(@rotation_cost, A(:) + 0.5*randn(D^2,1), 1e-3, W_module, ...\n X_module);\n end\n A = minimize(A(:), @rotation_cost, options.rotation_maxiter, W_module, ...\n X_module);\n A = reshape(A, [D D]);\n if index_selected(Q.ind, options.rotation_show)\n A\n end\n [Q.W, Q.CovW] = W_module.rotate(A);\n [Q.X, Q.CovX] = X_module.rotate(inv(A)');\n\n end\n\n \n %\n % Evaluate VB lower bound\n %\n \n if index_selected(Q.ind, options.loglikelihood)\n % Likelihood part: \n logpdf_y = gaussian_logpdf(Q.Tau(Obs)'*E2(Obs), ...\n 0, ...\n 0, ...\n -sum(LogTau(Obs))-logrhow'*sum(Obs,2)-sum(Obs,1)*logrhox, ...\n MN_obs);\n\n % Debugging stuff\n klw(Q.ind) = -KL_W;\n klx(Q.ind) = -KL_X;\n kltau(Q.ind) = -KL_Tau;\n loglike(Q.ind) = logpdf_y;\n\n % Lower bound\n Q.loglikelihood(Q.ind) = logpdf_y - KL_W - KL_X - KL_Tau;\n \n if Q.loglikelihood(Q.ind) < loglikelihood_old\n warning(sprintf('Loglikelihood lower bound decreased relatively %e!', ...\n (loglikelihood_old - Q.loglikelihood(Q.ind)) / ...\n loglikelihood_old));\n % plot([Q.loglikelihood, klw, klx, kltau, loglike]);\n end\n \n fprintf('Iteration step %d: loglikelihood=%e (%.2f seconds)\\n', Q.ind, ...\n Q.loglikelihood(Q.ind), cputime()-startitercpu);\n \n loglikelihood_old = Q.loglikelihood(Q.ind);\n end\n \n if index_selected(Q.ind, options.autosave)\n Q.W_struct = W_module.get_struct();\n Q.X_struct = X_module.get_struct();\n Q.Tau_struct = noise_module.get_struct();\n fprintf('Saving results to %s...', options.autosavefile);\n save(options.autosavefile, '-struct', 'Q');\n fprintf(' done.\\n');\n end\n \nend\n\n\n\nfunction [c, dc] = rotation_cost(a, W_module, X_module)\nN = sqrt(length(a));\nA = reshape(a, N, N);\n[U,S,V] = svd(A);\ninvS = diag(1./diag(S));\ninvAt = U*invS*V';\n[c_w, dc_w] = W_module.rotation_cost(A, U, S, V);\n[c_x, dc_x] = X_module.rotation_cost(invAt, U, invS, V);\ndc_x = -invAt*dc_x'*invAt;\nc = c_w + c_x;\ndc = dc_w(:) + dc_x(:);\n\n", "meta": {"author": "jluttine", "repo": "matlab", "sha": "63406c7782b0869948f06e1dbc594460c165d24e", "save_path": "github-repos/MATLAB/jluttine-matlab", "path": "github-repos/MATLAB/jluttine-matlab/matlab-63406c7782b0869948f06e1dbc594460c165d24e/fa/old_vbfa.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.3223314157806203}} {"text": "%Starts from the current decoded state, takes input as minimum distance to\n%reach that state and previous state And returns previous state and decoded\n%information bit corresponding to that state.\n\nfunction [prev_state,decoded_bit]=prev_stage(curr_state,distance_prev,metric)\n if(curr_state==1)\n if(distance_prev(1)+metric(1) <= distance_prev(3)+metric(5))\n prev_state=1;decoded_bit=0;\n else\n prev_state=3;decoded_bit=0;\n end\n end\n \n if(curr_state==2)\n if(distance_prev(1)+metric(2) <= distance_prev(3)+metric(6))\n prev_state=1;decoded_bit=1;\n else\n prev_state=3;decoded_bit=1;\n end\n end\n \n if(curr_state==3)\n if(distance_prev(2)+metric(3) <= distance_prev(4)+metric(7))\n prev_state=2;decoded_bit=0;\n else\n prev_state=4;decoded_bit=0;\n end\n end\n \n if(curr_state==4)\n if(distance_prev(2)+metric(4) <= distance_prev(4)+metric(8))\n prev_state=2;decoded_bit=1;\n else\n prev_state=4;decoded_bit=1;\n end\n end\n \nend", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/38559-viterbi-decoder/prev_stage.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.3220556577548419}} {"text": "function [] = aps_weather_model_SAR(model_type)\n% [] = aps_weather_model_SAR()\n% Script to load weather model data and compute SAR delays\n% The DEM file can be .grd file or other. If the latter, the DEM should have an asociated\n% \".rsc\" file, with the same filename as the DEM. The \".rsc\" files should\n% contain a WIDTH, LENGTH, X_FIRST, Y_FIRST, X_STEP, Y_STEP and optional a \n% FORMAT string. The weather model data is assumed to be structured in date_before(d,:) folders. \n%\n%\n% INPUTS:\n% demfile Full path to the DEM file. The DEM needs to me in meters.\n% xlims Limits in the x-direction, either in degrees\n% ylims Limits in the y-direction, either in degrees\n% demnull The value for no DEM data, default is -32768.\n% smpres The output resolution, either in degrees\n% Units needs to be consistend with xlims and ylims.\n%\n% OUTPUTS:\n% It will give the computed ZENITH hydrostatic and wet delay map in cm for the selected region. \n%\n% Copyright (C) 2015 Bekaert David - University of Leeds\n% Email: eedpsb@leeds.ac.uk or davidbekaert.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 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%\n% Modified from Richard Walters - Oxford / Leeds University 2012-2013\n% Modifcations:\n% DB \t10/2013\t\tConvert script to a function, integrate in aps_toolbox, \n% add syntax. Retrieve parameters automatic.\n% DB 10/2013 Output the combined delay map.\n% DB 10/2013 Increased processing efficiency\n% DB 10/2013 add compatibility with Doris construct_dem.sh script\n% DB 10/2013 Bug fix incase the the netcdf is split over two days\n% DB 11/2013 Change the computation f saturated pressure to be\n% identical witt how it was computed in ERA-I model.\n% DB 11/2013 Update filenaming to Hydrostatic as its not dry delay.\n% Compute the hydrostatic delay directly from int(P/T)\n% DB 01/2014 Fix bug for the ERA-I longitude boundary, being set to small. \n% DB 01/2014 Allow for tiled ERA-I data\n% HB-DB 02/2014 Fix to include ECMWF with scaling and offset\n% DB 02/2014 Include a parameter for ECMWF data website\n% DB 03/2014 Include an extra check for the DEM grd file and the\n% selected crop\n% DB \t03/2014 Save individual time stamp SAR date_before(d,:) processing\n% DB 07/2014 Redefine meris_lat(lon)_range to region_lat(lon)_range\n% DB 08/2014 Check if netcdf exist (ERA-I is not an operation service)\n% DB 11/2014 Include option to output the 3D delays for each date_before(d,:)\n% HW 02/2015 check dem file format automatically\n% DB \t06/2015 Bug fix for plotting the support information \n% DB 06/2015 Fix typo in error message\n% DB 11/2015 Branch of the DEM in to seperate function same for all codes\n% DB 11/2015 Add multicore option from matlab\n% DB \t02/2016 Close netcdf files\n% DB 04/2016 Branch into weather model script and include merra too\n% SSS 04/2016 Clear variables such memory need is reduced\n% DB 07/2016 redefine hydrostatic delay to be based on surface pressure.\n% DB 08/2016 Uncomment a keyboard\n% DB 07/2016 expand to include ERA5 test model data\n% KM 02/2018 expand to include NARR model data\n\nfig_test = 0; % when 1 show the dem as debug figure\nsave_3D_delays = 0; % When 1 saves the tropopsheric delays for each x,y and with height\n\nif nargin<1\n error('Give at least the model_type: era, era5, narr, merra, or merra2')\nend\n% change to lower caps for saving and filename generation consistency\nmodel_type = lower(model_type);\n\n%% Constants\n% Parameters from Jolivet et al 2011, GRL\nRd = 287.05; % [j/kg/K] specific gas constants dry air\nRv = 461.495; % [j/kg/K] water vapour\nk1 = 0.776; % [K/Pa]\nk2 = 0.716; % [K/Pa]\nk3 = 3.75e3; % [K^2/Pa]\ncoeff.Rd = Rd;\ncoeff.Rv = Rv;\n\n%% Defaults\nzref = 15000; % zref for integration- tropopause\nzincr = 15; % z increment spacing for vertical interpolation before integration\nvertres = 5; % vertical resolution for comparing dem to vert profiles of delay\n\n%% output file names\n% output file for the DEM and look angles\nsmpdem = 'dem_smp.xyz';\n\n% getting the variables from the parms_aps file\nstamps_processed = getparm_aps('stamps_processed',1);\n\n%%% defaults for the weather models. If not applicable it will be changed below for the specific model.\nif strcmp(model_type,'narr')\n timelist_model = ['0000' ;'0300'; '0600' ; '0900'; '1200' ;'1500'; '1800' ;'2100'; '0000'];\n model_lag = 8*7; % days\nelse\n timelist_model= ['0000' ; '0600' ; '1200' ; '1800' ; '0000']; % the time interval the model is outputed\n model_lag = 0; % ? check lags\nend\nera_data_type = []; % the weather model data type for ERA only.\n\n\n%%% Updating specific weather model information\nif strcmpi(model_type,'era')\n weather_model_datapath = getparm_aps('era_datapath',1);\n era_data_type = getparm_aps('era_data_type'); % the datatype of the model either BADC or ERA\nelseif strcmpi(model_type,'merra') || strcmpi(model_type,'merra2')\n weather_model_datapath = getparm_aps('merra_datapath',1); \nelseif strcmpi(model_type,'narr') \n weather_model_datapath = getparm_aps('narr_datapath',1); \n\nelse\n error(['weather model type not supported, either: wrf, era, narr, merra for now'])\nend\n\nlambda = getparm_aps('lambda',1)*100; % radar wavelength in cm\ndemfile = getparm_aps('demfile',1);\ndemnull = getparm_aps('dem_null',1);\nUTC_sat = getparm_aps('UTC_sat',1);\nifgday_matfile = getparm_aps('ifgday_matfile',1);\nifgs_dates = load(ifgday_matfile);\n\n\n% loading the data\nif strcmp(stamps_processed,'y')\n dates = ifgs_dates.day;\n load psver\n fprintf('Stamps processed structure \\n')\nelse\n psver = 2;\n ifgs_dates = ifgs_dates.ifgday;\n dates = reshape(ifgs_dates,[],1);\n dates = unique(dates);\n dates = datenum(num2str(dates),'yyyymmdd');\nend\n\n% getting the dates\nn_dates = length(dates);\n\n%% Compute and resample DEM\n[dem,xmin,xmax,ymin,ymax,smpres,nncols,nnrows] = get_DEM;\n\n% the region which is cropped from the ERA data and used to make the interpolation.\n% Should be larger than the region to which the delay is computed\nlonmin = floor(xmin)-1;\nlonmax= ceil(xmax)+1;\nlatmin = floor(ymin)-1;\nlatmax = ceil(ymax)+1;\n\n% setting the maximum height of the DEM to limit the range at which ERA-I\n% needs to be interpolated to\nmaxdem = ceil(max(max(dem))/100)*100+50; % max height of dem in metres\n\nfprintf(['Interpolate to a maximum dem height of ', num2str(maxdem) ,' m\\n'])\n\n\n%% Compute based on Satellite pass which weather model outputs that will be used\n[time_before,time_after, date_before, date_after,f_before,f_after] = aps_weather_model_times(timelist_model,dates,UTC_sat,model_lag);\n\n%% generating a file \n[modelfile_before,modelfile_after] = aps_weather_model_filenames(model_type,time_before,time_after,date_before, date_after,weather_model_datapath);\n\n\n%% performing the calucluation for each date \nfor d = 1:n_dates\n \n % the save filenames\n outfile = [weather_model_datapath filesep date_before(d,:) filesep date_before(d,:) '_ZWD.xyz'];\n hydroutfile = [weather_model_datapath filesep date_before(d,:) filesep date_before(d,:) '_ZHD.xyz']; \n \n no_data = 0;\n for kk = 1:2\n if kk == 1\n file = modelfile_before(d,:);\n end\n if kk == 2\n file = modelfile_after(d,:);\n end\n \n \n % check\n if exist(file,'file')~=2\n no_data = no_data+1;\n else\n \n % loading the weather model data\n if strcmpi(model_type,'era')\n [ Temp,e,Geopot,P,longrid,latgrid,xx,yy,lon0360_flag] = aps_load_era(file,era_data_type) ;\n elseif strcmpi(model_type,'era5')\n [ Temp,e,Geopot,P,longrid,latgrid,xx,yy,lon0360_flag] = aps_load_era(file,era_data_type) ;\n elseif strcmpi(model_type,'merra') || strcmpi(model_type,'merra2')\n [ Temp,e,Geopot,P,longrid,latgrid,xx,yy,lon0360_flag] = aps_load_merra(file,model_type,coeff) ;\n elseif strcmpi(model_type,'narr')\n [ Temp,e,Geopot,P,longrid,latgrid,xx,yy,lon0360_flag] = aps_load_narr(file,model_type,coeff) ;\n end\n% longrid=longrid';latgrid=latgrid';\n % verify and cope with NAN's\n [Temp,e,Geopot,P,longrid,latgrid] = aps_weather_model_nan_check(Temp,e,Geopot,P,longrid,latgrid) ;\n\n % define weather model grid nodes\n latlist = reshape(latgrid(:,:,1),[],1);\n lonlist = reshape(longrid(:,:,1),[],1);\n xlist = reshape(xx,[],1);\n ylist = reshape(yy,[],1);\n\n % Limit weather model to those grid points around the user-defined InSAR box\n % Getting the weather model resolution\n lat_res = abs(diff(unique(latgrid)))*1.5;\n lat_res = lat_res(1);\n lon_res = abs(diff(unique(longrid)))*1.5;\n lon_res = lon_res(1);\n\n % make sure the weather model and the lonlat specified by user\n % is defined in the same way. Weatehr models can be [0 360]\n % degrees. User can be [-180 180] unlikely [0 360]\n if strcmpi(lon0360_flag,'y')\n % fprintf('This needs to be defined better and some checks are needed \\n')\n % not all pixels should be shifted.\n \n if xmin<0\n xmin= xmin+360; \n end\n if xmax<0\n xmax = xmax +360; \n end\n end\n\n % generation a plot\n if fig_test ==1 & d==1 & kk==1\n fontsize = 15;\n hfig = figure('name',[model_type ' weather model nodes and InSAR region'],'position', [ 200 243 610 603]);\n % for the legend generation\n plot(mean([xmin xmax]),mean([ymax ymin]),'wo','markeredgecolor','k','markerfacecolor','w','markersize',15)\n hold on\n plot(mean([xmin xmax]),mean([ymax ymin]),'r.')\n hold on\n plot(mean([xmin xmax]),mean([ymax ymin]),'r-','linewidth',2)\n\n imagesc([xmin xmax],[ymax ymin],dem) \n cc=colorbar;\n view(0,90)\n\n axis xy\n ylabel(cc,'Topography [m]','fontsize',fontsize)\n hold on\n plot(lonlist,latlist,'wo','markeredgecolor','k','markerfacecolor','w','markersize',15)\n hold on\n plot([xmin xmin xmax xmax xmin],[ymin ymax ymax ymin ymin],'r-','linewidth',2)\n\n title([model_type ' weather model nodes'],'fontsize',fontsize)\n set(gca,'fontsize',fontsize)\n axis equal\n axis tight \n\n legend('location','northoutside',[model_type ' weather model nodes'],['Used ' model_type ' weather model nodes'],'InSAR box')\n end\n\n % making the weather model grid slightly larger than the InSAR\n % bounding box. Will use the weather model resolution for this\n % to make sure an extra grid node is included.\n ix = find(ymin-lat_res<= latlist & latlist <= ymax+lat_res & xmin-lon_res<= lonlist & lonlist<= xmax+lon_res) ;\n xlist = xlist(ix);\n ylist = ylist(ix);\n latlist = latlist(ix);\n lonlist = lonlist(ix);\n numy = length(unique(latlist));\n numx = length(unique(lonlist));\n ulatlist = unique(latlist);\n ulonlist = unique(lonlist);\n uxlist = unique(xlist);\n uylist = unique(ylist);\n\n if fig_test ==1 & d==1 & kk==1\n figure(hfig)\n hold on\n plot(lonlist,latlist,'r.')\n xlim([xmin-4*lon_res xmax+4*lon_res])\n ylim([ymin-4*lat_res ymax+4*lat_res])\n str='';\n while ~strcmpi(str,'y') && ~strcmpi(str,'n') \n fprintf(['Do the red nodes extend (just) outside the red InSAR rectangle? \\n']) \n str = input('Continue? [y: for yes, n: no] \\n','s');\n end\n if strcmpi(str,'n')\n error('Check your lon lat crop, otherwize extend area of downlaoded weather model data.')\n end\n end\n \n clear lon_res lat_res ylist xlist %%%SSS 4/16\n\n % saving the information for support plotting \n eval([model_type '.' model_type '_lonlat =[lonlist latlist];']); % era.era_lonlat = [lonlist latlist];\n eval([model_type '.region =[[xmin xmin xmax xmax xmin]'' [ymin ymax ymax ymin ymin]''];']); % era.region = [[xmin xmin xmax xmax xmin]' [ymin ymax ymax ymin ymin]'];\n deminfo.xmin = xmin;\n deminfo.xmax = xmax;\n deminfo.ymax = ymax;\n deminfo.ymin = ymin;\n deminfo.dem = dem;\n eval([model_type '.deminfo =deminfo;']); % era.deminfo = deminfo;\n clear deminfo\n % checking if the file already exist. Yes append otherwiuze create it\n if exist('tca_support.mat','file')==2\n eval(['save(''tca_support.mat'',''-append'',''' model_type ''');']); % save('tca_support.mat','-append','era')\n else\n eval(['save(''tca_support.mat'',''' model_type ''');']); % save('tca_support.mat','era') \n end\n% if fig_test ==1 & d==1 & kk==1\n% if exist(['aps_' model_type],'dir')~=7\n% mkdir(['aps_' model_type]);\n% end\n% print(hfig,'-dpng',['aps_' model_type filesep model_type '_datapoints.png'])\n% print(hfig,'-depsc',['aps_' model_type filesep model_type '_datapoints.eps'])\n% end\n eval(['clear ' model_type]);\n \n\n % Convert Geopotential to Geopotential Height and then to Geometric Height\n g0 = 9.80665;\n % Calculate Geopotential Height, H\n H = Geopot./g0;\n\n % map of g with latitude\n g = 9.80616.*(1 - 0.002637.*cosd(2.*latgrid) + 0.0000059.*(cosd(2.*latgrid)).^2);\n % map of Re with latitude\n Rmax = 6378137; \n Rmin = 6356752;\n Re = sqrt(1./(((cosd(latgrid).^2)./Rmax^2) + ((sind(latgrid).^2)./Rmin^2)));\n\n % Calculate Geometric Height, Z\n Z = (H.*Re)./(g/g0.*Re - H);\n \n % Find middle of scene to work out glocal and Rlocal for use later\n midx = round(mean(uxlist));\n midy = round(mean(uylist));\n glocal = g(midy,midx,1);\n Rlocal = Re(midy,midx,1);\n\n cdslices = maxdem/vertres +1;\n cdstack = zeros(numy,numx,cdslices);\n cdstack_dry = zeros(numy,numx,cdslices);\n cdstack_wet = zeros(numy,numx,cdslices);\n\n XI=(0:zincr:zref)';\n gh = glocal.*(Rlocal./(Rlocal+XI)).^2; %gravity with height for XI height range\n\n % Interpolate Temp P and e from 0:20:15000 m\n % then integrate using trapz to estimate delay as function of height\n for i = 1:numx;\n for j = 1:numy;\n xn = uxlist(i);\n yn = uylist(j);\n\n %interpolate at res zincr before doing integration\n X=double(squeeze(Z(yn,xn,:)));\n Ye=double(squeeze(e(yn,xn,:)));\n YeI = interp1(X,Ye,XI,'spline')*100; %change from hPa to Pa\n\n YP=double(squeeze(P(yn,xn,:)));\n YPI = interp1(X,YP,XI,'spline')*100; %change from hPa to Pa\n\n YT=double(squeeze(Temp(yn,xn,:)));\n YTI = interp1(X,YT,XI,'spline');\n\n tmp1 = ((k2-(Rd*k1/Rv)).*YeI./YTI + k3.*YeI./(YTI.^2));\n Lw = (10^-6).*-1*flipud(cumtrapz(flipud(XI),flipud(tmp1)));\n % L is zenith delay one way in metres\n % tmp2 = k1.*YPI./YTI;\n %Ld = (10^-6).*-1*flipud(cumtrapz(flipud(XI),flipud(tmp2))); % This is using P/T expression (Hanssen, 2001)\n gm = glocal; \n Ld = (10^-6).*((k1*Rd/gm).*(YPI - YPI(zref/zincr +1))); % This is P0 expression (Hanssen, 2001)\n\n % Interpolate important part (i.e. total delay at elevations\n % less than maxdem) at high res i.e. vertres, and put in cdstack.\n cdI=(0:vertres:maxdem)';\n LdI=interp1(XI,Ld,cdI,'spline');\n LwI=interp1(XI,Lw,cdI,'spline');\n\n %cdstack(j,i,:) = LsI;\n cdstack_dry(j,i,:) = LdI;\n cdstack_wet(j,i,:) = LwI;\n \n if save_3D_delays==1 \n cdI3D=(0:100:max(XI))';\n LdI3D=interp1(XI,Ld,cdI3D,'spline');\n LwI3D=interp1(XI,Lw,cdI3D,'spline');\n\n %cdstack(j,i,:) = LsI;\n cdstack_dry3D(j,i,:) = LdI3D;\n cdstack_wet3D(j,i,:) = LwI3D;\n clear LdI3D LwI3D\n end\n end\n end\n clear uxlist uylist ulonlist ulatlist %%%SSS 4/16 \n\n % Interpolate each cdstack layer onto a grid given by the DEM extents\n % in UTM m.\n xsmpres = (xmax-xmin)/nncols;\n ysmpres = (ymax-ymin)/nnrows;\n [xi,yi] = meshgrid(xmin+0.5*xsmpres:xsmpres:xmax-0.5*xsmpres,ymin+0.5*ysmpres:ysmpres:ymax-0.5*ysmpres);\n\n ix_temp = diff(lonlist);\n ix_temp = find(ix_temp~=0);\n ix_temp = ix_temp(1);\n lonlist_matrix = reshape(lonlist,ix_temp,[]) ;\n latlist_matrix = reshape(latlist,ix_temp,[]) ;\n clear lonlist latlist %%%SSS 4/16\n \n % saving the outputs\n if save_3D_delays==1 \n if kk==1\n clear hgt lon lat dry1 dry2 wet1 dem_temp hgt_topo %%%SSS 4/16\n hgt = cdI3D;\n lon = [lonlist_matrix];\n lat = latlist_matrix;\n dry1 = cdstack_dry3D;\n wet1 = cdstack_wet3D;\n \n % also give the station topography\n dem_temp = dem;\n dem_temp(isnan(dem_temp))=0;\n hgt_topo = griddata(xi,yi,dem_temp,lon,lat,'linear'); \n clear dem_temp\n \n \n elseif kk==2\n clear dry2 wet2\n dry2 = cdstack_dry3D;\n wet2 = cdstack_wet3D;\n end\n end\n \n clear cdstack_interp_dry %%%SSS 4/16\n cdstack_interp_dry = zeros(nnrows,nncols,cdslices);\n parfor n = 1:cdslices\n newslice = interp2(lonlist_matrix,latlist_matrix,cdstack_dry(:,:,n),xi,yi,'linear'); \n cdstack_interp_dry(:,:,n)= flipud(newslice); % flipud due to ypositive downpage for matlab figs, and ypositive uppage for utmy\n end \n\n clear cdstack_interp_wet %%%SSS 4/16 \n cdstack_interp_wet = zeros(nnrows,nncols,cdslices);\n parfor n = 1:cdslices \n newslice = interp2(lonlist_matrix,latlist_matrix,cdstack_wet(:,:,n),xi,yi,'linear'); \n cdstack_interp_wet(:,:,n)= flipud(newslice); % flipud due to ypositive downpage for matlab figs, and ypositive uppage for utmy\n end\n clear lonlist_matrix latlist_matrix %%%SSS 4/16\n % keeping the coordinates in the same grid as the data\n xi = flipud(xi);\n yi = flipud(yi);\n\n\n % Pull out delays from cdstack layers that match dem heights\n clear wetcorrection hydrcorrection rounddem %%%SSS 4/16\n wetcorrection = ones(nnrows,nncols);\n hydrcorrection = ones(nnrows,nncols);\n rounddem = round(dem/vertres);\n rounddem(dem < 0)=0;\n\n % cope with the case that NaN are present. This can be sea-level\n rounddem(isnan(dem))=0;\n\n for i=1:nnrows\n for j=1:nncols\n wetcorrection(i,j) = cdstack_interp_wet(i,j,rounddem(i,j)+1);\n end\n end\n\n for i=1:nnrows\n for j=1:nncols\n hydrcorrection(i,j) = cdstack_interp_dry(i,j,rounddem(i,j)+1);\n end\n end\n\n if kk==1\n wetcorrection1 = wetcorrection;\n drycorrection1 = hydrcorrection;\n end\n if kk==2\n wetcorrection2 = wetcorrection;\n drycorrection2 = hydrcorrection;\n end\n clear wetcorrection hydrcorrection\n\n end\n end\n\n if sum(no_data)==0\n % note that this is a one way Zenith delay and not a slant delay. \n % Units are in cm\n\n % saving individual estimates based on the time-stamp\n outfile_wet_before = [weather_model_datapath filesep date_before(d,:) filesep date_before(d,:) '_ZWD_before.xyz'];\n outfile_wet_after = [weather_model_datapath filesep date_before(d,:) filesep date_before(d,:) '_ZWD_after.xyz'];\n outfile_dry_before = [weather_model_datapath filesep date_before(d,:) filesep date_before(d,:) '_ZHD_before.xyz'];\n outfile_dry_after = [weather_model_datapath filesep date_before(d,:) filesep date_before(d,:) '_ZHD_after.xyz'];\n\n\n fidwet_before = fopen(outfile_wet_before,'w');\n data_write = [reshape(xi,[],1) reshape(yi,[],1) reshape(wetcorrection1,[],1)]';\n tally = fwrite(fidwet_before,data_write,'double');\n fclose(fidwet_before);\n clear data_write tally %%%SSS 4/16\n fidwet_after = fopen(outfile_wet_after,'w');\n data_write = [reshape(xi,[],1) reshape(yi,[],1) reshape(wetcorrection2,[],1)]';\n tally = fwrite(fidwet_after,data_write,'double');\n fclose(fidwet_after);\n clear data_write tally %%%SSS 4/16\n fiddry_before = fopen(outfile_dry_before,'w');\n data_write = [reshape(xi,[],1) reshape(yi,[],1) reshape(drycorrection1,[],1)]';\n tally = fwrite(fiddry_before,data_write,'double');\n fclose(fiddry_before); \n clear data_write tally %%%SSS 4/16\n fiddry_after = fopen(outfile_dry_after,'w');\n data_write = [reshape(xi,[],1) reshape(yi,[],1) reshape(drycorrection2,[],1)]';\n tally = fwrite(fiddry_after,data_write,'double');\n fclose(fiddry_after);\n clear data_write tally %%%SSS 4/16\n\n % saving the outputs\n if save_3D_delays==1 \n wet = wet1*f_before(d) + wet2*f_after;\n dry = dry1*f_before(d) + dry2*f_after;\n save([weather_model_datapath filesep date_before(d,:) filesep date_before(d,:) '_3D.mat'],'dry','wet','hgt','lon','lat','hgt_topo')\n clear wet dry hgt dry1 dry2 wet1 wet2 %%%SSS 4/16\n end\n \n % Output wet correction\n wetcorrection = wetcorrection1*f_before(d) + wetcorrection2*f_after(d);\n clear wetcorrection1 wetcorrection2\n wetcorrection = wetcorrection*100; % delay in [cm]\n fid = fopen(outfile,'w');\n data_write = [reshape(xi,[],1) reshape(yi,[],1) reshape(wetcorrection,[],1)]';\n tally = fwrite(fid,data_write,'double');\n fclose(fid);\n clear data_write tally wetcorrection %%%SSS 4/16\n\n % Output hydrostatic correction\n hydrcorrection = drycorrection1*f_before(d) + drycorrection2*f_after(d);\n clear drycorrection1 drycorrection2\n hydrcorrection = hydrcorrection*100; % delay in [cm]\n fid = fopen(hydroutfile,'w');\n data_write = [reshape(xi,[],1) reshape(yi,[],1) reshape(hydrcorrection,[],1)]';\n tally = fwrite(fid,data_write,'double');\n fclose(fid);\n clear data_write tally hydrcorrection %%%SSS 4/16\n\n fprintf([num2str(d) ' completed out of ' num2str(n_dates) '\\n' ])\n \n else\n fprintf([num2str(d) ' completed out of ' num2str(n_dates) ' (NO DATA)\\n' ])\n end\nend\n\n\n", "meta": {"author": "dbekaert", "repo": "TRAIN", "sha": "6c93feb95ae95eaf4c8468e89ec0b8325eac946f", "save_path": "github-repos/MATLAB/dbekaert-TRAIN", "path": "github-repos/MATLAB/dbekaert-TRAIN/TRAIN-6c93feb95ae95eaf4c8468e89ec0b8325eac946f/matlab/aps_weather_model_SAR.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6757646010190475, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.32205565775484185}} {"text": "function [sicdmeta] = pfa_sicd_meta(meta, nbdata, ifp_params)\n%PFA_SICD_META Creates a SICD metadata structure for an image created by pfa_file.m\n%\n% Inputs:\n% meta: Collection narrowband data. This is the same\n% structure returned by the get_meta function for a\n% object returned by open_ph_reader.\n% nbdata: CPHD-style per-pulse narrowband data. This is the\n% same structure returned as the second return parameter\n% of the read_cphd function.\n% ifp_params: Structure of some additional parameters computed\n% during image formation.\n%\n% Outputs:\n% sicdmeta: Image formation and collection information in a\n% structure compatible with the SICD writer. \n%\n% Authors: Wade Schwartzkopf and Tom Krauss, NGA/IDT\n%\n% //////////////////////////////////////////\n% /// CLASSIFICATION: UNCLASSIFIED ///\n% //////////////////////////////////////////\n\n% Create SICD meatdata structure\nsicdmeta = meta2sicd_cphdx(meta,nbdata,ifp_params.channel);\n\n% Image Creation\nsicdmeta.ImageCreation.DateTime = now();\nsicdmeta.ImageCreation.Profile = 'pfa_sicd_meta.m';\n\n% ImageData\nsicdmeta.ImageData.PixelType = 'RE32F_IM32F';\nsicdmeta.ImageData.NumRows = ifp_params.image_size_pixels(1);\nsicdmeta.ImageData.NumCols = ifp_params.image_size_pixels(2);\nsicdmeta.ImageData.FirstRow = 0;\nsicdmeta.ImageData.FirstCol = 0;\nsicdmeta.ImageData.FullImage.NumRows = sicdmeta.ImageData.NumRows;\nsicdmeta.ImageData.FullImage.NumCols = sicdmeta.ImageData.NumCols;\nsicdmeta.ImageData.SCPPixel.Row = floor(sicdmeta.ImageData.NumRows/2);\nsicdmeta.ImageData.SCPPixel.Col = floor(sicdmeta.ImageData.NumCols/2);\n\n% GeoData\nsicdmeta.GeoData.EarthModel='WGS_84';\ncenter=mean(nbdata.SRPPos); % Current PFA code only forms to this point\nsicdmeta.GeoData.SCP.ECF.X=mean(center(1));\nsicdmeta.GeoData.SCP.ECF.Y=mean(center(2));\nsicdmeta.GeoData.SCP.ECF.Z=mean(center(3));\nscp_lla = ecf_to_geodetic([sicdmeta.GeoData.SCP.ECF.X sicdmeta.GeoData.SCP.ECF.Y sicdmeta.GeoData.SCP.ECF.Z]);\nsicdmeta.GeoData.SCP.LLH.Lat=scp_lla(1);\nsicdmeta.GeoData.SCP.LLH.Lon=scp_lla(2);\nsicdmeta.GeoData.SCP.LLH.HAE=scp_lla(3);\n% Corner coordinates will be popupated later in derived_sicd_fields call\n\n% Grid\nsicdmeta.Grid.ImagePlane = 'SLANT';\nsicdmeta.Grid.Type = 'RGAZIM';\nsicdmeta.Grid.Row.Sgn=-1; % We have done an IFFT in PFA\nsicdmeta.Grid.Row.ImpRespBW = diff(ifp_params.k_v_bounds);\nsicdmeta.Grid.Row.ImpRespWid = 0.886/sicdmeta.Grid.Row.ImpRespBW;\nsicdmeta.Grid.Row.SS = 1/(ifp_params.sample_rate*sicdmeta.Grid.Row.ImpRespBW);\nsicdmeta.Grid.Row.KCtr = mean(ifp_params.k_v_bounds);\nsicdmeta.Grid.Row.DeltaKCOAPoly = 0;\nsicdmeta.Grid.Row.WgtType.WindowName = 'UNIFORM';\nsicdmeta.Grid.Col.Sgn=-1; % We have done an IFFT in PFA\nsicdmeta.Grid.Col.ImpRespBW = diff(ifp_params.k_u_bounds);\nsicdmeta.Grid.Col.ImpRespWid = 0.886/sicdmeta.Grid.Col.ImpRespBW;\nsicdmeta.Grid.Col.SS = 1/(ifp_params.sample_rate*sicdmeta.Grid.Col.ImpRespBW);\nsicdmeta.Grid.Col.KCtr = 0;\nsicdmeta.Grid.Col.WgtType.WindowName = 'UNIFORM';\nsicdmeta.Grid.Col.DeltaKCOAPoly = 0;\n\n% ImageFormation\nsicdmeta.ImageFormation.RcvChanProc.NumChanProc = 1; % This function only handles single-channel data\nsicdmeta.ImageFormation.RcvChanProc.ChanIndex = ifp_params.channel;\nsicdmeta.ImageFormation.ImageFormAlgo = 'PFA';\nsicdmeta.ImageFormation.TStartProc = nbdata.TxTime(1);\nsicdmeta.ImageFormation.TEndProc = nbdata.TxTime(end);\nif isfield(meta.Channel,'Parameters') && ...\n isfield(meta.Channel.Parameters(ifp_params.channel),'Polarization') && ...\n all(isfield(meta.Channel.Parameters(ifp_params.channel).Polarization,{'TxPol','RcvPol'}))\n sicdmeta.ImageFormation.TxRcvPolarizationProc = ...\n [meta.Channel.Parameters(ifp_params.channel).Polarization.TxPol ':' ...\n meta.Channel.Parameters(ifp_params.channel).Polarization.RcvPol];\nend\nsicdmeta.ImageFormation.TxFrequencyProc.MinProc = ...\n min(nbdata.SC0 + (nbdata.SCSS * double(min(ifp_params.sample_range)-1)));\nsicdmeta.ImageFormation.TxFrequencyProc.MaxProc = ...\n max(nbdata.SC0 + (nbdata.SCSS * double(max(ifp_params.sample_range)-1)));\nsicdmeta.ImageFormation.ImageFormAlgo = 'PFA';\nsicdmeta.ImageFormation.STBeamComp = 'NO';\nsicdmeta.ImageFormation.ImageBeamComp = 'NO';\nsicdmeta.ImageFormation.AzAutofocus = 'NO';\nsicdmeta.ImageFormation.RgAutofocus = 'NO';\n\n% SCPCOA\nsicdmeta.SCPCOA.SCPTime = nbdata.TxTime(ifp_params.ref_pulse_index);\n\n% Timeline\nif isfield(meta,'Global') && isfield(meta.Global, 'Timeline') && ...\n all(isfield(meta.Global.Timeline, {'TxTime1', 'TxTime2'}))\n sicdmeta.Timeline.CollectDuration = meta.Global.Timeline.TxTime2 - ...\n meta.Global.Timeline.TxTime1;\nelse\n sicdmeta.Timeline.CollectDuration = nbdata.TxTime(end) - nbdata.TxTime(1);\nend\n\n% PFA\nsicdmeta.PFA.FPN = struct('X',ifp_params.fpn(1),'Y',ifp_params.fpn(2),'Z',ifp_params.fpn(3));\nsicdmeta.PFA.IPN = struct('X',ifp_params.ipn(1),'Y',ifp_params.ipn(2),'Z',ifp_params.ipn(3));\nsicdmeta.PFA.PolarAngRefTime = nbdata.TxTime(ifp_params.ref_pulse_index);\n% This often givens a \"badly conditioned\" polynomial warning with fitting a\n% polynomial in ECF space. Ignore.\nold_state = warning('off','MATLAB:polyfit:RepeatedPointsOrRescale');\nsicdmeta.PFA.PolarAngPoly = fliplr( polyfit(nbdata.TxTime, ifp_params.k_a, 5) ).';\nsicdmeta.PFA.SpatialFreqSFPoly = fliplr( polyfit(ifp_params.k_a, ifp_params.k_sf, 5) ).';\nwarning(old_state);\nsicdmeta.PFA.Krg1 = ifp_params.k_v_bounds(1);\nsicdmeta.PFA.Krg2 = ifp_params.k_v_bounds(2);\nsicdmeta.PFA.Kaz1 = ifp_params.k_u_bounds(1);\nsicdmeta.PFA.Kaz2 = ifp_params.k_u_bounds(2);\n\nsicdmeta = derived_sicd_fields(sicdmeta); % Computes many derived fields\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/Processing/IFP/PFA/pfa_sicd_meta.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7549149978955811, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.32183656414082945}} {"text": "% ==============================================================================\n%\n% Software License Agreement (BSD License)\n% Copyright (c) 2019\n% (www.aimlab.wpi.edu)\n%\n% All rights reserved.\n%\n% Redistribution and use in source and binary forms, with or without\n% modification, are permitted provided that the following conditions\n% are met:\n%\n% * Redistributions of source code must retain the above copyright\n% notice, this list of conditions and the following disclaimer.\n%\n% * Redistributions in binary form must reproduce the above\n% copyright notice, this list of conditions and the following\n% disclaimer in the documentation and/or other materials provided\n% with the distribution.\n%\n% * Neither the name of authors nor the names of its contributors may\n% be used to endorse or promote products derived from this software\n% without specific prior written permission.\n%\n% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n% \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n% LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n% FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n% COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n% INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n% BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n% LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n% CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n% LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n% ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n% POSSIBILITY OF SUCH DAMAGE.\n%\n% \\author: \n% \\author: \n% \\author: Adnan Munawar\n% \\version: 0.1$\n% ==============================================================================\n\nfunction [its,sizePath,run_time] = RRTextend3D(dim,segmentLength,random_world,show_output)\n% dim = 2;\n% radius =0;\n% segmentLength = 5;\n% random_world = 0;\n% n_its = 1000;\n% standard length of path segments\nif dim ==2\n start_cord = [5,5];\n goal_cord = [95,95];\n \nelse\n \n start_cord = [5,5,5];\n goal_cord = [95,95,95];\nend\n\n\n\n% create random world\nSize = 100;\nNumObstacles = 100;\n\nif random_world ==1\n world = createWorld(NumObstacles,ones(1,dim)*Size,zeros(1,dim),dim);\nelse\n [world NumObstacles] = createKnownWorld(ones(1,dim)*Size,[0;0;0],dim);\nend\n% randomly select start and end nodes\n%start_node = generateRandomNode(world,dim)\n%end_node = generateRandomNode(world,dim)\nstart_node = [start_cord,0,0,0];\nend_node = [goal_cord,0,0,0];\n% establish tree starting with the start node\ntree = start_node;\n\na = clock;\n\n% check to see if start_node connects directly to end_node\nif ( (norm(start_node(1:dim)-end_node(1:dim))world.endcorner(i))|(node(i)1\n size_near = size(near_idx,1);\n \n for i = 1:size_near\n if collision(new_node, tree(near_idx(i),:), world,dim)==0\n \n cost_near = tree(near_idx(i),dim+2)+line_cost(tree(near_idx(i),:),new_point,dim);\n \n if cost_near < min_cost\n min_cost = cost_near;\n min_parent_idx = near_idx(i);\n end\n \n end\n end\n end\n \n new_node = [new_point, 0 , min_cost, min_parent_idx];\n new_tree = [tree; new_node];\n new_node_idx = size(new_tree,1);\n \n if size(near_idx,1)>1\n reduced_idx = near_idx;\n for j = 1:size(reduced_idx,1)\n near_cost = new_tree(reduced_idx(j),dim+2);\n lcost = line_cost(new_tree(reduced_idx(j),:),new_point,dim);\n if near_cost > min_cost + lcost ...\n && collision(new_tree(reduced_idx(j),:),new_node,world,dim)\n before = new_tree(reduced_idx(j),dim+3)\n new_tree(reduced_idx(j),dim+3) = new_node_idx;\n after = new_tree(reduced_idx(j),dim+3)\n end\n \n end\n end\n flag1=1;\n end\nend\n\n\nif flag_chk == 0\n % check to see if new node connects directly to end_node\n if ( (norm(new_node(1:dim)-end_node(1:dim))1,\n parent_node = tree(parent_node,dim+3);\n path = [tree(parent_node,:); path];\nend\n\nend\n\n\nfunction plotExpandedTree(world,tree,dim)\nind = size(tree,1);\nwhile ind>0\n branch = [];\n node = tree(ind,:);\n branch = [ branch ; node ];\n parent_node = node(dim+3);\n while parent_node > 1\n cur_parent = parent_node;\n branch = [branch; tree(parent_node,:)];\n parent_node = tree(parent_node,dim+3);\n end\n ind = ind - 1;\n \n if dim == 2\n X = branch(:,1);\n Y = branch(:,2);\n \n p = plot(X,Y);\n set(p,'Color','r','LineWidth',0.5,'Marker','.','MarkerEdgeColor','g');\n hold on;\n \n elseif dim == 3\n X = branch(:,1);\n Y = branch(:,2);\n Z = branch(:,3);\n \n p = plot3(X,Y,Z);\n set(p,'Color','r','LineWidth',0.5,'Marker','.','MarkerEdgeColor','g');\n hold on;\n end\nend\nend\n\n\n\n\nfunction plotWorld(world,path,dim)\n% the first element is the north coordinate\n% the second element is the south coordinate\nif dim ==2\n \n N = 10;\n th = 0:2*pi/N:2*pi;\n axis([world.origincorner(1),world.endcorner(1),...\n world.origincorner(2), world.endcorner(2)]);\n hold on\n \n for i=1:world.NumObstacles,\n X = world.radius(i)*sin(th) + world.cx(i);\n Y = world.radius(i)*cos(th) + world.cy(i);\n fill(X,Y,'blue');\n end\n \n X = path(:,1);\n Y = path(:,2);\n p = plot(X,Y);\n \nelseif dim ==3\n axis([world.origincorner(1),world.endcorner(1),...\n world.origincorner(2), world.endcorner(2),...\n world.origincorner(3), world.endcorner(3)]);\n hold on\n \n for i=1:world.NumObstacles,\n [X Y Z] = sphere(10);\n X = (X*world.radius(i));\n Y = (Y*world.radius(i));\n Z = (Z*world.radius(i));\n surf(X+world.cx(i),Y+world.cy(i),Z+world.cz(i));\n colormap([0.5 0.2 0.3]);\n end\n \n X = path(:,1);\n Y = path(:,2);\n Z = path(:,3);\n p = plot3(X,Y,Z);\nend\nset(p,'Color','black','LineWidth',3)\nxlabel('X axis');\nylabel('Y axis');\nzlabel('Z axis');\ntitle('RRT Extend Algorithm');\nend\n", "meta": {"author": "adnanmunawar", "repo": "matlab-rrt-variants", "sha": "47b2ec61b8c444a27b7ac58f7c79c1279aff5187", "save_path": "github-repos/MATLAB/adnanmunawar-matlab-rrt-variants", "path": "github-repos/MATLAB/adnanmunawar-matlab-rrt-variants/matlab-rrt-variants-47b2ec61b8c444a27b7ac58f7c79c1279aff5187/RRTextend3D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5926665855647395, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.32173692846631297}} {"text": "%This Matlab script can be used to reproduce Figure 7.18 in the monograph:\n%\n%Emil Bjornson, Jakob Hoydis and Luca Sanguinetti (2017), \n%\"Massive MIMO Networks: Spectral, Energy, and Hardware Efficiency\", \n%Foundations and Trends in Signal Processing: Vol. 11, No. 3-4, \n%pp. 154-655. DOI: 10.1561/2000000093.\n%\n%For further information, visit: https://www.massivemimobook.com\n%\n%This is version 1.0 (Last edited: 2017-11-04)\n%\n%License: This code is licensed under the GPLv2 license. If you in any way\n%use this code for research that results in publications, please cite our\n%monograph as described above.\n\n\n%Empty workspace and close figures\nclose all;\nclear;\n\n\n%% Define parameters\nM_max = 15; % number of antenna columns/rows\nd_H = 1/2; % horizontal antenna spacing\nh_BS = 25; % height of the antenna array\nh_UE = 1.5; % height of the UE\nCellRadius = 500; % cell radius\nK = 500; % number of UEs\nfc = 2.6e9; % center frequency\nbw = 20e6; % bandwidth\nN = 1024; % number of subcarriers\n\n% Compute derived parameters\nh = h_BS - h_UE; % effective height\nd_V = 1/2; % vertical antenna spacing\nd = d_V;\n\n%Simulate new channel reponses or load existing results (the latter is the\n%preset)\nsimulate = false;\n\n\n%% Simulate channels\nif (simulate)\n % Draw random positions\n A = rand(1,K)*CellRadius^2;\n B = rand(1,K)*pi*2/3 - pi/3;\n POS = repmat(sqrt(A)',[1,2]).* [cos(B); sin(B)]'; %UE positions uniformly distributed on a disc of radius R\n \n % Create a new layout\n s = simulation_parameters; % Create object with general parameters\n s.center_frequency = fc;\n s.sample_density = 1;\n s.use_absolute_delays = 1;\n \n l = layout(s); % Create new layout from general parameters\n l.no_rx = K; % Generate KUEs\n l.rx_array.generate('omni'); % use omnidirectional antennas at the UEs\n \n l.randomize_rx_positions(CellRadius, h_UE, h_UE, 1); % randomly distribute UEs within a disc of radius R and height 1.5m\n for k=1:K\n l.rx_position(:,k) = [POS(k,1); POS(k,2); h_UE]; % use the same positions as for the other simulations\n end\n \n for i=1:l.no_rx % for each receiver\n l.track(i).generate('linear',0,0) % define a linear track consiting of only one position\n l.track(i).scenario = '3GPP_3D_UMa_LOS'; % select the Urban Macrocell NLOS scenario for the link\n end\n \n % Simulate channel for planar array\n l.tx_array.generate('3gpp-3d', 1, M_max, M_max, fc, 1, 0, d);\n [h_channel, h_parset, h_cb] = l.get_channels();\n h_freq = h_channel.fr(bw,N);\n H_plan = zeros(K,M_max^2, N);\n for k=1:K\n H_plan(k,:,:) = squeeze(h_freq{k});\n end\n \n % Simulate channel for horizontal array\n l.tx_array.generate('3gpp-3d', 1, 1, M_max^2, fc, 1, 0, d);\n [h_channel, h_parset, h_cb] = l.get_channels();\n h_freq = h_channel.fr(bw,N);\n H_hori = zeros(K,M_max^2, N);\n for k=1:K\n H_hori(k,:,:) = squeeze(h_freq{k});\n end\n \n % Simulate channel for vertical array\n l.tx_array.generate('3gpp-3d', 1, M_max^2, 1, fc, 1, 0, d);\n [h_channel, h_parset, h_cb] = l.get_channels();\n h_freq = h_channel.fr(bw,N);\n H_vert = zeros(K,M_max^2, N);\n for k=1:K\n H_vert(k,:,:) = squeeze(h_freq{k});\n end\nend\n\n%% Compute channel orthogonality\nif (~simulate)\n load('section7_orthogonality_3GPP.mat')\nelse\n \n IT = 100000;\n COR_3GPP_PLAN = zeros(1,M_max);\n COR_3GPP_HORI = zeros(1,M_max);\n COR_3GPP_VERT = zeros(1,M_max);\n \n for it=1:IT\n \n %Output simulation progress\n disp([num2str(it) ' iterations out of ' num2str(IT)]);\n \n % Draw random position indices\n posInd = randperm(K,2);\n \n % For all antenna size\n for m = 1:M_max\n M_H = m;\n M_V = m;\n M = M_H*M_V;\n indices = repmat((0:M_H-1)*M_max + 1, [M_V,1]) + repmat((0:M_V-1)', [1,M_H]);\n indices = indices(:);\n for n=1:N\n % Planar array\n h1 = H_plan(posInd(1),indices,n);\n h2 = H_plan(posInd(2),indices,n);\n COR_3GPP_PLAN(m) = abs(h1*h2')^2 / (norm(h1)^2*norm(h2)^2)/IT/N + COR_3GPP_PLAN(m);\n \n % Horizontal array\n h1 = H_hori(posInd(1),1:m^2,n);\n h2 = H_hori(posInd(2),1:m^2,n);\n COR_3GPP_HORI(m) = abs(h1*h2')^2 / (norm(h1)^2*norm(h2)^2)/IT/N + COR_3GPP_HORI(m);\n \n % Vertical array\n h1 = H_vert(posInd(1),1:m^2,n);\n h2 = H_vert(posInd(2),1:m^2,n);\n COR_3GPP_VERT(m) = abs(h1*h2')^2 / (norm(h1)^2*norm(h2)^2)/IT/N + COR_3GPP_VERT(m);\n end\n end\n end\nend\n\n\n%% Load channel measurements\nhor_out=load('section7_measurement_horizontal.mat');\nvert_out=load('section7_measurement_vertical.mat');\nplanar_square = load('section7_measurement_planar.mat');\n\nx_measured=(1:8).^2;\n\n%Compute average UE correlation\nCOR_MEAS_HORI = mean(hor_out.crossco).^2;\nCOR_MEAS_PLAN = mean(planar_square.crossco).^2;\nCOR_MEAS_VERT = mean(vert_out.crossco).^2;\n\n\n%% Plot the simulation results\nfigure;\nhold on; box on;\n\nxvals = (1:M_max).^2;\n\nplot(xvals, COR_3GPP_VERT, 'LineWidth', 1, 'Color', 'k', 'LineStyle', '-', 'Marker', 'x');\nplot(x_measured, COR_MEAS_VERT(x_measured), 'LineWidth', 1, 'Color', 'k', 'LineStyle', '--', 'Marker', 'x');\n\nplot(xvals, COR_3GPP_PLAN, 'LineWidth', 1, 'Color', 'b', 'LineStyle', '-', 'Marker', 'o');\nplot(x_measured, COR_MEAS_PLAN, 'LineWidth', 1, 'Color', 'b', 'LineStyle', '--', 'Marker', 'o');\n\nplot(x_measured, COR_MEAS_HORI(x_measured), 'LineWidth', 1, 'Color', 'r', 'LineStyle', '--','Marker', 'square');\nplot(xvals, COR_3GPP_HORI, 'LineWidth', 1, 'Color', 'r', 'LineStyle', '-','Marker', 'square');\n\nCOR_IID = 1./xvals;\nplot(xvals, COR_IID, 'LineWidth', 1, 'Color', 'k', 'LineStyle', '-.');\n\nlegend({'3GPP Vertical', 'Meas. Vertical', '3GPP Planar', 'Meas. Planar', 'Meas. Horizontal', '3GPP Horizontal', 'i.i.d.'}, 'location', 'southwest');\nset(gca, 'XScale', 'log', 'YScale', 'log');\nxlabel('Number of antennas (M)');\nylabel('Average UE correlation');\nset(gca,'xtick',[1,4,9,16,25,36,49,64,121,225]);\nxlim([1,M_max^2]);\nylim([COR_IID(end), 1]);\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_figure18.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.321382703275402}} {"text": "function [g, gdata, gprior] = gp_g(w, gp, x, y, varargin)\n%GP_G Evaluate the gradient of energy (GP_E) for Gaussian Process\n%\n% Description\n% G = GP_G(W, GP, X, Y, OPTIONS) takes a full GP parameter\n% vector W, GP structure GP, a matrix X of input vectors and a\n% matrix Y of target vectors, and evaluates the gradient G of\n% the energy function (gp_e). Each row of X corresponds to one\n% input vector and each row of Y corresponds to one target\n% vector.\n%\n% [G, GDATA, GPRIOR] = GP_G(W, GP, X, Y, OPTIONS) also returns\n% separately the data and prior contributions to the gradient.\n%\n% OPTIONS is optional parameter-value pair\n% z - optional observed quantity in triplet (x_i,y_i,z_i)\n% Some likelihoods may use this. For example, in case of\n% Poisson likelihood we have z_i=E_i, that is, expected\n% value for ith case.\n%\n% See also\n% GP_E, GP_PAK, GP_UNPAK, GPCF_*\n%\n% Copyright (c) 2007-2011 Jarno Vanhatalo\n% Copyright (c) 2010 Aki Vehtari\n% Copyright (c) 2010 Heikki Peura\n% Copyright (c) 2014 Arno Solin and Jukka Koskenranta\n\n% This software is distributed under the GNU General Public\n% License (version 3 or later); please refer to the file\n% License.txt, included with the software, for details.\n\nif isfield(gp,'latent_method') && ~strcmp(gp.latent_method,'MCMC')\n % use an inference specific method\n fh_g = gp.fh.g;\n switch nargout\n case {0 1}\n [g] = fh_g(w, gp, x, y, varargin{:});\n case 2\n [g, gdata] = fh_g(w, gp, x, y, varargin{:});\n case 3\n [g, gdata, gprior] = fh_g(w, gp, x, y, varargin{:});\n end\n return\nend\n\nip=inputParser;\nip.FunctionName = 'GP_G';\nip.addRequired('w', @(x) isvector(x) && isreal(x));\nip.addRequired('gp',@isstruct);\nip.addRequired('x', @(x) ~isempty(x) && isreal(x) && all(isfinite(x(:))))\nip.addRequired('y', @(x) ~isempty(x) && isreal(x) && all(isfinite(x(:))))\nip.addParamValue('z', [], @(x) isreal(x) && all(isfinite(x(:))))\nip.parse(w, gp, x, y, varargin{:});\nz=ip.Results.z;\nif ~all(isfinite(w(:)));\n % instead of stopping to error, return NaN\n g=NaN;\n gdata = NaN;\n gprior = NaN;\n return;\nend\n\n% unpak the parameters\ngp=gp_unpak(gp, w);\n[tmp,tmp,hier]=gp_pak(gp);\nncf = length(gp.cf);\nif isfield(gp.lik, 'nondiagW')\n % Likelihoods with non-diagonal Hessian\n switch gp.lik.type\n case {'LGP', 'LGPC'}\n % Do nothing\n case {'Softmax', 'Multinom'}\n n=size(x,1);\n nout=size(y(:),1)./n;\n % [n,nout]=size(y);\n nl=cumsum([0 repmat(n,1,nout)]);\n otherwise\n n=size(x,1);\n nout=length(gp.comp_cf);\n \n % Help indices for latent processes\n if ~isfield(gp.lik, 'xtime')\n nl=[0 repmat(n,1,nout)];\n else\n xtime=gp.lik.xtime;\n ntime=size(xtime,1);\n nl=[0 ntime n];\n end\n nl=cumsum(nl);\n end\n if isfield(gp, 'comp_cf') % own covariance for each ouput component\n multicf = true;\n if length(gp.comp_cf) ~= nout\n error('GP2_G: the number of component vectors in gp.comp_cf must be the same as number of outputs.')\n end\n else\n multicf = false;\n end\nelse\n n=size(x,1);\nend\n\ng = [];\ngdata = [];\ngprior = [];\n\nif isfield(gp,'savememory') && gp.savememory\n savememory=1;\nelse\n savememory=0;\nend\n\nswitch gp.type\n case 'FULL'\n % ============================================================\n % FULL\n % ============================================================\n \n if ~isfield(gp.lik, 'nondiagW') || ismember(gp.lik.type, {'LGP' 'LGPC'})\n % Evaluate covariance\n if isfield(gp, 'lik_mono')\n [K,C] = gp_dtrcov(gp, x, gp.xv);\n % if isequal(gp.lik.type, 'Gaussian')\n % % Condition the derivatives on the observations\n % cc=C(size(x,1)+1:end,size(x,1)+1:end);\n % cy=C(size(x,1)+1:end,1:size(x,1));\n % cyy=C(1:size(x,1),1:size(x,1));\n % C=cc - cy*(cyy\\cy');\n % %C=0.5.*(C+C')+1e-10.*eye(size(C));\n % meany=cy*(cyy\\y(1:n));\n % y=(y(n+1:end)-meany);\n % n=length(y);\n % end\n else\n [~, C] = gp_trcov(gp, x);\n end\n \n \n if issparse(C)\n % evaluate the sparse inverse\n [LD, notpositivedefinite] = ldlchol(C);\n invC = spinv(LD,1);\n if notpositivedefinite\n % instead of stopping to chol error, return NaN\n g=NaN;\n gdata = NaN;\n gprior = NaN;\n return;\n end\n if ~isfield(gp,'meanf')\n b = ldlsolve(LD,y);\n else\n [invNM invAt HinvC]=mean_gf(gp,x,C,LD,[],[],y,'gaussian');\n end\n else\n % evaluate the full inverse\n ws1=warning('off','MATLAB:nearlySingularMatrix');\n ws2=warning('off','MATLAB:SingularMatrix');\n invC = inv(C);\n if ~isfield(gp,'meanf')\n b = C\\y;\n else\n [invNM invAt HinvC]=mean_gf(gp,x,C,invC,[],[],y,'gaussian');\n if isnan(invNM)\n g=NaN;gdata=NaN;gprior=NaN;\n return\n end\n end\n warning(ws1);\n warning(ws2);\n end\n else\n b = zeros(nl(end),1);\n y=y(:);\n \n switch gp.lik.type\n case 'Coxph'\n % In Cox-Ph, latent processes have different inputs so stacking in invC\n % is not possible.\n invC = zeros(nl(end),nl(end));\n if multicf\n [tmp, C] = gp_trcov(gp, xtime, gp.comp_cf{1});\n invC(1+nl(1):nl(2),1+nl(1):nl(2)) = inv(C);\n b(nl(1)+1:nl(2)) = C\\y(nl(1)+1:nl(2));\n [tmp, C] = gp_trcov(gp, x, gp.comp_cf{2});\n invC(1+nl(2):nl(3),1+nl(2):nl(3)) = inv(C);\n b(1+nl(2):nl(3)) = C\\y(1+nl(2):nl(3));\n else\n error('Specify covariance function for time process and input process, when using Cox-Ph likelihood');\n end\n otherwise\n invC = zeros(n,n,nout);\n if multicf\n for i1=1:nout\n [tmp, C] = gp_trcov(gp, x, gp.comp_cf{i1});\n invC(:,:,i1) = inv(C);\n b(1+nl(i1):nl(i1+1)) = C\\y(1+nl(i1):nl(i1+1));\n % b(:,i1) = C\\y(:,i1);\n end\n else\n [tmp, C] = gp_trcov(gp, x);\n invCtmp = inv(C);\n for i1=1:nout\n invC(:,:,i1) = invCtmp;\n b(1+nl(i1):nl(i1+1)) = C\\y(1+nl(i1):nl(i1+1));\n % b(:,i1) = C\\y(:,i1);\n end\n end\n end\n end\n \n % =================================================================\n % Gradient with respect to covariance function parameters\n i1=0;\n if ~isempty(strfind(gp.infer_params, 'covariance'))\n \n if isfield(gp,'deriv') && gp.deriv % derivative observations in use\n % initialize few variables related to derivative observations\n [n,m] = size(x);\n ind_Ddim = x(:,gp.deriv);\n ind_Ddim_derivs = ind_Ddim(ind_Ddim>0);\n uDdim = unique(ind_Ddim_derivs);\n x1 = x(:,setdiff(1:m,gp.deriv)); % Take only the non-index columns\n end\n \n for i=1:ncf\n \n gpcf = gp.cf{i};\n \n if isfield(gp.lik, 'nondiagW') && ~ismember(gp.lik.type, {'LGP' 'LGPC'})\n % check in which components the covariance function is present\n % for likelihoods with non-diagonal Hessian\n do = false(nout,1);\n if multicf\n for z1=1:nout\n if any(gp.comp_cf{z1}==i)\n do(z1) = true;\n end\n end\n else\n do = true(nout,1);\n end\n end\n \n if ~(isfield(gp,'deriv') && gp.deriv)\n % No derivative observations\n if ~savememory\n if isfield(gp.lik, 'nondiagW') && isfield(gp,'comp_cf') && ~isempty(intersect(gp.comp_cf{1},i)) && isfield(gp.lik, 'xtime')\n DKffc = gpcf.fh.cfg(gpcf, xtime);\n else\n DKffc = gpcf.fh.cfg(gpcf, x);\n end\n np=length(DKffc);\n else\n % If savememory option is used, just get the number of\n % hyperparameters and calculate gradients later\n np=gpcf.fh.cfg(gpcf,[],[],[],0);\n end\n gprior_cf = -gpcf.fh.lpg(gpcf);\n else\n [n,m]=size(x);\n gprior_cf = -gpcf.fh.lpg(gpcf);\n if (~isfield(gpcf, 'selectedVariables') || any(ismember(gpcf.selectedVariables,uDdim)))\n % !!! Note. The check whether to calculate derivative\n % matrices for a covariance function could/should be made\n % nicer\n DKffa = gpcf.fh.cfg(gpcf, x1(ind_Ddim==0,:));\n np=length(DKffa);\n for inp=1:np\n % the block of covariance matrix\n DKffc{inp}(ind_Ddim==0,ind_Ddim==0) = DKffa{inp};\n end\n for u1 = 1:length(uDdim)\n % the blocks on the left side, below Kff\n Kdf = gpcf.fh.cfdg(gpcf, x1(ind_Ddim==uDdim(u1),:), x1(ind_Ddim==0,:), uDdim(u1));\n D = gpcf.fh.cfdg2(gpcf, x1(ind_Ddim==uDdim(u1),:), x1(ind_Ddim==uDdim(u1),:), uDdim(u1), uDdim(u1));\n for inp=1:np\n DKffc{inp}(ind_Ddim==uDdim(u1),ind_Ddim==0) = Kdf{inp};\n DKffc{inp}(ind_Ddim==0,ind_Ddim==uDdim(u1)) = Kdf{inp}';\n DKffc{inp}(ind_Ddim==uDdim(u1),ind_Ddim==uDdim(u1)) = D{inp};\n end\n \n uDdim2 = uDdim(u1+1:end);\n for u2=1:length(uDdim2)\n Kdf2 = gpcf.fh.cfdg2(gpcf, x1(ind_Ddim==uDdim(u1),:) ,x1(ind_Ddim==uDdim2(u2),:), uDdim(u1), uDdim2(u2));\n for inp=1:np\n DKffc{inp}(ind_Ddim==uDdim(u1),ind_Ddim==uDdim2(u2)) = Kdf2{inp};\n DKffc{inp}(ind_Ddim==uDdim2(u2),ind_Ddim==uDdim(u1)) = Kdf2{inp}';\n end\n end\n \n end\n \n %DKffc{inp} = Ktemp;\n \n else\n % A covariance function that does not use any\n % of the input dimensions with respect to which\n % derivatives are observed\n %warning('not tested yet')\n DKffa = gpcf.fh.cfg(gpcf, x(ind_Ddim==0,:));\n np=length(DKffa);\n for inp=1:np\n Ktemp = sparse(n,n);\n Ktemp(ind_Ddim==0,ind_Ddim==0) = DKffa{inp};\n DKffc{inp} = Ktemp;\n end\n end\n \n end\n \n % Are there specified mean functions\n if ~isfield(gp,'meanf')\n % Evaluate the gradient with respect to covariance function\n % parameters\n for i2 = 1:np\n if savememory\n if isfield(gp.lik, 'nondiagW') && isfield(gp,'comp_cf') && ~isempty(intersect(gp.comp_cf{1},i)) && isfield(gp.lik, 'xtime')\n DKff=gpcf.fh.cfg(gpcf,xtime,[],[],i2);\n else\n DKff=gpcf.fh.cfg(gpcf,x,[],[],i2);\n end\n else\n DKff=DKffc{i2};\n end\n i1 = i1+1;\n if ~isfield(gp.lik, 'nondiagW') || ismember(gp.lik.type, {'LGP' 'LGPC'})\n Bdl = b'*(DKff*b);\n Cdl = sum(sum(invC.*DKff)); % help arguments\n else\n % Non-diagonalizable likelihoods\n Bdl=0; Cdl=0;\n if isfield(gp.lik,'xtime');\n if do(1)\n Bdl = Bdl + b(1:ntime)'*(DKff*b(1:ntime));\n Cdl = Cdl + sum(sum(invC(1:ntime,1:ntime).*DKff)); % help arguments\n end\n if do(2)\n Bdl = Bdl + b(ntime+1:end)'*(DKff*b(ntime+1:end));\n Cdl = Cdl + sum(sum(invC(ntime+1:end,ntime+1:end).*DKff)); % help arguments\n end\n else\n for z1=1:nout\n if do(z1)\n Bdl = Bdl + b(1+nl(z1):nl(z1+1))'*(DKff*b(1+nl(z1):nl(z1+1)));\n Cdl = Cdl + sum(sum(invC(:,:,z1).*DKff)); % help arguments\n end\n end\n end\n end\n gdata(i1)=0.5.*(Cdl - Bdl);\n end\n else\n for i2 = 1:np\n if savememory\n DKff=gpcf.fh.cfg(gpcf,x,[],[],i2);\n else\n DKff=DKffc{i2};\n end\n i1=i1+1;\n dA = -1*HinvC*DKff*HinvC'; % d A / d th\n trA = sum(invAt(:).*dA(:)); % d log(|A|) / dth\n dMNM = invNM'*(DKff*invNM); % d M'*N*M / d th\n trK = sum(sum(invC.*DKff)); % d log(Ky�?�) / d th\n gdata(i1)=0.5*(-1*dMNM + trK + trA);\n end\n end\n \n gprior = [gprior gprior_cf];\n end\n end\n \n % =================================================================\n % Gradient with respect to Gaussian likelihood function parameters\n if ~isempty(strfind(gp.infer_params, 'likelihood')) && isfield(gp.lik.fh,'trcov')\n % Evaluate the gradient from Gaussian likelihood\n gprior_lik = -gp.lik.fh.lpg(gp.lik);\n if ~isempty(gprior_lik)\n DCff = gp.lik.fh.cfg(gp.lik, x);\n if isfield(gp, 'lik_mono')\n DCff{1}=diag(DCff{1}*[ones(size(x,1),1); zeros(size(gp.xv,1)*length(nvd),1)]);\n end\n for i2 = 1:length(DCff)\n i1 = i1+1;\n if ~isfield(gp,'meanf')\n if size(DCff{i2}) > 1\n yKy = b'*(DCff{i2}*b);\n trK = sum(sum(invC.*DCff{i2})); % help arguments\n gdata_zeromean(i1)=0.5.*(trK - yKy);\n else\n yKy=DCff{i2}.*(b'*b);\n trK = DCff{i2}.*(trace(invC));\n gdata_zeromean(i1)=0.5.*(trK - yKy);\n end\n gdata(i1)=gdata_zeromean(i1);\n else\n if size(DCff{i2}) > 1\n trK = sum(sum(invC.*DCff{i2})); % help arguments\n else\n trK = DCff{i2}.*(trace(invC));\n end\n dA = -1*HinvC*DCff{i2}*HinvC'; % d A / d th\n trA = sum(invAt(:).*dA(:)); % d log(|A|) / dth\n dMNM = invNM'*(DCff{i2}*invNM); % d M'*N*M / d th\n gdata(i1)=0.5*(-1*dMNM + trA + trK);\n end\n end\n end\n gprior = [gprior gprior_lik];\n end\n \n \n if ~isempty(strfind(gp.infer_params, 'mean')) && isfield(gp,'meanf')\n notpositivedefinite2 = 0; notpositivedefinite3 = 0;\n \n nmf=numel(gp.meanf);\n [H,b,B]=mean_prep(gp,x,[]);\n M = H'*b-y;\n \n if issparse(C)\n [LD, notpositivedefinite] = ldlchol(C);\n if ~notpositivedefinite\n KH = ldlsolve(LD, H');\n end\n [LB, notpositivedefinite2] = chol(B);\n if ~notpositivedefinite2\n A = LB\\(LB'\\eye(size(B))) + H*KH;\n LA = chol(A);\n a = ldlsolve(LD, M) - KH*(LA\\(LA'\\(KH'*M)));\n iNH = ldlsolve(LD, H') - KH*(LA\\(LA'\\(KH'*H')));\n end\n else\n N = C + H'*B*H;\n [LN, notpositivedefinite3] = chol(N);\n if ~notpositivedefinite3\n a = LN\\(LN'\\M);\n iNH = LN\\(LN'\\H');\n end\n end\n if (~notpositivedefinite2 && ~notpositivedefinite3)\n Ha=H*a;\n g_bb = (-H*a)'; % b and B parameters are log transformed in packing\n indB = find(B>0);\n for i=1:length(indB)\n Bt = zeros(size(B)); Bt(indB(i))=1;\n BH = Bt*H;\n g_B(i) = 0.5* ( Ha'*Bt*Ha - sum(sum(iNH.*(BH'))) );\n end\n g_BB = g_B.*B(indB)';\n % Interweave the mean functions parameters in correct order\n g_bB = [-g_bb; -g_BB];\n g_bB = g_bB(:)';\n for i=1:nmf\n gpmf = gp.meanf{i};\n [lpg_b, lpg_B] = gpmf.fh.lpg(gpmf);\n gprior = [gprior -lpg_b -lpg_B];\n % Check whether parameters are fixed or not\n if isempty(lpg_b)\n g_bB(1+(i-1)*2)=NaN;\n end\n if isempty(lpg_B)\n g_bB(2+(i-1)*2)=NaN;\n end\n end\n gdata = [gdata g_bB(~isnan(g_bB))];\n else\n g=NaN;\n gdata = NaN;\n gprior = NaN;\n return\n end\n end\n \n case 'FIC'\n % ============================================================\n % FIC\n % ============================================================\n g_ind = zeros(1,numel(gp.X_u));\n gdata_ind = zeros(1,numel(gp.X_u));\n gprior_ind = zeros(1,numel(gp.X_u));\n \n u = gp.X_u;\n DKuu_u = 0;\n DKuf_u = 0;\n \n % First evaluate the needed covariance matrices\n % v defines that parameter is a vector\n [Kv_ff, Cv_ff] = gp_trvar(gp, x); % 1 x f vector\n K_fu = gp_cov(gp, x, u); % f x u\n K_uu = gp_trcov(gp, u); % u x u, noiseles covariance K_uu\n K_uu = (K_uu+K_uu')./2; % ensure the symmetry of K_uu\n [Luu, notpositivedefinite] = chol(K_uu,'lower');\n if notpositivedefinite\n % If not positive definite, return NaN\n g=NaN; gdata=NaN; gprior=NaN;\n return;\n end\n % Evaluate the Lambda (La)\n % Q_ff = K_fu*inv(K_uu)*K_fu'\n % Here we need only the diag(Q_ff), which is evaluated below\n B=Luu\\(K_fu');\n Qv_ff=sum(B.^2)';\n Lav = Cv_ff-Qv_ff; % 1 x f, Vector of diagonal elements\n % iLaKfu = diag(inv(Lav))*K_fu = inv(La)*K_fu\n iLaKfu = zeros(size(K_fu)); % f x u,\n for i=1:n\n iLaKfu(i,:) = K_fu(i,:)./Lav(i); % f x u\n end\n % ... then evaluate some help matrices.\n % A = K_uu+K_uf*inv(La)*K_fu\n A = K_uu+K_fu'*iLaKfu;\n A = (A+A')./2; % Ensure symmetry\n [A, notpositivedefinite] = chol(A,'upper');\n if notpositivedefinite\n % If not positive definite, return NaN\n g=NaN; gdata=NaN; gprior=NaN;\n return;\n end\n L = iLaKfu/A;\n b = y'./Lav' - (y'*L)*L';\n iKuuKuf = Luu'\\(Luu\\K_fu');\n La = Lav;\n LL = sum(L.*L,2);\n \n % =================================================================\n % Gradient with respect to covariance function parameters\n if ~isempty(strfind(gp.infer_params, 'covariance'))\n % Loop over the covariance functions\n i1=0;\n for i=1:ncf\n \n % Get the gradients of the covariance matrices\n % and gprior from gpcf_* structures\n gpcf = gp.cf{i};\n if savememory\n % If savememory option is used, just get the number of\n % hyperparameters and calculate gradients later\n np=gpcf.fh.cfg(gpcf,[],[],[],0);\n else\n DKffc = gpcf.fh.cfg(gpcf, x, [], 1);\n DKuuc = gpcf.fh.cfg(gpcf, u);\n DKufc = gpcf.fh.cfg(gpcf, u, x);\n np=length(DKffc);\n end\n gprior_cf = -gpcf.fh.lpg(gpcf);\n \n for i2 = 1:np\n i1 = i1+1;\n if savememory\n DKff=gpcf.fh.cfg(gpcf,x,[],1,i2);\n DKuu=gpcf.fh.cfg(gpcf,u,[],[],i2);\n DKuf=gpcf.fh.cfg(gpcf,u,x,[],i2);\n else\n DKff=DKffc{i2};\n DKuu=DKuuc{i2};\n DKuf=DKufc{i2};\n end\n KfuiKuuKuu = iKuuKuf'*DKuu;\n gdata(i1) = -0.5.*((2*b*DKuf'-(b*KfuiKuuKuu))*(iKuuKuf*b') + 2.*sum(sum(L'.*(L'*DKuf'*iKuuKuf))) - ...\n sum(sum(L'.*((L'*KfuiKuuKuu)*iKuuKuf))));\n \n gdata(i1) = gdata(i1) - 0.5.*(b.*DKff')*b';\n gdata(i1) = gdata(i1) + 0.5.*(2.*b.*sum(DKuf'.*iKuuKuf',2)'*b'- b.*sum(KfuiKuuKuu.*iKuuKuf',2)'*b');\n gdata(i1) = gdata(i1) + 0.5.*(sum(DKff./La) - sum(LL.*DKff));\n gdata(i1) = gdata(i1) + 0.5.*(2.*sum(LL.*sum(DKuf'.*iKuuKuf',2)) - sum(LL.*sum(KfuiKuuKuu.*iKuuKuf',2)));\n end\n \n gprior = [gprior gprior_cf];\n end\n end\n \n % =================================================================\n % Gradient with respect to Gaussian likelihood function parameters\n if ~isempty(strfind(gp.infer_params, 'likelihood')) && isfield(gp.lik.fh,'trcov')\n % Evaluate the gradient from Gaussian likelihood\n DCff = gp.lik.fh.cfg(gp.lik, x);\n gprior_lik = -gp.lik.fh.lpg(gp.lik);\n for i2 = 1:length(DCff)\n i1 = i1+1;\n gdata(i1)= -0.5*DCff{i2}.*b*b';\n gdata(i1)= gdata(i1) + 0.5*sum(DCff{i2}./La-sum(L.*L,2).*DCff{i2});\n end\n % % Set the gradients of hyperparameter\n % if length(gprior_lik) > length(DCff)\n % for i2=length(DCff)+1:length(gprior_lik)\n % i1 = i1+1;\n % gdata(i1) = 0;\n % end\n % end\n gprior = [gprior gprior_lik];\n end\n \n % =================================================================\n % Gradient with respect to inducing inputs\n if ~isempty(strfind(gp.infer_params, 'inducing'))\n if isfield(gp.p, 'X_u') && ~isempty(gp.p.X_u)\n m = size(gp.X_u,2);\n st=0;\n if ~isempty(gdata)\n st = length(gdata);\n end\n \n gdata(st+1:st+length(gp.X_u(:))) = 0;\n i1 = st+1;\n gprior_ind=[];\n if iscell(gp.p.X_u) % Own prior for each inducing input\n for i = 1:size(gp.X_u,1)\n pr = gp.p.X_u{i};\n gprior_ind =[gprior_ind -pr.fh.lpg(gp.X_u(i,:), pr)];\n end\n else % One prior for all inducing inputs\n gprior_ind = -gp.p.X_u.fh.lpg(gp.X_u(:)', gp.p.X_u);\n end\n gprior = [gprior gprior_ind];\n % gdata=[gdata zeros(1,length(gprior) - length(gdata))];\n \n % Loop over the covariance functions\n for i=1:ncf\n i1 = st;\n gpcf = gp.cf{i};\n \n if savememory\n % If savememory option is used, just get the number of\n % covariates in X and calculate gradients later\n np=gpcf.fh.ginput(gpcf,u,[],0);\n else\n np=1;\n DKuu = gpcf.fh.ginput(gpcf, u);\n DKuf = gpcf.fh.ginput(gpcf, u, x);\n end\n for i3=1:np\n if savememory\n DKuu=gpcf.fh.ginput(gpcf,u,[],i3);\n DKuf=gpcf.fh.ginput(gpcf,u,x,i3);\n end\n for i2 = 1:length(DKuu)\n if savememory\n i1 = st + (i2-1)*np+i3;\n %i1 = st + 2*i2 - (i3==1);\n else\n i1 = i1+1;\n end\n KfuiKuuKuu = iKuuKuf'*DKuu{i2};\n gdata(i1) = gdata(i1) - 0.5.*((2*b*DKuf{i2}'-(b*KfuiKuuKuu))*(iKuuKuf*b') + ...\n 2.*sum(sum(L'.*(L'*DKuf{i2}'*iKuuKuf))) - sum(sum(L'.*((L'*KfuiKuuKuu)*iKuuKuf))));\n gdata(i1) = gdata(i1) + 0.5.*(2.*b.*sum(DKuf{i2}'.*iKuuKuf',2)'*b'- b.*sum(KfuiKuuKuu.*iKuuKuf',2)'*b');\n gdata(i1) = gdata(i1) + 0.5.*(2.*sum(LL.*sum(DKuf{i2}'.*iKuuKuf',2)) - ...\n sum(LL.*sum(KfuiKuuKuu.*iKuuKuf',2)));\n end\n end\n end\n end\n end\n \n case {'PIC' 'PIC_BLOCK'}\n % ============================================================\n % PIC\n % ============================================================\n g_ind = zeros(1,numel(gp.X_u));\n gdata_ind = zeros(1,numel(gp.X_u));\n gprior_ind = zeros(1,numel(gp.X_u));\n \n u = gp.X_u;\n ind = gp.tr_index;\n DKuu_u = 0;\n DKuf_u = 0;\n \n % First evaluate the needed covariance matrices\n % if they are not in the memory\n % v defines that parameter is a vector\n K_fu = gp_cov(gp, x, u); % f x u\n K_uu = gp_trcov(gp, u); % u x u, noiseles covariance K_uu\n K_uu = (K_uu+K_uu')./2; % ensure the symmetry of K_uu\n [Luu, notpositivedefinite] = chol(K_uu,'lower');\n if notpositivedefinite\n % If not positive definite, return NaN\n g=NaN; gdata=NaN; gprior=NaN;\n return;\n end\n % Evaluate the Lambda (La)\n % Q_ff = K_fu*inv(K_uu)*K_fu'\n % Here we need only the diag(Q_ff), which is evaluated below\n %B=K_fu/Luu;\n B=Luu\\K_fu';\n iLaKfu = zeros(size(K_fu)); % f x u\n for i=1:length(ind)\n Qbl_ff = B(:,ind{i})'*B(:,ind{i});\n [Kbl_ff, Cbl_ff] = gp_trcov(gp, x(ind{i},:));\n la = Cbl_ff - Qbl_ff;\n La{i} = (la + la')./2;\n iLaKfu(ind{i},:) = La{i}\\K_fu(ind{i},:);\n end\n % ... then evaluate some help matrices.\n % A = chol(K_uu+K_uf*inv(La)*K_fu))\n A = K_uu+K_fu'*iLaKfu;\n A = (A+A')./2; % Ensure symmetry\n \n [LA,notpositivedefinite]=chol(A,'upper');\n if notpositivedefinite\n % instead of stopping to chol error, return NaN\n g=NaN; gdata = NaN; gprior = NaN;\n return;\n end\n L = iLaKfu/LA;\n b = zeros(1,n);\n b_apu=(y'*L)*L';\n for i=1:length(ind)\n b(ind{i}) = y(ind{i})'/La{i} - b_apu(ind{i});\n end\n iKuuKuf = Luu'\\(Luu\\K_fu');\n \n % =================================================================\n % Gradient with respect to covariance function parameters\n \n if ~isempty(strfind(gp.infer_params, 'covariance'))\n % Loop over the covariance functions\n i1=0;\n for i=1:ncf\n \n % Get the gradients of the covariance matrices\n % and gprior from gpcf_* structures\n gpcf = gp.cf{i};\n if savememory\n % If savememory option is used, just get the number of\n % hyperparameters and calculate gradients later\n np=gpcf.fh.cfg(gpcf,[],[],[],0);\n else\n DKuuc = gpcf.fh.cfg(gpcf, u);\n DKufc = gpcf.fh.cfg(gpcf, u, x);\n for kk = 1:length(ind)\n DKffc{kk} = gpcf.fh.cfg(gpcf, x(ind{kk},:));\n end\n np=length(DKuuc);\n end\n gprior_cf = -gpcf.fh.lpg(gpcf);\n \n for i2 = 1:np\n i1 = i1+1;\n if savememory\n DKuu=gpcf.fh.cfg(gpcf,u,[],[],i2);\n DKuf=gpcf.fh.cfg(gpcf,u,x,[],i2);\n else\n DKuu=DKuuc{i2};\n DKuf=DKufc{i2};\n end\n KfuiKuuKuu = iKuuKuf'*DKuu;\n % H = (2*K_uf'- KfuiKuuKuu)*iKuuKuf;\n % Here we evaluate gdata = -0.5.* (b*H*b' + trace(L*L'H)\n gdata(i1) = -0.5.*((2*b*DKuf'-(b*KfuiKuuKuu))*(iKuuKuf*b') + 2.*sum(sum(L'.*(L'*DKuf'*iKuuKuf))) - ...\n sum(sum(L'.*((L'*KfuiKuuKuu)*iKuuKuf))));\n for kk=1:length(ind)\n if savememory\n DKff=gpcf.fh.cfg(gpcf,x(ind{kk},:),[],[],i2);\n else\n DKff=DKffc{kk}{i2};\n end\n gdata(i1) = gdata(i1) ...\n + 0.5.*(-b(ind{kk})*DKff*b(ind{kk})' ...\n + 2.*b(ind{kk})*DKuf(:,ind{kk})'*iKuuKuf(:,ind{kk})*b(ind{kk})'- ...\n b(ind{kk})*KfuiKuuKuu(ind{kk},:)*iKuuKuf(:,ind{kk})*b(ind{kk})' ...\n +trace(La{kk}\\DKff)...\n - trace(L(ind{kk},:)*(L(ind{kk},:)'*DKff)) ...\n + 2.*sum(sum(L(ind{kk},:)'.*(L(ind{kk},:)'*DKuf(:,ind{kk})'*iKuuKuf(:,ind{kk})))) - ...\n sum(sum(L(ind{kk},:)'.*((L(ind{kk},:)'*KfuiKuuKuu(ind{kk},:))*iKuuKuf(:,ind{kk})))));\n end\n end\n gprior = [gprior gprior_cf];\n end\n end\n \n % =================================================================\n % Gradient with respect to Gaussian likelihood function parameters\n if ~isempty(strfind(gp.infer_params, 'likelihood')) && isfield(gp.lik.fh,'trcov')\n % Evaluate the gradient from Gaussian likelihood\n DCff = gp.lik.fh.cfg(gp.lik, x);\n gprior_lik = -gp.lik.fh.lpg(gp.lik);\n for i2 = 1:length(DCff)\n i1 = i1+1;\n gdata(i1)= -0.5*DCff{i2}.*b*b';\n for kk=1:length(ind)\n gdata(i1)= gdata(i1) + 0.5*trace((inv(La{kk})-L(ind{kk},:)*L(ind{kk},:)')).*DCff{i2};\n end\n end\n gprior = [gprior gprior_lik];\n end\n \n % =================================================================\n % Gradient with respect to inducing inputs\n if ~isempty(strfind(gp.infer_params, 'inducing'))\n if isfield(gp.p, 'X_u') && ~isempty(gp.p.X_u)\n m = size(gp.X_u,2);\n \n st=0;\n if ~isempty(gdata)\n st = length(gdata);\n end\n gdata(st+1:st+length(gp.X_u(:))) = 0;\n \n i1 = st+1;\n gprior_ind=[];\n if iscell(gp.p.X_u) % Own prior for each inducing input\n for i = 1:size(gp.X_u,1)\n pr = gp.p.X_u{i};\n gprior_ind =[gprior_ind -pr.fh.lpg(gp.X_u(i,:), pr)];\n end\n else % One prior for all inducing inputs\n gprior_ind = -gp.p.X_u.fh.lpg(gp.X_u(:)', gp.p.X_u);\n end\n gprior = [gprior gprior_ind];\n \n % Loop over the covariance functions\n for i=1:ncf\n i1=st;\n gpcf = gp.cf{i};\n if savememory\n % If savememory option is used, just get the number of\n % covariates in X and calculate gradients later\n np=gpcf.fh.ginput(gpcf,u,[],0);\n else\n np=1;\n DKuu = gpcf.fh.ginput(gpcf, u);\n DKuf = gpcf.fh.ginput(gpcf, u, x);\n end\n \n for i3 = 1:np\n if savememory\n DKuu=gpcf.fh.ginput(gpcf, u, [], i3);\n DKuf=gpcf.fh.ginput(gpcf, u, x, i3);\n end\n for i2 = 1:length(DKuu)\n if savememory\n i1 = st + (i2-1)*np+i3;\n %i1 = st + 2*i2 - (i3==1);\n else\n i1 = i1+1;\n end\n KfuiKuuDKuu_u = iKuuKuf'*DKuu{i2};\n gdata(i1) = gdata(i1) -0.5.*((2*b*DKuf{i2}'-(b*KfuiKuuDKuu_u))*(iKuuKuf*b') + 2.*sum(sum(L'.*((L'*DKuf{i2}')*iKuuKuf))) - ...\n sum(sum(L'.*((L'*KfuiKuuDKuu_u)*iKuuKuf))));\n \n for kk=1:length(ind)\n gdata(i1) = gdata(i1) + 0.5.*(2.*b(ind{kk})*DKuf{i2}(:,ind{kk})'*iKuuKuf(:,ind{kk})*b(ind{kk})'- ...\n b(ind{kk})*KfuiKuuDKuu_u(ind{kk},:)*iKuuKuf(:,ind{kk})*b(ind{kk})' ...\n + 2.*sum(sum(L(ind{kk},:)'.*(L(ind{kk},:)'*DKuf{i2}(:,ind{kk})'*iKuuKuf(:,ind{kk})))) - ...\n sum(sum(L(ind{kk},:)'.*((L(ind{kk},:)'*KfuiKuuDKuu_u(ind{kk},:))*iKuuKuf(:,ind{kk})))));\n end\n end\n end\n end\n end\n end\n \n case 'CS+FIC'\n % ============================================================\n % CS+FIC\n % ============================================================\n g_ind = zeros(1,numel(gp.X_u));\n gdata_ind = zeros(1,numel(gp.X_u));\n gprior_ind = zeros(1,numel(gp.X_u));\n \n u = gp.X_u;\n DKuu_u = 0;\n DKuf_u = 0;\n \n cf_orig = gp.cf;\n \n cf1 = {};\n cf2 = {};\n j = 1;\n k = 1;\n for i = 1:ncf\n if ~isfield(gp.cf{i},'cs')\n cf1{j} = gp.cf{i};\n j = j + 1;\n else\n cf2{k} = gp.cf{i};\n k = k + 1;\n end\n end\n gp.cf = cf1;\n \n % First evaluate the needed covariance matrices\n % if they are not in the memory\n % v defines that parameter is a vector\n [Kv_ff, Cv_ff] = gp_trvar(gp, x); % 1 x f vector\n K_fu = gp_cov(gp, x, u); % f x u\n K_uu = gp_trcov(gp, u); % u x u, noiseles covariance K_uu\n K_uu = (K_uu+K_uu')./2; % ensure the symmetry of K_uu\n [Luu, notpositivedefinite] = chol(K_uu,'lower');\n if notpositivedefinite\n % If not positive definite, return NaN\n g=NaN; gdata=NaN; gprior=NaN;\n return;\n end\n % Evaluate the Lambda (La)\n % Q_ff = K_fu*inv(K_uu)*K_fu'\n % Here we need only the diag(Q_ff), which is evaluated below\n B=Luu\\(K_fu');\n Qv_ff=sum(B.^2)';\n Lav = Cv_ff-Qv_ff; % 1 x f, Vector of diagonal elements\n \n gp.cf = cf2;\n K_cs = gp_trcov(gp,x);\n La = sparse(1:n,1:n,Lav,n,n) + K_cs;\n gp.cf = cf_orig;\n \n LD = ldlchol(La);\n % iLaKfu = La\\K_fu;\n iLaKfu = ldlsolve(LD, K_fu);\n \n % ... then evaluate some help matrices.\n % A = chol(K_uu+K_uf*inv(La)*K_fu))\n A = K_uu+K_fu'*iLaKfu;\n A = (A+A')./2; % Ensure symmetry\n [LA, notpositivedefinite] = chol(A,'upper');\n if notpositivedefinite\n % If not positive definite, return NaN\n g=NaN; gdata=NaN; gprior=NaN;\n return;\n end\n L = iLaKfu/LA;\n %b = y'/La - (y'*L)*L';\n b = ldlsolve(LD,y)' - (y'*L)*L';\n \n siLa = spinv(La);\n idiagLa = diag(siLa);\n iKuuKuf = K_uu\\K_fu';\n LL = sum(L.*L,2);\n \n % =================================================================\n % Gradient with respect to covariance function parameters\n if ~isempty(strfind(gp.infer_params, 'covariance'))\n % Loop over covariance functions\n i1=0;\n for i=1:ncf\n \n gpcf = gp.cf{i};\n \n % Evaluate the gradient for FIC covariance functions\n if ~isfield(gpcf,'cs')\n % Get the gradients of the covariance matrices\n % and gprior from gpcf_* structures\n if savememory\n % If savememory option is used, just get the number of\n % hyperparameters and calculate gradients later\n np=gpcf.fh.cfg(gpcf,[],[],[],0);\n else\n DKffc = gpcf.fh.cfg(gpcf, x, [], 1);\n DKuuc = gpcf.fh.cfg(gpcf, u);\n DKufc = gpcf.fh.cfg(gpcf, u, x);\n np=length(DKuuc);\n end\n gprior_cf = -gpcf.fh.lpg(gpcf);\n \n \n for i2 = 1:np\n i1 = i1+1;\n if savememory\n DKff=gpcf.fh.cfg(gpcf,x,[],1,i2);\n DKuu=gpcf.fh.cfg(gpcf,u,[],[],i2);\n DKuf=gpcf.fh.cfg(gpcf,u,x,[],i2);\n else\n DKff=DKffc{i2};\n DKuu=DKuuc{i2};\n DKuf=DKufc{i2};\n end\n KfuiKuuKuu = iKuuKuf'*DKuu;\n gdata(i1) = -0.5.*((2*b*DKuf'-(b*KfuiKuuKuu))*(iKuuKuf*b') + 2.*sum(sum(L'.*(L'*DKuf'*iKuuKuf))) - ...\n sum(sum(L'.*((L'*KfuiKuuKuu)*iKuuKuf))));\n \n temp1 = sum(KfuiKuuKuu.*iKuuKuf',2);\n temp2 = sum(DKuf'.*iKuuKuf',2);\n temp3 = 2.*DKuf' - KfuiKuuKuu;\n gdata(i1) = gdata(i1) - 0.5.*(b.*DKff')*b';\n gdata(i1) = gdata(i1) + 0.5.*(2.*b.*temp2'*b'- b.*temp1'*b');\n gdata(i1) = gdata(i1) + 0.5.*(sum(idiagLa.*DKff - LL.*DKff)); % corrected\n gdata(i1) = gdata(i1) + 0.5.*(2.*sum(LL.*temp2) - sum(LL.*temp1));\n \n %gdata(i1) = gdata(i1) + 0.5.*sum(sum(La\\((2.*K_uf') - KfuiKuuKuu).*iKuuKuf',2));\n gdata(i1) = gdata(i1) + 0.5.*sum(sum(ldlsolve(LD,temp3).*iKuuKuf',2));\n gdata(i1) = gdata(i1) - 0.5.*( idiagLa'*(sum(temp3.*iKuuKuf',2)) ); % corrected\n end\n \n % Evaluate the gradient for compact support covariance functions\n else\n % Get the gradients of the covariance matrices\n % and gprior from gpcf_* structures\n if savememory\n % If savememory option is used, just get the number of\n % hyperparameters and calculate gradients later\n np=gpcf.fh.cfg(gpcf,[],[],[],0);\n else\n DKffc = gpcf.fh.cfg(gpcf, x);\n np=length(DKffc);\n end\n gprior_cf = -gpcf.fh.lpg(gpcf);\n \n for i2 = 1:np\n i1 = i1+1;\n if savememory\n DKff=gpcf.fh.cfg(gpcf,x,[],[],i2);\n else\n DKff=DKffc{i2};\n end\n gdata(i1) = 0.5*(sum(sum(siLa.*DKff',2)) - sum(sum(L.*(L'*DKff')')) - b*DKff*b');\n end\n end\n gprior = [gprior gprior_cf];\n end\n end\n \n % =================================================================\n % Gradient with respect to Gaussian likelihood function parameters\n if ~isempty(strfind(gp.infer_params, 'likelihood')) && isfield(gp.lik.fh,'trcov')\n % Evaluate the gradient from Gaussian likelihood\n DCff = gp.lik.fh.cfg(gp.lik, x);\n gprior_lik = -gp.lik.fh.lpg(gp.lik);\n for i2 = 1:length(DCff)\n i1 = i1+1;\n gdata(i1)= -0.5*DCff{i2}.*b*b';\n gdata(i1)= gdata(i1) + 0.5*sum(idiagLa-LL).*DCff{i2};\n end\n gprior = [gprior gprior_lik];\n end\n \n % =================================================================\n % Gradient with respect to inducing inputs\n if ~isempty(strfind(gp.infer_params, 'inducing'))\n if isfield(gp.p, 'X_u') && ~isempty(gp.p.X_u)\n m = size(gp.X_u,2);\n st=0;\n if ~isempty(gdata)\n st = length(gdata);\n end\n \n gdata(st+1:st+length(gp.X_u(:))) = 0;\n i1 = st+1;\n gprior_ind=[];\n if iscell(gp.p.X_u) % Own prior for each inducing input\n for i = 1:size(gp.X_u,1)\n pr = gp.p.X_u{i};\n gprior_ind =[gprior_ind -pr.fh.lpg(gp.X_u(i,:), pr)];\n end\n else % One prior for all inducing inputs\n gprior_ind = -gp.p.X_u.fh.lpg(gp.X_u(:)', gp.p.X_u);\n end\n gprior = [gprior gprior_ind];\n \n for i=1:ncf\n i1=st;\n gpcf = gp.cf{i};\n if ~isfield(gpcf,'cs')\n if savememory\n % If savememory option is used, just get the number of\n % covariates in X and calculate gradients later\n np=gpcf.fh.ginput(gpcf,u,[],0);\n else\n np=1;\n DKuu = gpcf.fh.ginput(gpcf, u);\n DKuf = gpcf.fh.ginput(gpcf, u, x);\n end\n \n for i3 = 1:np\n if savememory\n DKuu = gpcf.fh.ginput(gpcf,u,[],i3);\n DKuf = gpcf.fh.ginput(gpcf,u,x,i3);\n end\n for i2 = 1:length(DKuu)\n if savememory\n i1 = st + (i2-1)*np+i3;\n %i1 = st + 2*i2 - (i3==1);\n else\n i1 = i1+1;\n end\n KfuiKuuKuu = iKuuKuf'*DKuu{i2};\n \n gdata(i1) = gdata(i1) - 0.5.*((2*b*DKuf{i2}'-(b*KfuiKuuKuu))*(iKuuKuf*b') + ...\n 2.*sum(sum(L'.*(L'*DKuf{i2}'*iKuuKuf))) - sum(sum(L'.*((L'*KfuiKuuKuu)*iKuuKuf))));\n gdata(i1) = gdata(i1) + 0.5.*(2.*b.*sum(DKuf{i2}'.*iKuuKuf',2)'*b'- b.*sum(KfuiKuuKuu.*iKuuKuf',2)'*b');\n gdata(i1) = gdata(i1) + 0.5.*(2.*sum(sum(L.*L,2).*sum(DKuf{i2}'.*iKuuKuf',2)) - ...\n sum(sum(L.*L,2).*sum(KfuiKuuKuu.*iKuuKuf',2)));\n \n gdata(i1) = gdata(i1) + 0.5.*sum(sum(ldlsolve(LD,(2.*DKuf{i2}') - KfuiKuuKuu).*iKuuKuf',2));\n gdata(i1) = gdata(i1) - 0.5.*( idiagLa'*(sum((2.*DKuf{i2}' - KfuiKuuKuu).*iKuuKuf',2)) ); % corrected\n end\n end\n end\n end\n end\n end\n \n case {'DTC' 'VAR' 'SOR'}\n % ============================================================\n % DTC/VAR/SOR\n % ============================================================\n g_ind = zeros(1,numel(gp.X_u));\n gdata_ind = zeros(1,numel(gp.X_u));\n gprior_ind = zeros(1,numel(gp.X_u));\n \n u = gp.X_u;\n DKuu_u = 0;\n DKuf_u = 0;\n \n % First evaluate the needed covariance matrices\n % v defines that parameter is a vector\n [Kv_ff, Cv_ff] = gp_trvar(gp, x); % 1 x f vector\n K_fu = gp_cov(gp, x, u); % f x u\n K_uu = gp_trcov(gp, u); % u x u, noiseles covariance K_uu\n K_uu = (K_uu+K_uu')./2; % ensure the symmetry of K_uu\n [Luu, notpositivedefinite] = chol(K_uu,'lower');\n if notpositivedefinite\n % If not positive definite, return NaN\n g=NaN; gdata=NaN; gprior=NaN;\n return;\n end\n % Evaluate the Lambda (La)\n % Q_ff = K_fu*inv(K_uu)*K_fu'\n % Here we need only the diag(Q_ff), which is evaluated below\n B=Luu\\(K_fu');\n Qv_ff=sum(B.^2)';\n Lav = Cv_ff-Kv_ff; % 1 x f, Vector of diagonal elements\n % iLaKfu = diag(inv(Lav))*K_fu = inv(La)*K_fu\n iLaKfu = zeros(size(K_fu)); % f x u,\n for i=1:n\n iLaKfu(i,:) = K_fu(i,:)./Lav(i); % f x u\n end\n % ... then evaluate some help matrices.\n % A = K_uu+K_uf*inv(La)*K_fu\n A = K_uu+K_fu'*iLaKfu;\n A = (A+A')./2; % Ensure symmetry\n [LA, notpositivedefinite] = chol(A);\n if notpositivedefinite\n % If not positive definite, return NaN\n g=NaN; gdata=NaN; gprior=NaN;\n return;\n end\n L = iLaKfu/LA;\n b = y'./Lav' - (y'*L)*L';\n iKuuKuf = Luu'\\(Luu\\K_fu');\n La = Lav;\n LL = sum(L.*L,2);\n iLav=1./Lav;\n \n LL1=iLav-LL;\n \n % =================================================================\n \n if ~isempty(strfind(gp.infer_params, 'covariance'))\n % Loop over the covariance functions\n i1=0;\n for i=1:ncf\n \n % Get the gradients of the covariance matrices\n % and gprior from gpcf_* structures\n gpcf = gp.cf{i};\n if savememory\n np=gpcf.fh.cfg(gpcf,[],[],[],0);\n else\n DKffc = gpcf.fh.cfg(gpcf, x, [], 1);\n DKuuc = gpcf.fh.cfg(gpcf, u);\n DKufc = gpcf.fh.cfg(gpcf, u, x);\n np=length(DKuuc);\n end\n gprior_cf = -gpcf.fh.lpg(gpcf);\n \n for i2 = 1:np\n i1 = i1+1;\n if savememory\n % If savememory option is used, just get the number of\n % hyperparameters and calculate gradients later\n DKff=gpcf.fh.cfg(gpcf,x,[],1,i2);\n DKuu=gpcf.fh.cfg(gpcf,u,[],[],i2);\n DKuf=gpcf.fh.cfg(gpcf,u,x,[],i2);\n else\n DKff=DKffc{i2};\n DKuu=DKuuc{i2};\n DKuf=DKufc{i2};\n end\n \n KfuiKuuKuu = iKuuKuf'*DKuu;\n gdata(i1) = -0.5.*((2*b*DKuf'-(b*KfuiKuuKuu))*(iKuuKuf*b'));\n gdata(i1) = gdata(i1) + 0.5.*(2.*(sum(iLav'*sum(DKuf'.*iKuuKuf',2))-sum(sum(L'.*(L'*DKuf'*iKuuKuf))))...\n - sum(iLav'*sum(KfuiKuuKuu.*iKuuKuf',2))+ sum(sum(L'.*((L'*KfuiKuuKuu)*iKuuKuf))));\n \n if strcmp(gp.type, 'VAR')\n gdata(i1) = gdata(i1) + 0.5.*(sum(iLav.*DKff)-2.*sum(iLav'*sum(DKuf'.*iKuuKuf',2)) + ...\n sum(iLav'*sum(KfuiKuuKuu.*iKuuKuf',2))); % trace-term derivative\n end\n end\n gprior = [gprior gprior_cf];\n end\n end\n \n % =================================================================\n % Gradient with respect to Gaussian likelihood function parameters\n if ~isempty(strfind(gp.infer_params, 'likelihood')) && isfield(gp.lik.fh,'trcov')\n % Evaluate the gradient from Gaussian likelihood\n DCff = gp.lik.fh.cfg(gp.lik, x);\n gprior_lik = -gp.lik.fh.lpg(gp.lik);\n for i2 = 1:length(DCff)\n i1 = i1+1;\n gdata(i1)= -0.5*DCff{i2}.*b*b';\n gdata(i1)= gdata(i1) + 0.5*sum(DCff{i2}./La-sum(L.*L,2).*DCff{i2});\n if strcmp(gp.type, 'VAR')\n gdata(i1)= gdata(i1) - 0.5*(sum((Kv_ff-Qv_ff)./La));\n end\n end\n gprior = [gprior gprior_lik];\n end\n \n % =================================================================\n % Gradient with respect to inducing inputs\n if ~isempty(strfind(gp.infer_params, 'inducing'))\n if isfield(gp.p, 'X_u') && ~isempty(gp.p.X_u)\n m = size(gp.X_u,1);\n st=0;\n if ~isempty(gdata)\n st = length(gdata);\n end\n \n gdata(st+1:st+length(gp.X_u(:))) = 0;\n i1 = st+1;\n gprior_ind=[];\n if iscell(gp.p.X_u) % Own prior for each inducing input\n for i = 1:size(gp.X_u,1)\n pr = gp.p.X_u{i};\n gprior_ind =[gprior_ind -pr.fh.lpg(gp.X_u(i,:), pr)];\n end\n else % One prior for all inducing inputs\n gprior_ind = -gp.p.X_u.fh.lpg(gp.X_u(:)', gp.p.X_u);\n end\n gprior = [gprior gprior_ind];\n i1 = i1 + m;\n % Loop over the covariance functions\n for i=1:ncf\n i1 = st;\n gpcf = gp.cf{i};\n if savememory\n % If savememory option is used, just get the number of\n % covariates in X and calculate gradients later\n np=gpcf.fh.ginput(gpcf,u,[],0);\n else\n np=1;\n DKuu = gpcf.fh.ginput(gpcf, u);\n DKuf = gpcf.fh.ginput(gpcf, u, x);\n end\n \n for i3 = 1:np\n if savememory\n DKuu=gpcf.fh.ginput(gpcf,u,[],i3);\n DKuf=gpcf.fh.ginput(gpcf,u,x,i3);\n end\n for i2 = 1:length(DKuu)\n if savememory\n i1 = st + (i2-1)*np+i3;\n %i1 = st + 2*i2 - (i3==1);\n else\n i1 = i1+1;\n end\n KfuiKuuKuu = iKuuKuf'*DKuu{i2};\n gdata(i1) = gdata(i1) - 0.5.*((2*b*DKuf{i2}'-(b*KfuiKuuKuu))*(iKuuKuf*b'));\n gdata(i1) = gdata(i1) + 0.5.*(2.*(sum(iLav'*sum(DKuf{i2}'.*iKuuKuf',2))-sum(sum(L'.*(L'*DKuf{i2}'*iKuuKuf))))...\n - sum(iLav'*sum(KfuiKuuKuu.*iKuuKuf',2))+ sum(sum(L'.*((L'*KfuiKuuKuu)*iKuuKuf))));\n \n if strcmp(gp.type, 'VAR')\n gdata(i1) = gdata(i1) + 0.5.*(0-2.*sum(iLav'*sum(DKuf{i2}'.*iKuuKuf',2)) + ...\n sum(iLav'*sum(KfuiKuuKuu.*iKuuKuf',2)));\n end\n end\n end\n end\n end\n end\n \n case {'KALMAN'}\n % ============================================================\n % Kalman filtering and smoothing\n % ============================================================\n %\n % The implementation below is primarily based on the methods\n % presented in the following publication. If you find this\n % useful as a part of your own research, please cite the papers.\n %\n % [1] Simo Sarkka, Arno Solin, Jouni Hartikainen (2013).\n % Spatiotemporal learning via infinite-dimensional Bayesian\n % filtering and smoothing. IEEE Signal Processing Magazine,\n % 30(4):51-61.\n %\n % [2] Simo Sarkka (2013). Bayesian filtering and smoothing.\n % Cambridge University Press.\n %\n % [3] Simo Sarkka (2006). Recursive Bayesian inference on stochastic\n % differential equations. Doctoral dissertation, Helsinki\n % University of Technology, Finland.\n %\n \n % Ensure that this is a purely temporal problem\n if size(x,2) > 1,\n error('The ''KALMAN'' option only supports one-dimensional data.')\n end\n \n % Extract the noise magnitude from the GP likelihood model\n R = gp.lik.sigma2;\n \n % Initialize model matrices\n F = []; L = []; Qc = [];\n H = []; Pinf = []; dF = [];\n dQc = []; dPinf = []; isstable = true;\n \n % For each covariance function\n for j=1:length(gp.cf)\n \n % Form correpsonding state space model for this covariance function\n try\n [jF,jL,jQc,jH,jPinf,jdF,jdQc,jdPinf,p] = gp.cf{j}.fh.cf2ss(gp.cf{j},x);\n catch\n gdata = nan*w; gprior = nan*w; g = nan*w;\n return\n end\n \n % Stack model\n F = blkdiag(F,jF);\n L = blkdiag(L,jL);\n Qc = blkdiag(Qc,jQc);\n H = [H jH];\n Pinf = blkdiag(Pinf,jPinf);\n \n % Should the covariance parameters be inferred?\n if ~isempty(strfind(gp.infer_params, 'covariance'))\n \n % Add derivatives\n dF = mblk(dF,jdF);\n dQc = mblk(dQc,jdQc);\n dPinf = mblk(dPinf, jdPinf);\n \n end\n \n % Set options\n isstable = isfield(p,'stationary') && (isstable && p.stationary);\n \n end\n \n % Number of partial derivatives (not including R)\n nparam = min(size(dF,3),numel(dF));\n \n % Gradient with respect to Gaussian likelihood function parameters\n if ~isempty(gp.lik.p.('sigma2')) && ...\n ~isempty(strfind(gp.infer_params, 'likelihood')) && ...\n isfield(gp.lik.fh,'trcov')\n \n % Include noise magnitude R into parameters\n nparam = nparam + 1;\n \n % Derivative of noise magnitude w.r.t. itself (1)\n dR = zeros(1,1,nparam);\n dR(end) = 1;\n \n % Derivatives of model matrices w.r.t. noise magnitude (0)\n dF(:,:,nparam) = zeros(size(F));\n dQc(:,:,nparam) = zeros(size(Qc));\n dPinf(:,:,nparam) = zeros(size(Pinf));\n \n else\n \n % Noise magnitude is not optimized\n dR = zeros(1,1,nparam);\n \n end\n \n % Sort values\n [x,ind] = sort(x(:));\n y = y(ind);\n \n % State dimension, number of data points and number of parameters\n n = size(F,1);\n steps = numel(y);\n \n % Allocate for results\n % edata = 0;\n gdata = zeros(1,nparam);\n \n % Set up\n Z = zeros(n);\n m = zeros(n,1);\n P = Pinf;\n dm = zeros(n,nparam);\n dP = dPinf;\n dt = -inf;\n QC = L*Qc*L';\n \n % Allocate space for expm results\n AA = zeros(2*n,2*n,nparam);\n AAA = zeros(4*n,4*n,nparam);\n \n % Loop over all observations\n for k=1:steps\n \n % The previous time step\n dt_old = dt;\n \n % The time discretization step length\n if (k>1)\n dt = x(k)-x(k-1);\n else\n dt = 0;\n end\n \n % Loop through all parameters (Kalman filter prediction step)\n for j=1:nparam\n \n % Should we recalculate the matrix exponential?\n if abs(dt-dt_old) > 1e-9\n \n % The first matrix for the matrix factor decomposition\n FF = [ F Z;\n dF(:,:,j) F];\n \n % Solve the matrix exponential\n AA(:,:,j) = expm2(FF*dt);\n \n end\n \n % Solve the differential equation\n foo = AA(:,:,j)*[m; dm(:,j)];\n mm = foo(1:n,:);\n dm(:,j) = foo(n+(1:n),:);\n \n if isstable\n \n % For stable systems we can use the method by Davison,\n % which simplifies everything (and speeds things up).\n \n % The discrete-time dynamical model\n if (j==1)\n A = AA(1:n,1:n,j);\n Q = Pinf - A*Pinf*A';\n PP = A*P*A' + Q;\n end\n \n % The derivatives of A and Q\n dA = AA(n+1:end,1:n,j);\n %dQ = dPinf(:,:,j) - dA*Pinf*A' - A*dPinf(:,:,j)*A' - A*Pinf*dA';\n dAPinfAt = dA*Pinf*A';\n dQ = dPinf(:,:,j) - dAPinfAt - A*dPinf(:,:,j)*A' - dAPinfAt';\n \n % The derivatives of P\n %dP(:,:,j) = dA*P*A' + A*dP(:,:,j)*A' + A*P*dA' + dQ;\n dAPAt = dA*P*A';\n dP(:,:,j) = dAPAt + A*dP(:,:,j)*A' + dAPAt' + dQ;\n \n else\n \n % The more general way for closed-form integration of\n % the covariance by matrix fraction decomposition.\n \n % Should we recalculate the matrix exponential?\n if abs(dt-dt_old) > 1e-9\n \n % Define W and G\n W = L*dQc(:,:,j)*L';\n G = dF(:,:,j);\n \n % The second matrix for the matrix factor decomposition\n FFF = [F QC Z Z;\n Z -F' Z Z;\n G W F QC;\n Z -G' Z -F'];\n \n % Solve the matrix exponential\n AAA(:,:,j) = expm2(FFF*dt);\n \n end\n \n % Solve using matrix fraction decomposition\n foo = AAA(:,:,j)*[P; eye(size(P)); dP(:,:,j); Z];\n \n % Pick the parts\n C = foo( (1:n),:);\n D = foo( n+(1:n),:);\n dC = foo(2*n+(1:n),:);\n dD = foo(3*n+(1:n),:);\n \n % The prediction step covariance\n if j==1, PP = C/D; end\n \n % Sove dP for j (C/D == P_{k|k-1})\n dP(:,:,j) = (dC - PP*dD)/D;\n \n end\n end\n \n % Set predicted m and P\n m = mm;\n P = PP;\n \n % Start the Kalman filter update step and precalculate variables\n S = H*P*H' + R;\n [LS,notposdef] = chol(S,'lower');\n \n % If matrix is not positive definite, add jitter\n if notposdef>0,\n jitter = gp.jitterSigma2*diag(rand(size(S,1),1));\n [LS,notposdef] = chol(S+jitter,'lower');\n \n if notposdef>0,\n gdata = nan; gprior = nan; g = nan;\n return;\n end\n end\n \n % Continue update\n HtiS = H'/LS/LS';\n iS = eye(size(S))/LS/LS';\n K = P*HtiS;\n v = y(k) - H*m;\n vtiS = v'/LS/LS';\n \n % Loop through all parameters (Kalman filter update step derivative)\n for j=1:nparam\n \n % Innovation covariance derivative\n dS = H*dP(:,:,j)*H' + dR(:,:,j);\n \n % Evaluate the energy derivative for j (optimized from above)\n gdata(j) = gdata(j) ...\n + .5*sum(iS(:).*dS(:)) ...\n - .5*(H*dm(:,j))*vtiS' ...\n - .5*vtiS*dS*vtiS' ...\n - .5*vtiS*(H*dm(:,j));\n \n % Kalman filter update step derivatives\n dK = dP(:,:,j)*HtiS - P*HtiS*dS/LS/LS';\n dm(:,j) = dm(:,j) + dK*v - K*H*dm(:,j);\n dKSKt = dK*S*K';\n dP(:,:,j) = dP(:,:,j) - dKSKt - K*dS*K' - dKSKt';\n \n end\n \n % Evaluate the energy (but only gradient required)\n %edata = edata + .5*size(S,1)*log(2*pi) + sum(log(diag(LS))) + .5*vtiS*v;\n \n % Finish Kalman filter update step\n m = m + K*v;\n P = P - K*S*K';\n \n end\n \n % Take all priors into account in the gradient\n gprior = [];\n if ~isempty(strfind(gp.infer_params, 'covariance'))\n for i=1:length(gp.cf)\n gprior = [gprior, -gp.cf{i}.fh.lpg(gp.cf{i})];\n end\n end\n \n gprior_lik = -gp.lik.fh.lpg(gp.lik);\n if ~isempty(gp.lik.p.('sigma2')) && ...\n ~isempty(strfind(gp.infer_params, 'likelihood')) && ...\n isfield(gp.lik.fh,'trcov')\n gprior = [gprior gprior_lik];\n end\n \n % Account for log transform\n w = gp_pak(gp);\n \n % Take correct values from w\n if length(gdata) < length(w)\n if any(hier==0)\n w = w([hier(1:find(hier==0,1)-1)==1 ... % Covariance function\n hier(find(hier==0,1):find(hier==0,1)+...\n length(gprior_lik)-1)==0]); % Likelihood function\n else\n w = w(hier==1);\n end\n end\n \n % Log-transformation\n [w,ws] = gp_pak(gp);\n ind = strncmpi(ws,'log(',4) & ~strncmpi(ws,'log(log(',8);\n gdata(ind) = gdata(ind).*exp(w(ind));\n \n % Log-log-transformation\n ind = strncmpi(ws,'log(log(',8);\n gdata(ind) = gdata(ind).*exp(w(ind)+exp(w(ind)));\n \n otherwise\n error('Unknown type of Gaussian process!')\nend\n\n% If ther parameters of the model (covariance function parameters,\n% likelihood function parameters, inducing inputs, mean function\n% parameters) have additional hyperparameters that are not fixed,\n% set the gradients in correct order\nif length(gprior) > length(gdata)\n %gdata(gdata==0)=[];\n tmp=gdata;\n gdata = zeros(size(gprior));\n % Set the gradients to right place\n if any(hier==0)\n gdata([hier(1:find(hier==0,1)-1)==1 ... % Covariance function\n hier(find(hier==0,1):find(hier==0,1)+length(gprior_lik)-1)==0 ... % Likelihood function\n hier(find(hier==0,1)+length(gprior_lik):end)==1 | ... % Inducing inputs or ...\n hier(find(hier==0,1)+length(gprior_lik):end)==-1]) = tmp; % Mean function parameters\n else\n if any(hier<0)\n hier(hier==-1)=1;\n end\n gdata(hier==1) = tmp;\n end\nend\ng = gdata + gprior;\n\nfunction C = mblk(A,B)\n%% mblk - Stack matrices by third dimension\n\n% Get sizes\nsA=size(A); sB=size(B);\n\n% Check if A or B is empty\nAe = ~any(sA==0); Be = ~any(sB==0);\n\n% Numel of sizes to 3\nsA = [sA Ae]; sA = sA(1:3);\nsB = [sB Be]; sB = sB(1:3);\n\n% Assign space for C\nC = zeros(sA+sB);\n\n% Set values of A if there is any\nif Ae\n C(1:sA(1), 1:sA(2), 1:sA(3)) = A;\nend\n\n% Set values of B if there is any\nif Be\n C(sA(1)+(1:sB(1)), ...\n sA(2)+(1:sB(2)), ...\n sA(3)+(1:sB(3))) = B;\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/gp_g.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.3210365487727679}} {"text": "function [imgOut, BTMO_segments, BTMO_which_operator] = BanterleTMO(img, BTMO_segments, BTMO_rescale)\n%\n%\n% [imgOut, BTMO_segments, BTMO_which_operator] = BanterleTMO(img, BTMO_segments)\n%\n%\n% Input:\n% -img: an HDR image with calibrated data in cd/m^2.\n% Note that this algorithm was tested with values\n% from 0.015cd/m^2 to 3,000 cd/m^2\n% -BTMO_segments: a segmented image, each value in a segment is a\n% dynamic range zone; i.e. integer values in [-6,9]. If it is not\n% provided this will be computed with the function CreateSegments\n% -BTMO_rescale:\n%\n% Output:\n% -imgOut: the tone mapped image using the HybridTMO\n% -BTMO_segments: the segmentation output; the input image is\n% segmented into different zones of dynamic range\n% -BTMO_which_operator: is a string which outputs if only\n% DragoTMO is used, if only Reinhard is used, or if the full\n% BanterleTMO is used.\n% \n% This TMO is an hybrid operator which merges different\n% Tone Mapping Operators: DragoTMO and ReinhardTMO\n%\n% Copyright (C) 2013-15 Francesco Banterle\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n%\n% The paper describing this technique is:\n% \"Dynamic Range Compression by Differential Zone Mapping Based on \n% Psychophysical Experiments\"\n% \t by Francesco Banterle, Alessandro Artusi, Elena Sikudova, \n% Thomas Edward William Bashford-Rogers, Patrick Ledda, Marina Bloj, Alan Chalmers \n% in ACM Symposium on Applied Perception (SAP) - August 2012 \n%\n%\n\ncheckNegative(img);\n\nif(~exist('BTMO_rescale', 'var'))\n BTMO_rescale = 1;\nend\n\nL = lum(img);\n\nif(BTMO_rescale)\n L_max = MaxQuart(L, 0.999);\n\n if(L_max > 0.0)\n img = img / L_max * 3000.0;\n img = ClampImg(img, 0.015, 3000.0);\n L = lum(img);\n end\nend\n\nindx = find(L > 3000);\nif(~isempty(indx))\n warning(['The input image has values over 3,000 cd/m^2. ', ...\n 'These values were not tested in the original paper.']);\nend\n\nindx = find(L < 0.015);\nif(~isempty(indx))\n warning(['The input image has values under 0.015 cd/m^2. ', ...\n 'These values were not tested in the original paper.']);\nend\n\n%segmentation\nif(~exist('BTMO_segments', 'var'))\n BTMO_segments = CreateSegments(img);\nelse \n if(isempty(BTMO_segments))\n BTMO_segments = CreateSegments(img); \n else \n BTMO_segments = round(BTMO_segments);\n end\nend\n\n%TMO look-up table for determing the best\n%TMO depending on the luminance zone. These\n%values were extracted from a psychophysical\n%experiment.\n% 0 ---> Drago et al. 2003\n% 1 ---> Reinhard et al. 2002\nLumZone = [-2, -1, 0, 1, 2, 3, 4];\nTMOForZone = [ 0, 0, 1, 0, 1, 0, 0];\n\n%mask\nmask = zeros(size(BTMO_segments));\n\nfor i=1:length(LumZone)\n mask(BTMO_segments == LumZone(i)) = TMOForZone(i);\nend\n\nimwrite(mask, 'mask.png');\n%check for Drago et al.'s operator\nindx0 = find(mask == 1);\n\n%check for Reinhard et al.'s operator\nindx1 = find(mask == 0);\n\n%are both TMOs used?\nif(~isempty(indx0) && ~isempty(indx1)) %pyramid blending with gamma encoding\n img_dra_tmo = DragoTMO(img);\n img_rei_tmo = ReinhardTMO(img, 0.5, -1, 'local', -1);\n\n gamma = 2.2;\n invGamma = 1.0 / gamma;\n imgA = img_rei_tmo.^invGamma;\n imgB = img_dra_tmo.^invGamma;\n \n imwrite(imgA, 'banterle_rei.png');\n imwrite(imgB, 'banterle_dra.png');\n imwrite(mask, 'banterle_mask.png');\n \n %removing gamma for linear output\n imgOut = pyrBlend(imgA, imgB, mask).^gamma;\n imwrite(imgOut.^invGamma, 'banterle_mix.png');\n \n BTMO_which_operator = 'BanterleTMO';\nelse\n %Only Reinhard et al.'s operator?\n length(indx1)\n length(indx0)\n if(isempty(indx1))\n imgOut = ReinhardTMO(img, -1, -1, 'bilateral', -1);\n BTMO_which_operator = 'ReinhardTMO';\n disp('The BanterleTMO is using ReinhardTMO only');\n end\n \n %Only Drago et al.'s operator?\n if(isempty(indx0))\n imgOut = DragoTMO(img);\n BTMO_which_operator = 'DragoTMO';\n disp('The BanterleTMO is using DragoTMO only');\n end \nend\n\nend\n", "meta": {"author": "banterle", "repo": "HDR_Toolbox", "sha": "a2b45dc48b7169192fb633097a83879e71a0c0f2", "save_path": "github-repos/MATLAB/banterle-HDR_Toolbox", "path": "github-repos/MATLAB/banterle-HDR_Toolbox/HDR_Toolbox-a2b45dc48b7169192fb633097a83879e71a0c0f2/source_code/Tmo/BanterleTMO.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6370307944803832, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.32100374815570765}} {"text": "classdef edgefx\n % EDGEFX: Edgefunction class\n % Constructs edgefunctions that are based on numerous geomteric and\n % topographic criteria that guide the spatially variability of elemental\n % resolution when building a mesh.\n % Copyright (C) 2018 Keith Roberts & William Pringle\n %\n % The following properties are available for input to the edgefx method:\n % Keyword Default Val\tVariable type\n % 'dis' defval; scalar\n % 'fs' defval; scalar\n % 'wl' defval; scalar/array\n % 'slp' defval; scalar/array\n % 'ch' defval; scalar\n % 'min_el_ch' 100; \tscalar\n % 'AngOfRe' 60; \tscalar\n % 'max_el' inf; scalar/array\n % 'max_el_ns' inf; \tscalar\n % 'g' 0.20; scalar/array\n % 'geodata' defval; geodata class\n % 'lmsl' defval; geodata class\n % 'dt' -1; scalar\n % 'fl' defval; scalar\n % 'Channels' defval; \tcell array\n % 'h0' defval; scalar\n % [defval = 0; % placeholder value if arg is not passed.]\n %\n % The 'wl','slp','max_el','g' options inputs can be scalars to apply\n % the parameter globally or they can be arrays to bound each parameter \n % value within topographic elevation bounds, using the following stucture:\n % [parameter_value1 z_min1 z_max1;\n % parameter_value2 z_min2 z_max2;\n % ...\n % parameter_valuen z_minn z_maxn];\n %\n % where, z_min is the minimum elevation bound and z_max is the maximum elevation bound. \n % - similar to axis bounds on matlab plots such as caxis, xlim, ylim, ...\n % - z is oriented same as the DEM, i.e., +ve value of z is above datum (overland) \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 properties\n nx % number of x coords\n ny % number of y coords\n x0y0 % 2-tuple of bot. left of domain\n\n lmsl % lmsl boundary as a geodata class\n\n bbox\n boubox\n used % edge function keywords\n\n dis % percent the edgelength changes in space\n fd % distance function\n hhd % matrix containing distance fx values.\n fs % number of elements to resolve a feature\n fsd % matrix containing feature size fx values.\n wl % wavelength\n wld % matrix containing wavelength fx values.\n slp % slope edge function\n slpd % matrix containing filtered slope fx values.\n fl % slope filter parameters\n ch % channels\n chd % matrix containing channel fx values.\n AngOfRe % Angle of reslope\n g % max allowable grade of mesh.\n dt % theoretical simulateable timestep\n\n F % edge function in gridded interpolant format.\n\n h0 % min. resolution of edgelength function in meters\n gridspace % edgelength function resolution in WGS84 degrees.\n max_el % max. resolution in domain\n max_el_ns % max. resolution +-<0.01 from shoreline\n boudist % distance in WGS84 degrees to boundary of mesh\n\n min_el_ch % min. element size along the channel\n Channels % cell array of streams.\n\n end\n\n methods\n\n %% Class constructor/pass it a shape class and edgefx params.\n function obj = edgefx(varargin)\n % Check for m_map dir\n M_MAP_EXISTS=0 ;\n if exist('m_proj','file')==2\n M_MAP_EXISTS=1 ;\n end\n if M_MAP_EXISTS~=1\n error('Where''s m_map? Chief, you need to read the user guide')\n end\n\n % Check for utilties dir\n UTIL_DIR_EXISTS=0 ;\n if exist('inpoly.m','file')\n UTIL_DIR_EXISTS=1 ;\n end\n if UTIL_DIR_EXISTS~=1\n error('Where''s the utilities directory? Chief, you need to read the user guide')\n end\n\n p = inputParser;\n\n defval = 0; % placeholder value if arg is not passed.\n % add name/value pairs\n addOptional(p,'dis',defval);\n addOptional(p,'fs',defval);\n addOptional(p,'wl',defval);\n addOptional(p,'slp',defval);\n addOptional(p,'ch',defval);\n addOptional(p,'min_el_ch',100);\n addOptional(p,'AngOfRe',60);\n addOptional(p,'max_el',inf);\n addOptional(p,'max_el_ns',inf);\n addOptional(p,'g',0.20);\n addOptional(p,'geodata',defval)\n addOptional(p,'lmsl',defval)\n addOptional(p,'dt',-1);\n addOptional(p,'fl',defval);\n addOptional(p,'Channels',defval);\n addOptional(p,'h0',defval);\n\n % parse the inputs\n parse(p,varargin{:});\n % store the inputs as a struct\n inp = p.Results;\n % get the fieldnames of the edge functions\n inp = orderfields(inp,{'max_el','min_el_ch','AngOfRe',...\n 'geodata','lmsl','Channels',...\n 'dis','fs','fl','g','max_el_ns',...\n 'wl','slp','ch','dt','h0'});\n fields = fieldnames(inp);\n % loop through and determine which args were passed.\n % also, assign reasonable default values if some options were\n\n % not assigned.\n for i = 1 : numel(fields)\n type = fields{i};\n switch type\n % parse aux options first\n case('max_el')\n obj.max_el = inp.(fields{i});\n if ~isempty(obj.max_el)\n obj.max_el = inp.(fields{i});\n end\n case('max_el_ns')\n obj.max_el_ns= inp.(fields{i});\n if obj.max_el_ns ~=0\n obj.max_el_ns = inp.(fields{i});\n end\n % obj.max_el_ns = obj.max_el_ns/111e3;\n case('g')\n obj.g= inp.(fields{i});\n if obj.g ~=0\n obj.g = inp.(fields{i});\n end\n case('fl')\n obj.fl = inp.(fields{i});\n if obj.fl ~=0\n obj.fl = inp.(fields{i});\n end\n case('geodata')\n if isa(inp.(fields{i}),'geodata')\n feat = inp.(fields{i});\n end\n case('lmsl')\n if isa(inp.(fields{i}),'geodata')\n obj.lmsl = inp.(fields{i});\n end\n case('dt')\n obj.dt=inp.(fields{i});\n if obj.dt >= 0\n obj.dt = inp.(fields{i});\n end\n case('h0')\n obj.h0=inp.(fields{i});\n if obj.h0 ~= 0\n obj.h0 = inp.(fields{i});\n else\n obj.h0 = feat.h0;\n end\n case('min_el_ch')\n obj.min_el_ch=inp.(fields{i});\n if obj.min_el_ch ~= 100\n obj.min_el_ch = inp.(fields{i});\n end\n case('AngOfRe')\n obj.AngOfRe=inp.(fields{i});\n if obj.AngOfRe ==60\n obj.AngOfRe = inp.(fields{i});\n end\n case('Channels')\n obj.Channels=inp.(fields{i});\n if ~isempty(obj.Channels) ~=0\n obj.Channels = inp.(fields{i});\n end\n end\n end\n\n % kjr april 28, 2018-form mesh size grid on-the-fly\n obj.fd = @dpoly;\n obj.x0y0 = feat.x0y0 + sqrt(eps);\n obj.gridspace = obj.h0/111e3;\n obj.nx = ceil(abs(feat.x0y0(1)-feat.bbox(1,2))/obj.gridspace);\n obj.ny = ceil(abs(feat.x0y0(2)-feat.bbox(2,2))/obj.gridspace);\n obj.bbox = feat.bbox;\n obj.boubox = feat.boubox;\n\n % WJP: Do Mercator projection for calculating\n % distances from shoreline\n if feat.bbox(1,2) > 180\n m_proj('mercator','lat', [-88 90], 'long',[0 360]);\n else\n m_proj('mercator','lat', [-88 90],'long',[-180 180]);\n end\n % now turn on the edge functions\n for i = 1 : numel(fields)\n type = fields{i};\n switch type\n case('dis')\n obj.dis = inp.(fields{i});\n if obj.dis ~= 0\n disp('Building distance function...');\n obj = distfx(obj,feat);\n obj.used{end+1} = 'dis';\n end\n case('fs')\n obj.fs = inp.(fields{i});\n if obj.fs ~= 0\n disp('Building feature size function...');\n try\n obj = featfx(obj,feat);\n obj.used{end+1} = 'fs';\n catch\n disp('man, no medial points!')\n end\n end\n case('wl')\n obj.wl = inp.(fields{i});\n if obj.wl(1)~=0 && ~isempty(feat.Fb)\n disp('Building wavelength function...');\n obj = wlfx(obj,feat);\n obj.used{end+1} = 'wl';\n end\n case('slp')\n obj.slp = inp.(fields{i});\n if obj.slp(1) ~= 0 && ~isempty(feat.Fb)\n disp('Building slope function...');\n obj = slpfx(obj,feat);\n obj.used{end+1} = 'slp';\n end\n case('ch')\n obj.ch = inp.(fields{i});\n if obj.ch ~= 0\n disp('Building channel function...');\n obj = chfx(obj,feat);\n obj.used{end+1} = 'ch';\n end\n case{'g','geodata','lmsl','max_el','min_el_ch',...\n 'Channels','max_el_ns','h0','dt','fl','AngOfRe'}\n % dummy to avoid warning\n otherwise\n warning('Unexpected edge function name/value pairs.')\n end\n if i==numel(fields)\n obj = finalize(obj,feat);\n disp('Finalized edge function!');\n end\n end\n end\n\n %% Traditional distance function, linear distance from coastline.\n function obj = distfx(obj,feat)\n [d,obj] = get_dis(obj,feat);\n obj.boudist = d;\n obj.hhd = obj.h0 + obj.dis*abs(d);\n end\n %% Feature size function, approximates width of nearshore geo.\n function obj = featfx(obj,feat)\n if isempty(feat.mainland) && isempty(feat.inner)\n % No medial points so use distance function using grade\n warning('No mainland or inner')\n xg = CreateStructGrid(obj);\n obj.fsd = xg*NaN;\n clearvars xg\n return\n end\n % Make sure we don't create a singularity on the coast in the\n % distance function!\n [d,obj] = get_dis(obj,feat);\n obj.boudist = d ;\n\n [xg,yg] = CreateStructGrid(obj);\n % use a harvestine assumption\n dx = obj.h0*cosd(yg(1,:)); % for gradient function\n dy = obj.h0; % for gradient function\n % Calculate the gradient of the distance function.\n [ddy,ddx] = EarthGradient(d,dy,dx);\n d_fs = sqrt(ddx.^2 + ddy.^2);\n clearvars ddx ddy\n % WJP: This fix is to put a medial point in narrow channels\n rf = []; cf = [];\n for ii = 2:size(d,1)-1\n for jj = 2:size(d,2)-1\n if d(ii,jj) < 0\n if (d(ii-1,jj) >= 0 && ...\n d(ii+1,jj) >= 0) || ...\n (d(ii,jj-1) >= 0 && ...\n d(ii,jj+1) >= 0)\n rf(end+1) = ii;\n cf(end+1) = jj;\n end\n end\n end\n end\n % Find singularties in the distance function that are\n % within the poly to get the medial axis.\n % Lets only create medial points in places that are\n % sufficiently far away from the coastline to capture the\n % feature and thus aren't spurious.\n d_fs = reshape(d_fs,[],1); d = reshape(d,[],1);\n lg = d_fs < 0.90 & d < -0.5*obj.h0 ;\n [r,c] = ind2sub([obj.nx obj.ny],find(lg));\n % create the coordinates using x0y0 + r*h0\n r = [r; rf']; c = [c; cf']; %WJP: add on \"fixed points\"\n x_kp = obj.x0y0(1) + (r-1)*obj.gridspace;\n y_kp = obj.x0y0(2) + (c-1)*obj.gridspace;\n clearvars lg r c cf rf\n % Ensure there are enough medial points nearby\n % to avoid surpurious medial points.\n % WJP: We want a line of points larger than around 7. This\n % corresponds to having three points back or forward up the\n % line. Let's check for those three closest points and ensure\n % they are within about co*h0 distance from each other.\n % co is the cutoff distance = 2*sqrt(2) (two diagonal dist)\n co = 2*sqrt(2);\n if length(x_kp) > 12\n [~, dmed] = WrapperForKsearch([x_kp,y_kp],[x_kp,y_kp],4);\n prune = dmed(:,2) > co*obj.h0 | dmed(:,3) > 2*co*obj.h0 | ...\n dmed(:,4) > 3*co*obj.h0;\n x_kp( prune ) = [];\n y_kp( prune ) = [];\n end\n\n % Now get the feature size along the coastline\n if length(x_kp) > 12\n % Use KD-tree\n dPOS = 0*d;\n noblks = ceil(length(dPOS)*2*8*1e-9);\n blklen = floor(length(dPOS)/noblks);\n ns = 1;\n for blks = 1:noblks\n if blks == noblks\n ne = length(dPOS);\n else\n ne = ns + blklen - 1;\n end\n [~,dPOS(ns:ne)] = WrapperForKsearch([x_kp,y_kp],...\n [xg(ns:ne)',yg(ns:ne)'],1);\n ns = ne + 1;\n end\n else\n % No medial points so use distance function using grade\n warning('No medial points, resorting to distance function')\n d = reshape(d,obj.nx,[]);\n obj.fsd = obj.h0 + obj.g*abs(d);\n clear x_kp y_kp d d_fs dPOS xg yg\n return\n end\n % reshape back\n d = reshape(d,obj.nx,[]); dPOS = reshape(dPOS,obj.nx,[]);\n % Feature_size is distance from medial axis plus distance to\n % coastline. min_el is then feature_size*2/R where R is\n % number of elements to model the feature\n % WJP: d needs to be the absolute value because when we\n % include the floodplain since dPOS is not signed but d is,\n % they will cancel out producing really fine resolution\n W = dPOS+abs(d);\n if obj.fs < 0\n % automatic feature size\n fs_auto = min(-obj.fs,ceil(W/obj.h0));\n obj.fsd = 2*W./fs_auto;\n else\n obj.fsd = 2*W/obj.fs;\n end\n clear x_kp y_kp d d_fs dPOS xg yg\n end\n\n function [d,obj] = get_dis(obj,feat)\n % Function used by distfx and featfx to return distance\n % and make the Fdis interpolant\n d = feval(obj.fd,obj,feat);\n d = reshape(d,obj.nx,[]);\n end\n\n %% Wavelength edge function.\n function obj = wlfx(obj,feat)\n\n % interpolate DEM's bathy linearly onto our edgefunction grid.\n [xg,yg] = CreateStructGrid(obj);\n tmpz = feat.Fb(xg,yg);\n if ~isempty(feat.Fb2)\n tmpz2 = feat.Fb2(xg,yg);\n tmpz(isnan(tmpz)) = tmpz2(isnan(tmpz));\n clear tmpz2\n end\n % Initialise wld\n obj.wld = NaN([obj.nx,obj.ny]);\n grav = 9.807;\n period = 12.42*3600; % M2 period in seconds\n\n for param = obj.wl'\n if numel(param)==1\n % no bounds specified.\n wlp = param(1);\n z_min = -inf;\n z_max = +inf;\n else\n wlp = param(1);\n z_min = param(2);\n z_max = param(3);\n end\n % limit min. depth to 1 m\n twld = period*sqrt(grav*max(abs(tmpz),1))/wlp;\n limidx = (tmpz >= z_min & tmpz < z_max);\n % Set wld with depth mask applied\n obj.wld(limidx) = twld(limidx);\n clearvars twld\n end\n clearvars tmpz xg yg;\n end\n\n %% Topographic length scale/slope edge function.\n function obj = slpfx(obj,feat)\n\n [xg,yg] = CreateStructGrid(obj);\n\n tmpz = feat.Fb(xg,yg);\n if ~isempty(feat.Fb2)\n tmpz2 = feat.Fb2(xg,yg);\n tmpz(isnan(tmpz)) = tmpz2(isnan(tmpz));\n clear tmpz2\n end\n tmpz(tmpz > 50) = 50; % ensure no larger than 50 m above land\n % use a Harvestine assumption\n dx = obj.h0*cosd(min(yg(1,:),85)); % for gradient function\n dy = obj.h0; % for gradient function\n % lets filter the bathy to get only relevant features\n % loop over each set of bandpass filter lengths\n tmpz_f = zeros(size(tmpz));\n if obj.fl(1) < 0 && obj.fl(1) ~= -999\n disp('INFO: Rossby radius of deformation filter on.') ;\n rbfilt = abs(obj.fl(1));\n barot = 1;\n if length(obj.fl) > 1 && obj.fl(2) < 0\n disp('INFO: Using 1st-mode baroclinic Rossby radius.');\n barot = 0;\n else\n disp('INFO: Using barotropic Rossby radius.') ;\n end\n obj.fl = [];\n filtit = 1;\n elseif obj.fl(1) == 0\n disp('INFO: Slope filter is off.');\n obj.fl = [];\n tmpz_f = tmpz;\n filtit = 0 ;\n elseif obj.fl(1) == -999\n disp('INFO: Slope filter is LEGACY.');\n obj.fl = [];\n tmpz_f = tmpz;\n filtit = -999;\n else\n filtit = 0;\n for lambda = obj.fl'\n if length(lambda) == 1 || lambda(2) == 0\n % do a low pass filter\n tmpz_ft = filt2(tmpz,dy,lambda(1),'lp') ;\n elseif all(lambda ~= 0)\n % do a bandpass filter\n tmpz_ft = filt2(tmpz,dy,lambda,'bp') ;\n else\n % highpass filter not recommended\n warning(['Highpass filter on bathymetry in slope' ...\n 'edgelength function is not recommended'])\n tmpz_ft = filt2(tmpz,dy,lambda(2),'hp') ;\n end\n tmpz_f = tmpz_f + tmpz_ft;\n end\n end\n\n % Rossby radius of deformation filter\n if filtit == 1\n tic\n bs = NaN([obj.nx,obj.ny]);\n % break into 10 deg latitude chunks, or less if higher res\n div = ceil(min(1e7/obj.nx,10*obj.ny/(max(yg(:))-min(yg(:)))));\n grav = 9.807;\n nb = ceil(obj.ny/div);\n n2s = 1;\n for jj = 1:nb\n n2e = min(obj.ny,n2s + div - 1);\n % Rossby radius of deformation filter\n % See Shelton, D. B., et al. (1998): Geographical variability of the first-baroclinic Rossby radius of deformation. J. Phys. Oceanogr., 28, 433-460.\n ygg = yg(:,n2s:n2e);\n dxx = mean(dx(n2s:n2e));\n f = 2*7.29e-5*abs(sind(ygg));\n if barot\n % barotropic case\n c = sqrt(grav*max(1,-tmpz(:,n2s:n2e)));\n else\n % baroclinic case (estimate Nm to be 2.5e-3)\n Nm = 2.5e-3;\n c = Nm*max(1,-tmpz(:,n2s:n2e))/pi;\n end\n rosb = c./f;\n clear f;\n % update for equatorial regions\n I = abs(ygg) < 5; Re = 6371e3;\n twobeta = 4*7.29e-5*cosd(ygg(I))/Re;\n rosb(I) = sqrt(c(I)./twobeta);\n clear twobeta\n % limit rossby radius to 10,000 km for practical purposes\n rosb(rosb > 1e7) = 1e7;\n % Keep lengthscales rbfilt * barotropic\n % radius of deformation\n rosb = min(10,max(0,floor(log2(rosb/dy/rbfilt))));\n edges = double(unique(rosb(:)));\n bst = rosb*0;\n for i = 1:length(edges)\n if edges(i) > 0\n mult = 2^edges(i);\n xl = 1; xu = obj.nx;\n if (max(xg(:)) > 179 && min(xg(:)) < -179) || ...\n (max(xg(:)) > 359 && min(xg(:)) < 1)\n % wraps around\n xr = [obj.nx-mult/2+1:1:obj.nx xl:xu 1:mult/2];\n else\n xr = xl:xu;\n end\n yl = max(1,n2s-mult/2);\n yu = min(obj.ny,n2e+mult/2);\n if max(yg(:)) > 89 && yu == obj.ny\n % create mirror around pole\n yr = [yl:yu yu-1:-1:2*obj.ny-n2e-mult/2];\n else\n yr = yl:yu;\n end\n if mult == 2\n tmpz_ft = filt2(tmpz(xr,yr),...\n [dxx dy],dy*2.01,'lp');\n else\n tmpz_ft = filt2(tmpz(xr,yr),...\n [dxx dy],dy*mult,'lp');\n end\n % delete the padded region\n tmpz_ft(1:find(xr == 1,1,'first')-1,:) = [];\n tmpz_ft(obj.nx+1:end,:) = [];\n tmpz_ft(:,1:find(yr == n2s,1,'first')-1) = [];\n tmpz_ft(:,n2e-n2s+2:end) = [];\n else\n tmpz_ft = tmpz(:,n2s:n2e);\n end\n [by,bx] = EarthGradient(tmpz_ft,dy,dx(n2s:n2e)); % get slope in x and y directions\n tempbs = sqrt(bx.^2 + by.^2); % get overall slope\n bst(rosb == edges(i)) = tempbs(rosb == edges(i));\n end\n bs(:,n2s:n2e) = bst;\n n2s = n2e + 1;\n end\n toc\n % legacy filter\n elseif filtit==-999\n bs = NaN([obj.nx,obj.ny]);\n % Rossby radius of deformation filter\n f = 2*7.29e-5*abs(sind(yg));\n % limit to 1000 km\n rosb = min(1000e3,sqrt(9.81*abs(tmpz))./f);\n % autmatically divide into discrete bins\n [~,edges] = histcounts(rosb);\n tmpz_ft = tmpz; dyb = dy;\n % get slope from filtered bathy for the segment only\n [by,bx] = EarthGradient(tmpz_ft,dy,dx); % get slope in x and y directions\n tempbs = sqrt(bx.^2 + by.^2); % get overall slope\n for i = 1:length(edges)-1\n sel = rosb >= edges(i) & rosb <= edges(i+1);\n rosbylb = mean(edges(i:i+1));\n if rosbylb > 2*dyb\n disp(['i = ',num2str(i), ' rl/dx = ',num2str(rosbylb/dyb)])\n tmpz_ft = filt2(tmpz_ft,dyb,rosbylb,'lp');\n dyb = rosbylb;\n % get slope from filtered bathy for the segment only\n [by,bx] = EarthGradient(tmpz_ft,dy,dx); % get slope in x and y directions\n tempbs = sqrt(bx.^2 + by.^2); % get overall slope\n else\n % otherwise just use the same tempbs from before\n end\n % put in the full one\n bs(sel) = tempbs(sel);\n end\n else\n % get slope from (possibly filtered) bathy\n [by,bx] = EarthGradient(tmpz_f,dy,dx); % get slope in x and y directions\n bs = sqrt(bx.^2 + by.^2); % get overall slope\n end\n clear bx by tmpz_f tmpz_ft\n\n % Allow user to specify depth ranges for slope parameter.\n obj.slpd = NaN([obj.nx,obj.ny]);\n for param = obj.slp'\n if numel(param)==1\n % no bounds specified. valid in this range.\n slpp = param(1);\n z_min = -inf;\n z_max = +inf;\n else\n slpp = param(1);\n z_min = param(2);\n z_max = param(3);\n end\n % Calculating the slope function\n dp = max(1,-tmpz);\n tslpd = (2*pi/slpp)*dp./(bs+eps);\n % apply slope with mask\n limidx = (tmpz >= z_min & tmpz < z_max);\n obj.slpd(limidx) = tslpd(limidx);\n clearvars tslpd\n end\n clearvars tmpz xg yg\n end\n\n %% Channel edgefunction\n function obj = chfx(obj,feat)\n\n ang_of_reslope=obj.AngOfRe ; % Estimate width of channel using tangent of this angle times depth.\n\n % STEP 1: Calculate the width of each channel using a v-shape approx to\n % channel's cross sectional area.\n for jj = 1:length(obj.Channels)\n if (isempty(obj.Channels{jj})); continue ;end\n pts{jj} = obj.Channels{jj};\n dp{jj} = feat.Fb(pts{jj}); % depth at x,y channel locations\n radii{jj}=(tand(ang_of_reslope)*max(1,-dp{jj})); % estimate of channel's width in degrees at x,y locations ASSUMING angle of reslope\n tempbb{jj} = feat.boubox;\n end\n\n [xg,yg] = CreateStructGrid(obj);\n\n % STEP 2: For each channel point, set the resolution around a\n % neighborhood of points as |h|/ch where ch is non-dim # between 0.5-1.5\n obj.chd = NaN([obj.nx,obj.ny]);\n % prune the potentially large channel network to only ones\n % partially enclosed in boubox\n isin = cellfun(@inpolysum,pts,tempbb);\n pts(isin==0) = []; radii(isin==0)= [];\n\n %figure; plot(xg,yg,'k.');\n tic\n tidx = [];\n for jj =1:length(pts) % For each channel jj\n sel = pts{jj};\n in = inpoly(sel,feat.boubox(1:end-1,:));\n sel(~in,:) = [];\n for jjj = 1 : size(sel,1) % For each channel point jjj on channel jj.\n % will the stencil be too large (nidx^2)?\n nidx = ceil(radii{jj}(jjj)/obj.h0); % stencil of points around channel point.\n % find linear index of channel point in 2-d matrix.\n [lidx] = FindLinearIdx(sel(jjj,1),sel(jjj,2),xg,yg);\n % convert to r,c or grid indices.\n [r,c] = ind2sub(size(xg),lidx);\n [cid,rid] = ndgrid(c-nidx:c+nidx,r-nidx:r+nidx); % grid of nearby points\n % ensure that all these points are within the domain.\n rid = min(max(rid(:),1),size(xg,1));\n cid = min(max(cid(:),1),size(xg,2));\n % convert back to linear indices.\n temp = sub2ind(size(xg),rid,cid);\n tidx = [tidx; temp];\n end\n end\n toc\n tmpz = feat.Fb(xg(tidx),yg(tidx));\n if ~isempty(feat.Fb2)\n tmpz2 = feat.Fb2(xg(tidx),yg(tidx));\n tmpz(isnan(tmpz)) = tmpz2(isnan(tmpz));\n clear tmpz2\n end\n dp = max(1,-tmpz);\n obj.chd(tidx) = dp/obj.ch;\n obj.chd(obj.chd < obj.min_el_ch) = obj.min_el_ch;\n clearvars Fb pts dp radii tempbb xg yg\n end\n\n\n %% General function to plot\n function plot(obj,type)\n % form grid here.\n % working out plottable size\n [xgrid,ygrid] = CreateStructGrid(obj);\n\n if nargin == 2\n switch type\n case('dis')\n val = obj.hhd;\n tt = 'Distance EdgeLength Function';\n case('fs')\n val = obj.fsd;\n tt = 'Feature Size EdgeLength Function';\n case('wl')\n val = obj.wld;\n tt = 'Wavelength EdgeLength Function';\n case('ch')\n val = obj.chd;\n tt = 'Channel EdgeLength Function';\n case('slp')\n val = obj.slpd;\n tt = 'Slope EdgeLength Function';\n otherwise\n warning('Unexpected plot type. No plot created.')\n end\n else\n val = obj.F.Values;\n tt = 'Total EdgeLength Function';\n end\n\n % working out stride\n mem = inf; stride = obj.gridspace;\n while mem > 1\n xx = obj.x0y0(1):stride:obj.bbox(1,2);\n yy = obj.x0y0(2):stride:obj.bbox(2,2);\n xs = whos('xx'); ys = whos('yy');\n mem = xs.bytes*ys.bytes/1e9;\n stride = stride*2;\n end\n stride = ceil(stride/obj.gridspace);\n I = [1:stride:size(xgrid,1)];\n J = [1:stride:size(xgrid,2)];\n\n figure;\n m_proj('merc',...\n 'long',[obj.bbox(1,1) obj.bbox(1,2)],...\n 'lat',[obj.bbox(2,1) obj.bbox(2,2)])\n hold on; m_fastscatter(xgrid(I,J),ygrid(I,J),val(I,J));\n cb = colorbar; ylabel(cb,'edgelength in meters');\n colormap(lansey)\n m_grid() %'xtick',10,'tickdir','out',...\n % 'yaxislocation','left','fontsize',7);\n title(tt);\n end\n\n %% Finalize edge function\n % Add grading, cfl limiting and bound enforcement.\n function obj = finalize(obj,feat)\n % package the edge functions into a known order.\n counter = 0;\n hh = zeros([obj.nx,obj.ny]);\n for i = 1 : numel(obj.used)\n type = obj.used{i};\n switch type\n case('dis')\n counter = counter + 1;\n hh(:,:,counter) = obj.hhd;\n obj.hhd = single(obj.hhd);\n case('fs')\n counter = counter + 1;\n hh(:,:,counter) = obj.fsd;\n obj.fsd = single(obj.fsd);\n case('wl')\n counter = counter + 1;\n hh(:,:,counter) = obj.wld;\n obj.wld = single(obj.wld);\n case('slp')\n counter = counter + 1;\n hh(:,:,counter) = obj.slpd;\n obj.slpd = single(obj.slpd);\n case('ch')\n counter = counter + 1;\n hh(:,:,counter) = obj.chd;\n obj.ch = single(obj.chd);\n otherwise\n error('FATAL: Could not finalize edge function');\n end\n end\n\n [hh_m] = min(hh,[],3);\n clearvars hh\n\n [xg,yg] = CreateStructGrid(obj);\n\n % Before grading, ensure edgefx reflects the spacing in\n % proximity to constraints.\n if ~isempty(feat.weirs)\n % form temporary mesh size function interpolat\n % if spacing is negative -999 then it will use the mesh\n % size function to determine the spacing.\n %Ftmp = griddedInterpolant(xg,yg,hh_m,'linear','nearest');\n\n for i =1:length(feat.weirs)\n if iscell(feat.weirs)\n % get spacing in meters along the face of the weir\n weir_spacing = feat.weirs{i}(1,4);\n % get crestline points in wgs84\n txy = feat.weirs{i}(:,1:2) ;\n else\n % get spacing in meters along the face of the weir\n weir_spacing = feat.weirs(i).min_ele;\n % get crestline points in wgs84\n txy = [feat.weirs(i).X feat.weirs(i).Y];\n end\n xy = [];\n [xy(:,2),xy(:,1)] = my_interpm(txy(:,2),txy(:,1),...\n (obj.h0/2)/111e3);\n % edit the mesh size function in proximity to the weir\n for j = 1 : length(xy)\n nidx = 10 ;\n % return the indices into the mesh size function\n [lidx] = FindLinearIdx(xy(j,1),xy(j,2),xg,yg);\n [r,c] = ind2sub(size(xg),lidx);\n [cid,rid]=ndgrid((c-nidx:c+nidx)',(r-nidx:r+nidx)'); % grid of nearby points\n rid = [rid(:);r]; cid=[cid(:);c];\n hh_m(rid,cid) = weir_spacing ;\n end\n end\n end\n\n\n % enforce all mesh resolution bounds,grade and enforce the CFL in planar metres\n if ~isinf(obj.max_el_ns) && ~isempty(obj.boudist)\n nearshore = abs(obj.boudist) < 2/3*obj.h0;\n hh_m(nearshore & hh_m > obj.max_el_ns) = obj.max_el_ns;\n end\n hh_m(hh_m < obj.h0 ) = obj.h0;\n\n % Compute tmpz if necessary\n if length(obj.max_el) > 1 || length(obj.g) > 1 || obj.dt(1) >= 0\n tmpz = feat.Fb(xg,yg);\n if ~isempty(feat.Fb2)\n tmpz2 = feat.Fb2(xg,yg);\n tmpz(isnan(tmpz)) = tmpz2(isnan(tmpz));\n clear tmpz2\n end\n end\n\n for param = obj.max_el'\n if numel(param)==1 && param~=0\n mx = obj.max_el(1);\n limidx = hh_m > mx | isnan(hh_m);\n\n hh_m( limidx ) = mx;\n else\n mx = param(1);\n z_min = param(2);\n z_max = param(3);\n\n limidx = (tmpz >= z_min & tmpz < z_max) & ...\n (hh_m > mx | isnan(hh_m));\n\n hh_m( limidx ) = mx;\n end\n end\n\n % Make sure this is called before releasing memory...\n if obj.dt(1) == 0\n % Find min allowable dt based on dis or fs function\n if any(~cellfun('isempty',strfind(obj.used,'dis')))\n hh_d = obj.hhd;\n elseif any(~cellfun('isempty',strfind(obj.used,'fs')))\n hh_d = obj.fsd;\n else\n error(['FATAL: cannot use automatic timestep ' ...\n 'limiter without specifying dis or fs option']);\n end\n end\n\n obj = release_memory(obj) ;\n\n disp('Relaxing the mesh size gradient');\n if all(abs(obj.bbox(1,:)) == 180)\n % for global mesh make it cyclical\n hh_m = [hh_m(end,:); hh_m; hh_m(1,:)];\n end\n hfun = reshape(hh_m',[numel(hh_m),1]);\n\n dx = obj.h0*cosd(min(yg(1,:),85)); % for gradient function\n dy = obj.h0; % for gradient function\n\n % make g a function of space\n dmy = xg*0 ;\n for param = obj.g'\n if numel(param)==1 && param~=0\n lim = obj.g(1);\n dmy = dmy + lim ;\n else\n lim = param(1);\n z_min = param(2);\n z_max = param(3);\n\n limidx = (tmpz >= z_min & tmpz < z_max) ;\n\n dmy( limidx ) = lim;\n end\n end\n if all(abs(obj.bbox(1,:)) == 180)\n % for global mesh make it cyclical\n dmy = [dmy(end,:); dmy; dmy(1,:)];\n end\n fdfdx = reshape(dmy',[numel(dmy),1]);\n clearvars dmy;\n\n [hfun,flag] = limgradStruct(obj.ny,dx,dy,hfun,...\n fdfdx,sqrt(length(hfun)));\n if flag == 1\n disp('Gradient relaxing converged!');\n else\n error(['FATAL: Gradient relaxing did not converge, '\n 'please check your edge functions']);\n end\n % reshape it back\n hh_m = reshape(hfun,obj.ny,[])';\n clearvars hfun fdfdx\n if all(abs(obj.bbox(1,:)) == 180)\n % for global mesh make it cyclical\n hh_m = hh_m(2:end-1,:);\n hh_m(end,:) = hh_m(1,:);\n end\n\n % Limit CFL if dt >= 0, dt = 0 finds dt automatically.\n if obj.dt(1) >= 0\n if isempty(feat.Fb)\n error('No DEM supplied Can''t CFL limit.')\n end\n % Estimate wavespeed in ocean (second term represents orbital\n % velocity at 0 degree phase for 1-m amp. wave).\n grav = 9.807;\n % Limit the minimum depth to 1 m (ignore overland)\n tmpz(tmpz > - 1) = -1;\n u = sqrt(grav*abs(tmpz)) + sqrt(grav./abs(tmpz));\n\n % Desired timestep to bound edgefx\n desDt = obj.dt(1);\n if isnan(desDt)\n disp('No timestep enforcement due to no distance function')\n end\n\n % Determine Courant min. and max. bounds\n if length(obj.dt) < 2\n % default behavior if no bounds are passed\n % for explicit type schemes we ensure the maxCr is\n % bounded\n minCr = eps; % Cannot be zero!!!\n maxCr = 0.5;\n elseif length(obj.dt) == 2\n if obj.dt(1)==0.0\n error('dt = 0 is only intended for restricting the upper bound of Cr')\n end\n % minimum Courant number bound\n minCr = obj.dt(2);\n maxCr = inf;\n elseif length(obj.dt) == 3\n % minimum and maximum Courant bound\n minCr = obj.dt(2);\n maxCr = obj.dt(3);\n else\n error('Length of dt name-value pair should be <=3')\n end\n\n if minCr > maxCr\n error('MinCr is > MaxCr, please switch order in dt name value call')\n end\n\n % Automatic timestep selection option (for ADCIRC models)\n if desDt == 0\n hh_d(hh_d < obj.h0) = obj.h0;\n obj.dt = min(min(maxCr*hh_d./u));\n desDt = obj.dt;\n end\n\n % Enforcement of Courant bounds in mesh size function\n fprintf(1, [ ...\n 'Enforcing timestep of ',num2str(desDt),' seconds ', ...\n 'with Courant number bounds of ',num2str(minCr),' to ',num2str(maxCr),'\\n', ...\n ] ) ;\n\n\n Cr = (desDt*u)./hh_m; % Courant number for given desDt for mesh size variations\n\n % resolution that meets max. Cr. criteria for desDt\n dxn_min = u*desDt/maxCr;\n % resolution that meets min. Cr. criteria for desDt\n dxn_max = u*desDt/minCr;\n\n % resolve min. Cr violations\n hh_m( Cr <= minCr) = dxn_max( Cr <= minCr); %--in planar metres\n\n % resolve max. Cr violations\n hh_m( Cr > maxCr) = dxn_min( Cr > maxCr); %--in planar metres\n\n clear dxn_min dxn_max Cr\n clear u hh_d tmpz\n end\n\n\n obj.F = griddedInterpolant(xg,yg,hh_m,'linear','nearest');\n\n clearvars xg yg\n end\n\n function [xg,yg] = CreateStructGrid(obj)\n [xg,yg] = ndgrid(obj.x0y0(1) + (0:obj.nx-1)'*obj.gridspace, ...\n obj.x0y0(2) + (0:obj.ny-1)'*obj.gridspace);\n end\n\n function obj = release_memory(obj)\n % releases heavy components from data structures\n if isa(obj,'edgefx')\n disp('--------------------------------------------------');\n disp('Releasing individual edge functions from memory...');\n disp('--------------------------------------------------');\n if ~isempty(obj.fsd)\n obj.fsd = [];\n end\n\n if ~isempty(obj.wld)\n obj.wld = [];\n end\n\n if ~isempty(obj.slpd)\n obj.slpd = [];\n end\n\n if ~isempty(obj.chd)\n obj.chd = [];\n end\n\n if ~isempty(obj.ch)\n obj.ch = [];\n end\n\n if ~isempty(obj.hhd)\n obj.hhd = [];\n end\n\n if ~isempty(obj.boudist)\n obj.boudist = [];\n end\n\n if ~isempty(obj.Channels)\n obj.Channels = [];\n end\n\n if ~isempty(obj.ch)\n obj.ch = [];\n end\n\n if ~isempty(obj.boudist)\n obj.boudist = [];\n end\n end\n end\n\n\n end\n\nend\n", "meta": {"author": "CHLNDDEV", "repo": "OceanMesh2D", "sha": "56222604a5c1fe897d10c8b08cb3380ef8b43740", "save_path": "github-repos/MATLAB/CHLNDDEV-OceanMesh2D", "path": "github-repos/MATLAB/CHLNDDEV-OceanMesh2D/OceanMesh2D-56222604a5c1fe897d10c8b08cb3380ef8b43740/@edgefx/edgefx.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.3208484655425162}} {"text": "function [Hhat_LMMSE,C_LMMSE,tau_p,R,H] = functionChannelEstimates_impairments(R,channelGaindB,nbrOfRealizations,M,K,L,p,f,kappatUE,kapparBS)\n%Generate the channel realizations and estimates of these channels for all\n%UEs in the entire network. The channels are assumed to be correlated\n%Rayleigh fading. The LMMSE estimator that takes transceiver hardware\n%impairments into account is used.\n%\n%INPUT:\n%R = M x M x K x L x L matrix with spatial correlation\n% matrices for all UEs in the network. R(:,:,k,j,l) is\n% the correlation matrix for the channel between UE k\n% in cell j and the BS in cell l. This such matrix can\n% either include the average channel gain or can be\n% normalized arbitrarily.\n%channelGaindB = K x L x L matrix containing the average channel gains\n% in dB of all the channels, if these are not already\n% included in the spatial channel correlation matrices.\n% The product R(:,:,k,j,l)*10^(channelGaindB(k,j,l)/10)\n% is the full spatial channel correlation matrix.\n%nbrOfRealizations = Number of channel realizations\n%M = Number of antennas per BS\n%K = Number of UEs per cell\n%L = Number of BSs and cells\n%p = Uplink transmit power per UE (same for everyone)\n%f = Pilot reuse factor\n%kappatUE = Hardware quality of the UEs' transmitters\n%kapparBS = Hardware quality of the BSs' receivers\n%\n%OUTPUT:\n%Hhat_LMMSE = M x nbrOfRealizations x K x L x L matrix with the LMMSE\n% channel estimates. The matrix Hhat_LMMSE(:,n,k,j,l) is the\n% n:th channel estimate of the channel between UE k in cell j\n% and the BS in cell l.\n%C_LMMSE = M x M x K x L x L matrix with estimation error correlation\n% matrices when using LMMSE estimation. The matrix is\n% organized in the same way as R.\n%tau_p = Length of pilot sequences\n%R = Scaled version of the input spatial correlation matrices R,\n% where the channel gains from channelGaindB are included\n%H = M x nbrOfRealizations x K x L x L matrix with the true\n% channel realizations. The matrix is organized in the same\n% way as Hhat_LMMSE.\n%\n%\n%This Matlab function was developed to generate simulation results to:\n%\n%Emil Bjornson, Jakob Hoydis and Luca Sanguinetti (2017), \n%\"Massive MIMO Networks: Spectral, Energy, and Hardware Efficiency\", \n%Foundations and Trends in Signal Processing: Vol. 11, No. 3-4, \n%pp. 154-655. DOI: 10.1561/2000000093.\n%\n%For further information, visit: https://www.massivemimobook.com\n%\n%This is version 1.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%% Generate channel realizations\n\n%Generate uncorrelated Rayleigh fading channel realizations\nH = (randn(M,nbrOfRealizations,K,L,L)+1i*randn(M,nbrOfRealizations,K,L,L));\n\n%Prepare a matrix to save the channel gains per UE\nbetas = zeros(K,L,L);\n\n\n%Go through all channels and apply the channel gains to the spatial\n%correlation matrices\nfor j = 1:L\n \n for l = 1:L\n \n for k = 1:K\n \n %Extract channel gain in linear scale\n betas(k,j,l) = 10^(channelGaindB(k,j,l)/10);\n \n %Apply channel gain to correlation matrix\n R(:,:,k,j,l) = betas(k,j,l) * R(:,:,k,j,l);\n \n %Apply correlation to the uncorrelated channel realizations\n Rsqrt = sqrtm(R(:,:,k,j,l));\n H(:,:,k,j,l) = sqrt(0.5)*Rsqrt*H(:,:,k,j,l);\n \n end\n \n end\n \nend\n\n\n\n%% Perform channel estimation\n\n%Length of pilot sequences\ntau_p = f*K;\n\n\n%Generate pilot pattern\nif f == 1\n \n pilotPattern = ones(L,1);\n \nelseif f == 2 %Only works in the running example with its 16 BSs\n \n pilotPattern = kron(ones(2,1),[1; 2; 1; 2; 2; 1; 2; 1]);\n \nelseif f == 4 %Only works in the running example with its 16 BSs\n \n pilotPattern = kron(ones(2,1),[1; 2; 1; 2; 3; 4; 3; 4]);\n \nelseif f == 16 %Only works in the running example with its 16 BSs\n \n pilotPattern = (1:L)';\n \nend\n\n\n%Store identity matrix of size M x M\neyeM = eye(M);\n\n%Generate realizations of normalized noise\nNp = sqrt(0.5)*(randn(M,nbrOfRealizations,K,L,f) + 1i*randn(M,nbrOfRealizations,K,L,f));\n\n\n%Prepare to store LMMSE channel estimates\nHhat_LMMSE = zeros(M,nbrOfRealizations,K,L,L);\n\n%Prepare to store estimation error correlation matrices\nC_LMMSE = zeros(M,M,K,L,L);\n\n\n%% Go through all f pilot groups\nfor g = 1:f\n \n %Create transmit distortion term\n etaUE = sqrt(0.5*p*tau_p*kapparBS*(1-kappatUE))*(randn(1,nbrOfRealizations,K,L,K) + 1i*randn(1,nbrOfRealizations,K,L,K));\n \n \n %Go through all cells\n for j = 1:L\n \n %Extract the cells that belong to pilot group g\n groupMembers = find(g==pilotPattern)';\n \n \n %Go through all UEs\n for k = 1:K\n \n %Create receive distortion term\n etabarBS = sqrt(0.5*p*tau_p*(1-kapparBS))*(randn(M,nbrOfRealizations,K,L) + 1i*randn(M,nbrOfRealizations,K,L));\n \n %Sum up transmit and receive distortion terms\n etaSum = repmat(etaUE(:,:,:,:,k),[M 1 1 1]) + etabarBS;\n \n %Compute processed pilot signal for all UEs that use these pilots, according to (6.22)\n ypk = sqrt(p*kappatUE*kapparBS)*tau_p*sum(H(:,:,k,g==pilotPattern,j),4) + squeeze(sum(sum(H(:,:,:,:,j).*etaSum,4),3)) + sqrt(tau_p)*Np(:,:,k,j,g);\n \n %Compute sum of all UEs' correlation matrices to BS j\n RjAll = sum(sum(R(:,:,:,:,j),3),4);\n \n %Compute the matrix that is inverted in the LMMSE estimator\n PsiInv = (p*kappatUE*kapparBS*tau_p*sum(R(:,:,k,g==pilotPattern,j),4) + p*(1-kappatUE)*kapparBS*RjAll + p*(1-kapparBS)*diag(diag(RjAll)) + eyeM);\n \n %Go through the cells in pilot group g\n for l = groupMembers\n \n %Compute LMMSE estimate of channel between BS l and UE k in\n %cell j using (6.23) in Theorem 6.1\n RPsi = R(:,:,k,l,j) / PsiInv;\n Hhat_LMMSE(:,:,k,l,j) = sqrt(p*kappatUE*kapparBS)*RPsi*ypk;\n \n %Compute corresponding estimation error correlation matrix, using (6.26)\n C_LMMSE(:,:,k,l,j) = R(:,:,k,l,j) - p*kappatUE*kapparBS*tau_p*RPsi*R(:,:,k,l,j);\n \n end\n \n end\n \n end\n \nend\n", "meta": {"author": "emilbjornson", "repo": "massivemimobook", "sha": "4e429497dea72d52172972f3f686b34d1d047013", "save_path": "github-repos/MATLAB/emilbjornson-massivemimobook", "path": "github-repos/MATLAB/emilbjornson-massivemimobook/massivemimobook-4e429497dea72d52172972f3f686b34d1d047013/Code/functionChannelEstimates_impairments.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7520125737597971, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.3205991980610138}} {"text": "function z = min( x, y, dim )\n\n% Disciplined convex/geometric programming information:\n% MAX is convex, log-log-concave, and nondecreasing in its first\n% two arguments. Thus when used in disciplined convex programs, \n% both arguments must be concave (or affine). In disciplined \n% geometric programs, both arguments must be log-concave/affine.\n\npersistent remap remap_1 remap_2 remap_3\nerror( nargchk( 1, 3, nargin ) );\nif nargin == 2,\n\n %\n % min( X, Y )\n %\n\n sx = size( x );\n sy = size( y );\n xs = all( sx == 1 );\n ys = all( sy == 1 );\n if xs,\n sz = sy;\n elseif ys || isequal( sx, sy ),\n sz = sx;\n else\n error( 'Array dimensions must match.' );\n end\n\n %\n % Determine the computation methods\n %\n\n if isempty( remap ),\n remap1 = cvx_remap( 'real' );\n remap1 = remap1' * remap1;\n remap2 = cvx_remap( 'log-concave' )' * cvx_remap( 'nonpositive' );\n remap3 = remap2';\n remap4 = cvx_remap( 'log-concave', 'real' );\n remap4 = remap4' * remap4;\n remap5 = cvx_remap( 'concave' );\n remap5 = remap5' * remap5;\n remap = remap1 + ~remap1 .* ...\n ( 2 * remap2 + 3 * remap3 + ~( remap2 | remap3 ) .* ...\n ( 4 * remap4 + ~remap4 .* ( 5 * remap5 ) ) );\n end\n vx = cvx_classify( x );\n vy = cvx_classify( y );\n vr = remap( vx + size( remap, 1 ) * ( vy - 1 ) );\n vu = sort( vr(:) );\n vu = vu([true;diff(vu)~=0]);\n nv = length( vu );\n\n %\n % The cvx multi-objective problem\n %\n\n xt = x;\n yt = y;\n if nv ~= 1,\n z = cvx( sz, [] );\n end\n for k = 1 : nv,\n\n %\n % Select the category of expression to compute\n %\n\n if nv ~= 1,\n t = vr == vu( k );\n if ~xs,\n xt = cvx_subsref( x, t );\n sz = size( xt ); %#ok\n end\n if ~ys,\n yt = cvx_subsref( y, t );\n sz = size( yt ); %#ok\n end\n end\n\n %\n % Apply the appropriate computation\n %\n\n switch vu( k ),\n case 0,\n % Invalid\n error( 'Disciplined convex programming error:\\n Cannot perform the operation min( {%s}, {%s} )', cvx_class( xt, false, true ), cvx_class( yt, false, true ) );\n case 1,\n % constant\n cvx_optval = cvx( min( cvx_constant( xt ), cvx_constant( yt ) ) );\n case 2,\n % min( log-concave, nonpositive ) (no-op)\n cvx_optval = yt;\n case 3,\n % min( nonpositive, log-concave ) (no-op)\n cvx_optval = xt;\n case 4,\n % posy\n cvx_begin gp\n hypograph variable zt( sz )\n xt >= zt; %#ok\n yt >= zt; %#ok\n cvx_end\n case 5,\n % non-posy\n cvx_begin\n hypograph variable zt( sz )\n xt >= zt; %#ok\n yt >= zt; %#ok\n cvx_end\n otherwise,\n error( 'Shouldn''t be here.' );\n end\n\n %\n % Store the results\n %\n\n if nv == 1,\n z = cvx_optval;\n else\n z = cvx_subsasgn( z, t, cvx_optval );\n end\n\n end\n\nelse\n\n %\n % min( X, [], dim )\n %\n\n if nargin > 1 && ~isempty( y ),\n error( 'min with two matrices to compare and a working dimension is not supported.' );\n end\n sx = size( x );\n if nargin < 2,\n dim = cvx_default_dimension( sx );\n elseif ~cvx_check_dimension( dim ),\n error( 'Third argument must be a positive integer.' );\n end\n\n %\n % Determine sizes, quick exit for empty arrays\n %\n\n sx = [ sx, ones( 1, dim - length( sx ) ) ];\n nx = sx( dim );\n if any( sx == 0 ),\n sx( dim ) = min( sx( dim ), 1 );\n z = zeros( sx );\n return\n end\n sy = sx;\n sy( dim ) = 1;\n\n %\n % Type check\n %\n\n if isempty( remap_3 ),\n remap_1 = cvx_remap( 'real' );\n remap_2 = cvx_remap( 'log-concave', 'real' );\n remap_3 = cvx_remap( 'concave' );\n end\n vx = cvx_reshape( cvx_classify( x ), sx );\n t1 = all( reshape( remap_1( vx ), sx ), dim );\n t2 = all( reshape( remap_2( vx ), sx ), dim );\n t3 = all( reshape( remap_3( vx ), sx ), dim );\n t3 = t3 & ~( t1 | t2 );\n t2 = t2 & ~t1;\n ta = t1 + ( 2 * t2 + 3 * t3 ) .* ~t1;\n nu = sort( ta(:) );\n nu = nu([true;diff(nu)~=0]);\n nk = length( nu );\n\n %\n % Quick exit for size 1\n %\n\n if nx == 1 && all( nu ),\n z = x;\n return\n end\n\n %\n % Permute and reshape, if needed\n %\n\n if dim > 1 && any( sx( 1 : dim - 1 ) > 1 ),\n perm = [ dim, 1 : dim - 1, dim + 1 : length( sx ) ];\n x = permute( x, perm );\n ta = permute( ta, perm );\n sx = sx(perm);\n sy = sy(perm);\n dim = 1;\n else\n perm = [];\n end\n nv = prod( sx ) / nx;\n x = reshape( x, nx, nv );\n\n %\n % Perform the computations\n %\n\n if nk ~= 1,\n z = cvx( [ 1, nv ], [] );\n end\n for k = 1 : nk,\n\n if nk == 1,\n xt = x;\n else\n tt = ta == nu( k );\n xt = cvx_subsref( x, ':', tt );\n nv = nnz( tt ); %#ok\n end\n\n switch nu( k ),\n case 0,\n error( 'Disciplined convex programming error:\\n Invalid computation: min( {%s} )', cvx_class( xt, false, true ) );\n case 1,\n cvx_optval = min( cvx_constant( xt ), [], dim );\n case 2,\n cvx_begin gp\n hypograph variable zt( 1, nv )\n xt >= ones(nx,1) * zt; %#ok\n cvx_end\n case 3,\n cvx_begin\n hypograph variable zt( 1, nv )\n xt >= ones(nx,1) * zt; %#ok\n cvx_end\n otherwise,\n error( 'Shouldn''t be here.' );\n end\n\n if nk == 1,\n z = cvx_optval;\n else\n z = cvx_subsasgn( z, tt, cvx_optval );\n end\n\n end\n\n %\n % Reverse the reshaping and permutation steps\n %\n\n z = reshape( z, sy );\n if ~isempty( perm ),\n z = ipermute( z, perm );\n end\n\nend\n\n% Copyright 2010 Michael C. Grant and Stephen P. Boyd.\n% See the file COPYING.txt for full copyright information.\n% The command 'cvx_where' will show where this file is located.\n", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/dependencies/cvx-1.21.b795/builtins/@cvx/min.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.689305616785446, "lm_q2_score": 0.4649015713733884, "lm_q1q2_score": 0.3204592644000565}} {"text": "%%*******************************************************************\n%% HSDHKMrhsfun: compute the right-hand side vector of the\n%% Schur complement equation for the HKM direction.\n%%\n%% SDPT3: version 3.1\n%% Copyright (c) 1997 by\n%% K.C. Toh, M.J. Todd, R.H. Tutuncu\n%% Last Modified: 16 Sep 2004\n%%*******************************************************************\n\nfunction [rhs,EinvRc,hRd] = HSDHKMrhsfun(blk,At,par,X,Z,rp,Rd,sigmu,hRd,dX,dZ)\n\nm = par.m;\nif (nargin > 8)\n corrector = 1;\nelse\n corrector = 0;\n hRd = zeros(m+2,1);\nend\nhEinvRc = zeros(m+2,1);\nEinvRc = cell(size(blk,1),1);\nif length(sigmu)==1; sigmu = sigmu*ones(1,size(blk,1)); end\n%%\nfor p = 1:size(blk,1)\n pblk = blk(p,:);\n n = sum(pblk{2});\n if strcmp(pblk{1},'l')\n if (corrector)\n Rq = dX{p}.*dZ{p};\n else\n Rq = sparse(n,1);\n tmp = par.dd{p}.*Rd{p};\n tmp2 = mexMatvec(At{p},tmp,1);\n hRd = hRd + tmp2;\n end\n EinvRc{p} = sigmu(p)./Z{p}-X{p} -Rq./Z{p};\n tmp2 = mexMatvec(At{p,1},EinvRc{p},1);\n hEinvRc = hEinvRc + tmp2;\n elseif strcmp(pblk{1},'q')\n if (corrector)\n ff{p} = qops(pblk,1./par.gamz{p},Z{p},3); %#ok\n hdx = qops(pblk,par.gamz{p},ff{p},5,dX{p});\n hdz = qops(pblk,par.gamz{p},ff{p},6,dZ{p});\n hdxdz = Arrow(pblk,hdx,hdz);\n Rq = qops(pblk,par.gamz{p},ff{p},6,hdxdz);\n else\n Rq = sparse(n,1);\n tmp = par.dd{p}.*Rd{p} ...\n + qops(pblk,qops(pblk,Rd{p},par.Zinv{p},1),X{p},3) ...\n + qops(pblk,qops(pblk,Rd{p},X{p},1),par.Zinv{p},3);\n tmp2 = mexMatvec(At{p,1},tmp,1);\n hRd = hRd + tmp2;\n end\n EinvRc{p} = sigmu(p)*par.Zinv{p}-X{p} -Rq;\n tmp2 = mexMatvec(At{p,1},EinvRc{p},1);\n hEinvRc = hEinvRc + tmp2;\n elseif strcmp(pblk{1},'s')\n if (corrector)\n Rq = Prod3(pblk,dX{p},dZ{p},par.Zinv{p},0);\n Rq = 0.5*(Rq+Rq');\n else\n Rq = sparse(n,n);\n tmp = Prod3(pblk,X{p},Rd{p},par.Zinv{p},0,par.nzlistAy{p});\n EinvRc{p} = 0.5*(tmp+tmp');\n tmp2 = AXfun(pblk,At(p,:),par.permA(p,:),EinvRc(p));\n hRd = hRd + tmp2;\n end\n EinvRc{p} = sigmu(p)*par.Zinv{p}-X{p}- Rq;\n tmp2 = AXfun(pblk,At(p,:),par.permA(p,:),EinvRc(p));\n hEinvRc = hEinvRc + tmp2;\n end\nend\n%%\nrhs = rp + hRd - hEinvRc;\nrhs(m+1) = rhs(m+1) + (par.mu/par.tau - par.kap);\nif (corrector)\n rhs(m+1) = rhs(m+1) - par.dtau*par.dkap/par.tau;\nend\n%%*******************************************************************\n", "meta": {"author": "zarathustr", "repo": "LibQPEP", "sha": "99e5c23e746ace0bac4a86742c31db6fcf7297ba", "save_path": "github-repos/MATLAB/zarathustr-LibQPEP", "path": "github-repos/MATLAB/zarathustr-LibQPEP/LibQPEP-99e5c23e746ace0bac4a86742c31db6fcf7297ba/MATLAB/sdpt3/HSDSolver/HSDHKMrhsfun.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7185944046238981, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.3201550309741239}} {"text": "function obj = t1_pnp_func_new(in1,in2,in3)\ncoefs_tq1_1 = in2(1);\ncoefs_tq1_2 = in2(4);\ncoefs_tq2_1 = in2(2);\ncoefs_tq1_3 = in2(7);\ncoefs_tq2_2 = in2(5);\ncoefs_tq3_1 = in2(3);\ncoefs_tq1_4 = in2(10);\ncoefs_tq2_3 = in2(8);\ncoefs_tq3_2 = in2(6);\ncoefs_tq1_5 = in2(13);\ncoefs_tq2_4 = in2(11);\ncoefs_tq3_3 = in2(9);\ncoefs_tq1_6 = in2(16);\ncoefs_tq2_5 = in2(14);\ncoefs_tq3_4 = in2(12);\ncoefs_tq1_7 = in2(19);\ncoefs_tq2_6 = in2(17);\ncoefs_tq3_5 = in2(15);\ncoefs_tq1_8 = in2(22);\ncoefs_tq2_7 = in2(20);\ncoefs_tq3_6 = in2(18);\ncoefs_tq1_9 = in2(25);\ncoefs_tq2_8 = in2(23);\ncoefs_tq3_7 = in2(21);\ncoefs_tq2_9 = in2(26);\ncoefs_tq3_8 = in2(24);\ncoefs_tq3_9 = in2(27);\ncoefs_tq1_10 = in2(28);\ncoefs_tq2_10 = in2(29);\ncoefs_tq3_10 = in2(30);\npinvG1_1 = in1(1);\npinvG1_2 = in1(4);\npinvG1_3 = in1(7);\nq0 = in3(1,:);\nq1 = in3(2,:);\nq2 = in3(3,:);\nq3 = in3(4,:);\nobj = q0.^2.*(coefs_tq1_1.*pinvG1_1+coefs_tq2_1.*pinvG1_2+coefs_tq3_1.*pinvG1_3)+q1.^2.*(coefs_tq1_5.*pinvG1_1+coefs_tq2_5.*pinvG1_2+coefs_tq3_5.*pinvG1_3)+q2.^2.*(coefs_tq1_8.*pinvG1_1+coefs_tq2_8.*pinvG1_2+coefs_tq3_8.*pinvG1_3)+q3.^2.*(coefs_tq1_10.*pinvG1_1+coefs_tq2_10.*pinvG1_2+coefs_tq3_10.*pinvG1_3)+q0.*q1.*(coefs_tq1_2.*pinvG1_1+coefs_tq2_2.*pinvG1_2+coefs_tq3_2.*pinvG1_3)+q0.*q2.*(coefs_tq1_3.*pinvG1_1+coefs_tq2_3.*pinvG1_2+coefs_tq3_3.*pinvG1_3)+q0.*q3.*(coefs_tq1_4.*pinvG1_1+coefs_tq2_4.*pinvG1_2+coefs_tq3_4.*pinvG1_3)+q1.*q2.*(coefs_tq1_6.*pinvG1_1+coefs_tq2_6.*pinvG1_2+coefs_tq3_6.*pinvG1_3)+q1.*q3.*(coefs_tq1_7.*pinvG1_1+coefs_tq2_7.*pinvG1_2+coefs_tq3_7.*pinvG1_3)+q2.*q3.*(coefs_tq1_9.*pinvG1_1+coefs_tq2_9.*pinvG1_2+coefs_tq3_9.*pinvG1_3);\n", "meta": {"author": "zarathustr", "repo": "LibQPEP", "sha": "99e5c23e746ace0bac4a86742c31db6fcf7297ba", "save_path": "github-repos/MATLAB/zarathustr-LibQPEP", "path": "github-repos/MATLAB/zarathustr-LibQPEP/LibQPEP-99e5c23e746ace0bac4a86742c31db6fcf7297ba/MATLAB/func_files/t1_pnp_func_new.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.712232184238947, "lm_q2_score": 0.4493926344647597, "lm_q1q2_score": 0.32007189762573046}} {"text": "function [net, info] = cnn_train_adagrad(net, imdb, getBatch, varargin)\n% CNN_TRAIN Demonstrates training a CNN\n% CNN_TRAIN() is an example learner implementing stochastic gradient\n% descent with momentum to train a CNN for image classification.\n% It can be used with different datasets by providing a suitable\n% getBatch function.\n\nopts.train = [] ;\nopts.val = [] ;\nopts.numEpochs = 300 ;\nopts.batchSize = 256 ;\nopts.useGpu = false ;\nopts.learningRate = 0.001 ;\nopts.continue = false ;\nopts.expDir = fullfile('data','exp') ;\nopts.conserveMemory = false ;\nopts.sync = true ;\nopts.prefetch = false ;\nopts.weightDecay = 0.0005 ;\nopts.errorType = 'multiclass' ;\nopts.plotDiagnostics = false ;\nopts.delta = 1e-8;\nopts.display = 1;\nopts.snapshot = 1;\nopts.test_interval = 1;\nopts = vl_argparse(opts, varargin) ;\n\nif ~exist(opts.expDir, 'dir'), mkdir(opts.expDir) ; end\nif isempty(opts.train), opts.train = find(imdb.images.set==1) ; end\nif isempty(opts.val), opts.val = find(imdb.images.set==2) ; end\nif isnan(opts.train), opts.train = [] ; end\n\n% -------------------------------------------------------------------------\n% Network initialization\n% -------------------------------------------------------------------------\n\nfor i=1:numel(net.layers)\n if ~strcmp(net.layers{i}.type,'conv'), continue; end\n net.layers{i}.filtersMomentum = zeros(size(net.layers{i}.filters), ...\n class(net.layers{i}.filters)) ;\n net.layers{i}.biasesMomentum = zeros(size(net.layers{i}.biases), ...\n class(net.layers{i}.biases)) ; %#ok<*ZEROLIKE>\n if ~isfield(net.layers{i}, 'filtersLearningRate')\n net.layers{i}.filtersLearningRate = 1 ;\n end\n if ~isfield(net.layers{i}, 'biasesLearningRate')\n net.layers{i}.biasesLearningRate = 1 ;\n end\n if ~isfield(net.layers{i}, 'filtersWeightDecay')\n net.layers{i}.filtersWeightDecay = 1 ;\n end\n if ~isfield(net.layers{i}, 'biasesWeightDecay')\n net.layers{i}.biasesWeightDecay = 1 ;\n end\nend\n\nif opts.useGpu\n net = vl_simplenn_move(net, 'gpu') ;\n for i=1:numel(net.layers)\n if ~strcmp(net.layers{i}.type,'conv'), continue; end\n net.layers{i}.filtersMomentum = gpuArray(net.layers{i}.filtersMomentum) ;\n net.layers{i}.biasesMomentum = gpuArray(net.layers{i}.biasesMomentum) ;\n end\nend\n\nG_f = cell(numel(net.layers), 1);\nG_b = cell(numel(net.layers), 1);\n\nfor l=1:numel(net.layers)\n \n if ~strcmp(net.layers{l}.type, 'conv'), continue ; end\n \n G_f{l} = zeros(size(net.layers{l}.filters), 'single');\n G_b{l} = zeros(size(net.layers{l}.biases), 'single');\n \nend\n\n% -------------------------------------------------------------------------\n% Train and validate\n% -------------------------------------------------------------------------\n\nrng(0) ;\n\nif opts.useGpu\n one = gpuArray(single(1)) ;\nelse\n one = single(1) ;\nend\n\ninfo.train.objective = [] ;\ninfo.train.error = [] ;\ninfo.train.topFiveError = [] ;\ninfo.train.speed = [] ;\ninfo.val.objective = [] ;\ninfo.val.error = [] ;\ninfo.val.topFiveError = [] ;\ninfo.val.speed = [] ;\n\nlr = opts.learningRate ;\nres = [] ;\nfor epoch=1:opts.numEpochs\n\n % fast-forward to where we stopped\n modelPath = @(ep) fullfile(opts.expDir, sprintf('net-epoch-%d.mat', ep));\n modelFigPath = fullfile(opts.expDir, 'net-train.pdf') ;\n if opts.continue\n if exist(modelPath(epoch),'file')\n if epoch == opts.numEpochs\n load(modelPath(epoch), 'net', 'info') ;\n end\n continue ;\n end\n if epoch > 1\n fprintf('resuming by loading epoch %d\\n', epoch-1) ;\n load(modelPath(epoch-1), 'net', 'info') ;\n end\n end\n\n train = opts.train(randperm(numel(opts.train))) ;\n val = opts.val ;\n\n info.train.objective(end+1) = 0 ;\n info.train.error(end+1) = 0 ;\n info.train.topFiveError(end+1) = 0 ;\n info.train.speed(end+1) = 0 ;\n info.val.objective(end+1) = 0 ;\n info.val.error(end+1) = 0 ;\n info.val.topFiveError(end+1) = 0 ;\n info.val.speed(end+1) = 0 ;\n\n for t=1:opts.batchSize:numel(train)\n % get next image batch and labels\n batch = train(t:min(t+opts.batchSize-1, numel(train))) ;\n batch_time = tic ;\n fprintf('training: epoch %02d: processing batch %3d of %3d ...', epoch, ...\n fix(t/opts.batchSize)+1, ceil(numel(train)/opts.batchSize)) ;\n [im, labels] = getBatch(imdb, batch) ;\n if opts.prefetch\n nextBatch = train(t+opts.batchSize:min(t+2*opts.batchSize-1, numel(train))) ;\n getBatch(imdb, nextBatch) ;\n end\n if opts.useGpu\n im = gpuArray(im) ;\n end\n\n % backprop\n net.layers{end}.class = labels ;\n res = vl_simplenn(net, im, one, res, ...\n 'conserveMemory', opts.conserveMemory, ...\n 'sync', opts.sync) ;\n\n % gradient step\n for l=1:numel(net.layers)\n if ~strcmp(net.layers{l}.type, 'conv'), continue ; end\n \n g_f = (net.layers{l}.filtersLearningRate) * ...\n (opts.weightDecay * net.layers{l}.filtersWeightDecay) * net.layers{l}.filters + ...\n (net.layers{l}.filtersLearningRate) / numel(batch) * res(l).dzdw{1};\n g_b = (net.layers{l}.biasesLearningRate) * ...\n (opts.weightDecay * net.layers{l}.biasesWeightDecay) * net.layers{l}.biases + ...\n (net.layers{l}.biasesLearningRate) / numel(batch) * res(l).dzdw{2};\n \n G_f{l} = G_f{l} + g_f .^ 2;\n G_b{l} = G_b{l} + g_b .^ 2;\n \n net.layers{l}.filters = net.layers{l}.filters - lr ./ (opts.delta + sqrt(G_f{l})) .* g_f;\n net.layers{l}.biases = net.layers{l}.biases - lr ./ (opts.delta + sqrt(G_b{l})) .* g_b;\n end\n\n % print information\n batch_time = toc(batch_time) ;\n speed = numel(batch)/batch_time ;\n info.train = updateError(opts, info.train, net, res, batch_time) ;\n\n fprintf(' %.2f s (%.1f images/s)', batch_time, speed) ;\n n = t + numel(batch) - 1 ;\n switch opts.errorType\n case 'multiclass'\n fprintf(' err %.1f err5 %.1f', ...\n info.train.error(end)/n*100, info.train.topFiveError(end)/n*100) ;\n fprintf('\\n') ;\n case 'binary'\n fprintf(' err %.1f', ...\n info.train.error(end)/n*100) ;\n fprintf('\\n') ;\n case 'euclideanloss'\n fprintf(' err %.1f', info.train.error(end) / n);\n fprintf('\\n') ;\n end\n\n % debug info\n if opts.plotDiagnostics\n figure(2) ; vl_simplenn_diagnose(net,res) ; drawnow ;\n end\n end % next batch\n\n % evaluation on validation set\n if epoch == 1 || rem(epoch, opts.test_interval) == 0 || epoch == opts.numEpochs\n for t=1:opts.batchSize:numel(val)\n batch_time = tic ;\n batch = val(t:min(t+opts.batchSize-1, numel(val))) ;\n fprintf('validation: epoch %02d: processing batch %3d of %3d ...', epoch, ...\n fix(t/opts.batchSize)+1, ceil(numel(val)/opts.batchSize)) ;\n [im, labels] = getBatch(imdb, batch) ;\n if opts.prefetch\n nextBatch = val(t+opts.batchSize:min(t+2*opts.batchSize-1, numel(val))) ;\n getBatch(imdb, nextBatch) ;\n end\n if opts.useGpu\n im = gpuArray(im) ;\n end\n\n net.layers{end}.class = labels ;\n res = vl_simplenn(net, im, [], res, ...\n 'disableDropout', true, ...\n 'conserveMemory', opts.conserveMemory, ...\n 'sync', opts.sync) ;\n\n % print information\n batch_time = toc(batch_time) ;\n speed = numel(batch)/batch_time ;\n info.val = updateError(opts, info.val, net, res, batch_time) ;\n\n fprintf(' %.2f s (%.1f images/s)', batch_time, speed) ;\n n = t + numel(batch) - 1 ;\n switch opts.errorType\n case 'multiclass'\n fprintf(' err %.1f err5 %.1f', ...\n info.val.error(end)/n*100, info.val.topFiveError(end)/n*100) ;\n fprintf('\\n') ;\n case 'binary'\n fprintf(' err %.1f', ...\n info.val.error(end)/n*100) ;\n fprintf('\\n') ;\n case 'euclideanloss'\n fprintf(' err %.1f', info.val.error(end) / n);\n fprintf('\\n') ;\n end\n end\n end\n\n % save\n info.train.objective(end) = info.train.objective(end) / numel(train) ;\n info.train.error(end) = info.train.error(end) / numel(train) ;\n info.train.topFiveError(end) = info.train.topFiveError(end) / numel(train) ;\n info.train.speed(end) = numel(train) / info.train.speed(end) ;\n info.val.objective(end) = info.val.objective(end) / numel(val) ;\n info.val.error(end) = info.val.error(end) / numel(val) ;\n info.val.topFiveError(end) = info.val.topFiveError(end) / numel(val) ;\n info.val.speed(end) = numel(val) / info.val.speed(end) ;\n if epoch == 1 || rem(epoch, opts.snapshot) == 0 || epoch == opts.numEpochs\n save(modelPath(epoch), 'net', 'info') ;\n end\n\n if epoch == 1 || rem(epoch, opts.display) == 0 || epoch == opts.numEpochs\n figure(1) ; clf ;\n subplot(1,2,1) ;\n semilogy(1:epoch, info.train.objective, 'k') ; hold on ;\n semilogy([1 opts.test_interval : opts.test_interval : epoch epoch], info.val.objective([1 opts.test_interval : opts.test_interval : epoch epoch]), 'b') ;\n xlabel('training epoch') ; ylabel('energy') ;\n grid on ;\n h=legend('train', 'val') ;\n set(h,'color','none');\n title('objective') ;\n subplot(1,2,2) ;\n switch opts.errorType\n case 'multiclass'\n plot(1:epoch, info.train.error, 'k') ; hold on ;\n plot(1:epoch, info.train.topFiveError, 'k--') ;\n plot([1 opts.test_interval : opts.test_interval : epoch epoch], info.val.error([1 opts.test_interval : opts.test_interval : epoch epoch]), 'b') ;\n plot([1 opts.test_interval : opts.test_interval : epoch epoch], info.val.topFiveError([1 opts.test_interval : opts.test_interval : epoch epoch]), 'b--') ;\n h=legend('train','train-5','val','val-5') ;\n case 'binary'\n plot(1:epoch, info.train.error, 'k') ; hold on ;\n plot([1 opts.test_interval : opts.test_interval : epoch epoch], info.val.error([1 opts.test_interval : opts.test_interval : epoch epoch]), 'b') ;\n h=legend('train','val') ;\n case 'euclideanloss'\n plot(1 : epoch, info.train.error, 'k'); hold on;\n plot([1 opts.test_interval : opts.test_interval : epoch epoch], info.val.error([1 opts.test_interval : opts.test_interval : epoch epoch]), 'b') ;\n h = legend('train', 'val') ;\n end\n grid on ;\n xlabel('training epoch') ; ylabel('error') ;\n set(h,'color','none') ;\n title('error') ;\n drawnow ;\n print(1, modelFigPath, '-dpdf') ;\n end\nend\n\n% -------------------------------------------------------------------------\nfunction info = updateError(opts, info, net, res, speed)\n% -------------------------------------------------------------------------\npredictions = gather(res(end-1).x) ;\nsz = size(predictions) ;\nn = prod(sz(1:2)) ;\n\nlabels = net.layers{end}.class ;\ninfo.objective(end) = info.objective(end) + sum(double(gather(res(end).x))) ;\ninfo.speed(end) = info.speed(end) + speed ;\nswitch opts.errorType\n case 'multiclass'\n [~,predictions] = sort(predictions, 3, 'descend') ;\n error = ~bsxfun(@eq, predictions, reshape(labels, 1, 1, 1, [])) ;\n info.error(end) = info.error(end) +....\n sum(sum(sum(error(:,:,1,:))))/n ;\n info.topFiveError(end) = info.topFiveError(end) + ...\n sum(sum(sum(min(error(:,:,1:5,:),[],3))))/n ;\n case 'binary'\n error = bsxfun(@times, predictions, labels) < 0 ;\n info.error(end) = info.error(end) + sum(error(:))/n ;\n case 'euclideanloss'\n error = euclideanloss(sigmoid(predictions), labels);\n info.error(end) = info.error(end) + error;\nend\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/分割算法/MovingObjectSegmentation-master/SBMI/BasicCNN/cnn_train_adagrad.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.31980701746173923}} {"text": "%SEQUENTIAL Sequential mapping\n%\n% V = SEQUENTIAL(W1,W2) \n% B = SEQUENTIAL(A,W)\n%\n% INPUT\n% W,W1,W2 Mappings\n% A Dataset\n%\n% OUTPUT\n% V Sequentially combined mapping\n% B Dataset\n%\n% DESCRIPTION\n% The two mappings W1 and W2 are combined into a single mapping V. Note \n% that SEQUENTIAL(W1,W2) is equivalent to W1*W2. If W2 is a mapping of \n% a type 'combiner', it is called to make a combination attempt.\n%\tSEQUENTIAL(A,W) maps the dataset A by the sequential mapping W.\n%\n% This routine is automatically called to execute W = W1*W2 or B = A*W2 in\n% case W2 is a sequential mapping. It should not be directly called by users.\n%\n% SEE ALSO (PRTools Guide)\n% MAPPINGS, DATASETS\n\n% Copyright: R.P.W. Duin, r.p.w.duin@37steps.com\n\nfunction [w,varargout] = sequential(w1,w2,w3)\n\t\n\t\t\n\t% Just necessary to inform PRMAP.\n\tif (nargin == 0) \n\t\tw = prmapping(mfilename,'combiner');\n\t\treturn;\n\tend\n\t[m1,k1] = size(w1); \n\t[m2,k2] = size(w2);\n\tif (~isa(w2,'prmapping'))\n\t\terror('Second argument should be a mapping.')\n\tend\n\n\tif isa(w1,'prmapping') \n\t\t% Definition\n if isempty(w1) % treat empty mapping as unity mapping\n w = w2;\n elseif (iscombiner(w2))\n\t\t\t% Execute the mapping W2.\n varargout = repmat({[]},[1, max((nargout-1),0)]);\n\t\t\tmap = getmapping_file(w2);\n\t\t\tpars = getdata(w2);\n\t\t\t[w,varargout{:}] = feval(map,w1,pars{:});\n\t\telse \n\t\t\t% W2 is just a general mapping.\n\t\t\tif (k1 > 0) && (m2 > 0) && (k1 ~= m2)\n\t\t\t\terror('Inner mapping/data sizes do not agree.')\n\t\t\tend\n\n\t\t\t% Define the mapping type after combining W1 and W2.\n\t\t\tif (isuntrained(w1)) || (isuntrained(w2))\n\t\t\t\tmappingtype = 'untrained';\n elseif (isgenerator(w2))\n mappingtype = 'generator';\n %elseif (isfixed(w2)) || (isfixed_cell(w2))\n % mappingtype = 'fixed';\n\t\t\telseif (istrained(w1)) || (istrained(w2))\n\t\t\t\tmappingtype = 'trained';\n\t\t\telse\n\t\t\t\tmappingtype = 'fixed';\n\t\t\tend\n\t\t\t\n\t\t\tif strcmp(mappingtype,'untrained')\n\t\t\t\tlabels = [];\n\t\t\t\tsize_in = 0;\n\t\t\t\tsize_out = 0;\n\t\t\telseif (m2 == 0 || k2 == 0) && (m1 ~= 0) && (k1 ~= 0) \n\t\t\t\t% E.G. TRAINED * FIXED\n\t\t\t\tlabels = getlabels(w1);\n\t\t\t\tsize_in = getsize_in(w1);\n\t\t\t\tsize_out = getsize_out(w1);\n\n\t\t\telseif (m2 ~= 0) && (k2 ~= 0) && (m1 == 0 || k1 == 0) \n\t\t\t\t% FIXED * TRAINED\n\t\t\t\tlabels = getlabels(w2);\n\t\t\t\tsize_in = getsize_in(w2);\n\t\t\t\tsize_out = getsize_out(w2);\n\n\t\t\telseif ~istrained(w2) \n\t\t\t\t% TRAINED * FIXED\n\t\t\t\tlabels = getlabels(w1);\n\t\t\t\tsize_in = getsize_in(w1);\n\t\t\t\tsize_out = getsize_out(w2);\n\n\t\t\telse \t\n\t\t\t\t% TRAINED * TRAINED\n\t\t\t\tlabels = getlabels(w2);\n\t\t\t\tsize_in = getsize_in(w1);\n\t\t\t\tsize_out = getsize_out(w2);\n\t\t\tend\n\t\t\tw = prmapping(mfilename,mappingtype,{w1,w2},labels,size_in,size_out);\n end\n if ismapping(w) && (getbatch(w1) || getbatch(w2))\n [n1,b1,o1] = getbatch(w1);\n [n2,b2,o2] = getbatch(w2);\n if ~n1\n b12 = b2; o12 = o2;\n elseif ~n2\n b12 = b1; o12 = o1;\n else\n b12 = min(b1,b2); o12 = min(o1,o2);\n end\n w = setbatch(w,true,b12,o12);\n end\n\n elseif isempty(w2) % treat empty mapping as unity mapping\n w = w1;\n \n else\n\t\t% Execution. We are here, when SEQUENTIAL(A,V) is called.\n\t\tif nargin == 3 % needed as MAP breaks down sequential mappings\n\t\t\tw2 = w2*w3; % restore them!\n\t\tend\n\t\ta = w1;\n\t\tif (~isa(a,'double')) && (~isa(a,'prdataset'))\n\t\t\terror('Just datasets or doubles can be mapped.')\n\t\tend\n\t\t% V can be a more complex mapping.\n\t\t% v = +w2; v1 = v{1}; v2 = v{2};\n [v1,v2] = getdata(w2);\n\t\tif (isuntrained(v1))\n\t\t\tif (isuntrained(v2))\n\t\t\t\tu = a*v1;\n\t\t\t\tw = u*(a*u*v2);\n\t\t\telse\n\t\t\t\tw = a*v1*v2;\n\t\t\tend\n\t\telse\n\t\t\tif (isuntrained(v2)) && (~isgenerator(v1))\n\t\t\t\tw = v1*(a*v1*v2);\n\t\t\t\t% may be v1 changed the dimensionality, reset it: \n\t\t\t\tw = setsize_in(w,size(a,2));\n else\n w1 = a*v1;\n w = w1*v2;\n\t\t\t\t%w = a*v1*v2;\n\t\t\t\tfeatlabels = getlabels(w2);\n\t\t\t\tif (isdataset(w)) && ~isempty(featlabels) && size(w,2) == size(featlabels,1)\n\t\t\t\t\tw = setfeatlab(w,featlabels);\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\t\tif ismapping(w)\n\t\t\tw = setbatch(w,getbatch(w2));\n\t\tend\n\tend\nreturn;\n", "meta": {"author": "marianux", "repo": "ecg-kit", "sha": "c8e3de47c54a9214138143676d2aa546b0540dd2", "save_path": "github-repos/MATLAB/marianux-ecg-kit", "path": "github-repos/MATLAB/marianux-ecg-kit/ecg-kit-c8e3de47c54a9214138143676d2aa546b0540dd2/common/prtools/sequential.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.31971558562578833}} {"text": "% timecrossf() - compute the time frequency content of an array rows and \n% cross-coherence between the rows for. If the rows depict \n% different components activation, these results can then \n% be used to analyse time relation between these\n% components (using the brainmovie function). You may \n% also input electrode activities into this function to \n% analyse the synchronisation and phase relashionship \n% between the electrodes. \n%\n% Usage:\n% >> [ allersps, allitcs, allcrossfs, allcrossfphis, times, freqs] ...\n% = timecrossf(data, frames, tlimits, srate, cycles, ...);\n%\n% Inputs:\n% data - multi-row data (nb_input,frames*nepochs) for the first\n% condition. Each row is a different input. The function \n% will conpute the time frequency content of each row and \n% the cross-coherence between the rows. If data is a cell\n% array { data1 data2 }, the function will compute the \n% time-frequency decomposition for these 2 arrays and the \n% difference between them.\n% frames - frames per epoch {768}\n% tlimits - epoch time limits (ms) [mintime maxtime]{[-1000 2000]}\n% srate - data sampling rate (Hz) {256}\n% ... - see timef or crossf command for details about other \n% parameters \n%\n% Outputs:\n% allersps - cell array (size nb_row,1) of ERSP (event-related \n% power spectrum content of each row of the data array)\n% allitcs - cell array (size nb_row,1) of ITC (event-related \n% inter-trial coherence content of each row of the data\n% array)\n% allcrossfs - cell array (size nb_row, nb_row) of cross-coherence \n% between the row of the data array (only the upper \n% diagonal part of the cell array is used)\n% allcrossfphis - cell array (size nb_row, nb_row) of cross-coherence \n% phase between the row of the data array (only the \n% upper diagonal part of the cell array is used)\n% times - time array returned by the crossf or timef functions\n% freqs - frequency array returned by the crossf or timef \n% functions\n%\n% Example1: generate a movie, 1 condition, below 10Hz dynamics \n%\n% % ICA decomposition, activity in array actICA (31 x (176 x n)), \n% % graph for 6 components, 176 points from -100 ms to 600 ms after\n% % stimulus onset, 250 Hz sampling rate \n% [ allersps, allitcs, allcrossfs, allcrossfphis, times, freqs] ...\n% = timecrossf( actICA(1:6,:), 176, [-100 600], 250, 1, 32, 100);\n% brainmovie( ersps, itcs, crossfs_amp, crossfs_phase, times, [1:2] ) \n% %[1:2] indicates the frequency rows to take into account (freqs(1:2))\n%\n% Example2: generate a movie, 2 condition, below 10Hz dynamics \n%\n% % Same as above with actICA2 (31 x (176 x n2)) the activity of the \n% % components for a different condition\n% [ allersps, allitcs, allcrossfs, allcrossfphis, times, freqs] ...\n% = timecrossf( actICA(1:6,:), 176, [-100 600], 250, 1, 32, 100);\n% [ allersps(:,2), allitcs(:,2), allcrossfs(:,:,2), ...\n%\t allcrossfphis(:,:,2)] ...\n% = timecrossf( actICA2(1:6,:), 176, [-100 600], 250, 1, 32, 100);\n% brainmovie( allersps, allitcs, allcrossfs, allcrossfphis, times, ...\n% [1:2] ) \n%\n% See also timef(), crossf(), brainmovie()\n\n% arno@salk.edu, Arnaud Delorme, CNL / Salk Institute, 2001\n\n% This program is free software; you can redistribute it and/or\n% modify it. \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.\n\nfunction [ ALLERSP, ALLITC, ALLCROSSF, ALLCROSSFANGLE, times, freqs ] = timecrossf(data, frames, tlimits, srate, cycle, varargin);\n\nif nargin < 3\n\thelp timecrossf;\n\treturn;\nend;\n\nSAVE = 0;\t% save graphs in jpeg format\n%XDISP = 'cole:0.0';\nnbcompo = size( data, 1);\nif iscell(data)\n data1 = data{1};\n data2 = data{2};\n nbcompo = size( data1, 1); \nend;\n\n% compute all time frequency maps\n% -------------------------------\ncompter = 1;\nfor numcompo = 1:nbcompo\n\tif iscell(data)\n [ersp,itc,powbase,times,freqs,erspboot,itcboot] = newtimef({ data1(numcompo,:) data2(numcompo,:) }, ...\n frames, tlimits, srate, cycle, varargin{:});\n size(ersp{1})\n ALLERSP{numcompo,1} = applyboot( ersp{1}, erspboot{1});\n ALLERSP{numcompo,2} = applyboot( ersp{2}, erspboot{2});\n ALLERSP{numcompo,3} = applyboot( ersp{3}, erspboot{3});\n ALLITC {numcompo,1} = applyboot( abs(itc{1}) , itcboot{1});\n ALLITC {numcompo,2} = applyboot( abs(itc{2}) , itcboot{2});\n if ~isreal(itc{3}), itc{3} = abs(itc{3}); end;\n ALLITC {numcompo,3} = applyboot( itc{3}, itcboot{3});\n else\n [ersp,itc,powbase,times,freqs,erspboot,itcboot] = newtimef( data(numcompo,:), ...\n frames, tlimits, srate, cycle, varargin{:}); \n ALLERSP{numcompo,1} = applyboot( ersp, erspboot);\n ALLITC{numcompo,1} = applyboot( itc, itcboot);\n end;\n\tif SAVE\n\t\t%command = sprintf('print -djpeg timef%2.2d', numcompo); eval(command); close;\n\t\tcommand = sprintf('hgsave(''timef%2.2d'');', numcompo); eval(command); close;\n\tend;\n\tcompter = compter + 1 ;\nend;\t\n\n% compute all cross coherence maps\n% --------------------------------\nALLCROSSF = cell(nbcompo, nbcompo);\nALLCROSSFANGLE = cell(nbcompo, nbcompo);\nfor index1 = 1:nbcompo\n\tfor index2 = 1:nbcompo\n\t\tif index2 > index1\n if iscell(data)\n [coh,mcoh,timesout,freqsout,cohboot,cohangles] = newcrossf({ data1(index1,:) data2(index1,:)}, ...\n { data1(index2,:) data2(index2,:)}, frames, ...\n tlimits, srate, cycle, varargin{:}); \n size(coh{1})\n ALLCROSSF { index1, index2, 1 } = applyboot(coh{1}, cohboot{1});\n ALLCROSSF { index1, index2, 2 } = applyboot(coh{2}, cohboot{2});\n ALLCROSSF { index1, index2, 3 } = applyboot(coh{3}, cohboot{3});\n ALLCROSSFANGLE { index1, index2, 1 } = cohangles{1};\n ALLCROSSFANGLE { index1, index2, 2 } = cohangles{2};\n ALLCROSSFANGLE { index1, index2, 3 } = cohangles{3};\n else\n [coh,mcoh,timesout,freqsout,cohboot,cohangles] = newcrossf(data(index1,:), data(index2,:), frames, ...\n tlimits, srate, cycle, varargin{:}); \n ALLCROSSF { index1, index2 } = applyboot(coh, cohboot);\n ALLCROSSFANGLE { index1, index2 } = cohangles;\n if SAVE\n %command = sprintf('print -djpeg crossf%2.2d-%2.2d%', index1, index2); eval(command); close;\n command = sprintf('hgsave(''crossf%2.2d-%2.2d%'');', index1, index2); eval(command); close;\n end;\n end;\n\t\tend;\n\tend;\nend;\n\nreturn;\n\nfunction array = applyboot(array, arrayboot)\n if isempty(arrayboot), return; end;\n if size(arrayboot,3) == 2\n array(find((array > arrayboot(:,:,1)) & (array < arrayboot(:,:,2)))) = 0;\n elseif size(arrayboot,2) > 2\n array(find(array < arrayboot(:,:))) = 0;\n elseif size(arrayboot,2) == 2 \n array(find((array > repmat(arrayboot(:,1),[1 size(array,2)])) & ...\n (array < repmat(arrayboot(:,2),[1 size(array,2)])))) = 0;\n else \n array(find(array < repmat(arrayboot(:,1),[1 size(array,2)]))) = 0; \n end;\n", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/PR_BCI_team/Team_EarEEG/ear-EEG connecting/external/eeglab_10_0_1_0x/plugins/brainmovie0.1/timecrossf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6654105454764747, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.3197155792496733}} {"text": "classdef prtClassKnn < prtClass\n % prtClassKnn K-nearest neighbors classifier\n %\n % CLASSIFIER = prtClassKnn returns a K-nearest neighbors classifier\n %\n % CLASSIFIER = prtClassKnn(PROPERTY1, VALUE1, ...) constructs a\n % prtClassKnn object CLASSIFIER with properties as specified by\n % PROPERTY/VALUE pairs.\n %\n % A prtClassKnn object inherits all properties from the abstract class\n % prtClass. In addition is has the following properties:\n %\n % k - The number of neigbors to be considered\n % distanceFunction - The function to be used to compute the\n % distance from samples to cluster centers. \n % It must be a function handle of the form:\n % @(x1,x2)distFun(x1,x2). Most prtDistance*\n % functions will work.\n %\n % For information on the K-nearest neighbors classifier algorithm, please\n % refer to the following URL:\n %\n % http://en.wikipedia.org/wiki/K-nearest_neighbor_algorithm \n %\n % A prtClassKnn object inherits the TRAIN, RUN, CROSSVALIDATE and\n % KFOLDS methods from prtAction. It also inherits the PLOT method\n % from prtClass.\n %\n % Example:\n %\n % TestDataSet = prtDataGenUnimodal; % Create some test and \n % TrainingDataSet = prtDataGenUnimodal; % training data\n % classifier = prtClassKnn; % Create a classifier\n % classifier = classifier.train(TrainingDataSet); % Train\n % classified = run(classifier, TestDataSet); % Test\n % classifier.plot;\n %\n % See also prtClass, prtClassLogisticDiscriminant, prtClassBagging,\n % prtClassMap, prtClassCap, prtClassBinaryToMaryOneVsAll, prtClassDlrt,\n % prtClassPlsda, prtClassFld, prtClassRvm, prtClassGlrt, prtClass\n\n\n\n\n\n\n\n properties (SetAccess=private)\n \n name = 'K-Nearest Neighbor' % K-Nearest Neighbor\n nameAbbreviation = 'KNN' % KNN \n isNativeMary = true; % true\n \n end\n \n properties\n \n k = 3; % The number of neighbors to consider in the voting\n \n distanceFunction = @(x1,x2)prtDistanceEuclidean(x1,x2); % Function handle to compute distance\n end\n \n methods\n function Obj = prtClassKnn(varargin)\n Obj = prtUtilAssignStringValuePairs(Obj,varargin{:});\n Obj.verboseStorage = true;\n end\n function Obj = set.k(Obj,val)\n if ~prtUtilIsPositiveScalarInteger(val)\n error('prt:prtClassKnn:k','k must be a positive scalar integer');\n end\n Obj.k = val;\n end\n \n function Obj = set.distanceFunction(Obj,val)\n if ~isa(val,'function_handle')\n error('prt:prtClassKnn:distanceFunction','distanceFunction must be a function handle');\n end\n Obj.distanceFunction = val;\n end\n end\n \n methods (Access=protected, Hidden = true)\n function Obj = preTrainProcessing(Obj,DataSet)\n if ~Obj.verboseStorage\n warning('prtClassKnn:verboseStorage:false','prtClassKnn requires verboseStorage to be true; overriding manual settings');\n end\n Obj.verboseStorage = true;\n Obj = preTrainProcessing@prtClass(Obj,DataSet);\n end\n function Obj = trainAction(Obj,twiddle)\n %Do nothing; we've already specified \"verboseStorage = true\",\n %so the \".dataSet\" field will be set when it comes time to test\n end\n \n function ClassifierResults = runAction(Obj,PrtDataSet)\n \n x = getObservations(PrtDataSet);\n n = PrtDataSet.nObservations;\n \n nClasses = Obj.dataSet.nClasses;\n uClasses = Obj.dataSet.uniqueClasses;\n labels = getTargets(Obj.dataSet);\n y = zeros(n,nClasses);\n \n xTrain = getObservations(Obj.dataSet);\n \n largestMatrixSize = prtOptionsGet('prtOptionsComputation','largestMatrixSize');\n memBlock = max(floor(largestMatrixSize/size(xTrain,1)),1);\n \n if n > memBlock\n for start = 1:memBlock:n\n indices = start:min(start+memBlock-1,n);\n \n distanceMat = feval(Obj.distanceFunction,xTrain,x(indices,:));\n \n [twiddle,I] = sort(distanceMat,1,'ascend');\n I = I(1:Obj.k,:);\n L = labels(I);\n \n % MATLAB indexing is inexplicably different if I is\n % 1xN or (k>1)xN\n if Obj.k ~= 1\n L = L';\n end\n \n for class = 1:nClasses\n y(indices,class) = sum(L == uClasses(class),2);\n end\n end\n else\n distanceMat = feval(Obj.distanceFunction,xTrain,x);\n \n [twiddle,I] = sort(distanceMat,1,'ascend');\n I = I(1:Obj.k,:);\n L = labels(I);\n \n % MATLAB indexing is inexplicably different if I is\n % 1xN or (k>1)xN\n if Obj.k ~= 1\n L = L';\n end\n \n for class = 1:nClasses\n y(:,class) = sum(L == uClasses(class),2);\n end\n end\n \n [Etc.nVotes,Etc.MapGuessInd] = max(y,[],2);\n Etc.MapGuess = uClasses(Etc.MapGuessInd);\n ClassifierResults = PrtDataSet;\n ClassifierResults.X = y;\n \n end\n \n end\nend\n", "meta": {"author": "covartech", "repo": "PRT", "sha": "4305e612af048e7dbf3d9392efc7436db125b1fc", "save_path": "github-repos/MATLAB/covartech-PRT", "path": "github-repos/MATLAB/covartech-PRT/PRT-4305e612af048e7dbf3d9392efc7436db125b1fc/class/prtClassKnn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6150878414043816, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.3195512484830636}} {"text": "close all\nclear\n\n%------------------------------------------------------------------------------------------\nnb = 1000;%Total number of initial states\nnmpcd=zeros(1,nb);%Store computing time for one time-step for NMPC-DCBF\nimpcd=zeros(1,nb);%Store computing time for one time-step for iMPC-DCBF\nnmpcinf=zeros(1,1);%Store infeasible rate for one time-step for NMPC-DCBF\nimpcinf=zeros(1,1);%Store infeasible rate for one time-step for iMPC-DCBF\ni=8;%i is number of horozon\nts = 1;%Total time steps\nload(gamma1_0p6gamma2_0p6\\InitialStateData');%Load the generated 1000 initial states\n[a, b, c, d]=compare(i,ts,nb,InitialMat);%Involves NMPC-DCBF and iMPC-DCBF\nnmpcd(1,:)=a;\nimpcd(1,:)=b;\nnmpcinf(1,1)=c;\nimpcinf(1,1)=d;\nnmpcplot1=nmpcd(1,:);\nnmpcplot1(nmpcplot1==-1)=[];%Eliminate infeasible one time-step trajectories\nimpcplot1=impcd(1,:);\nimpcplot1(impcplot1==-1)=[];%Eliminate infeasible one time-step trajectories\n\nsave('timecom8','nmpcplot1','impcplot1');\nsave('feasibility8','nmpcinf','impcinf');\n\ndistnmpc = fitdist(nmpcplot1','Normal');\ndistimpc = fitdist(impcplot1','Normal');\nmu1=distnmpc.mu;%Get mean of sample of computing time for NMPC-DCBF\nmu2=distimpc.mu;%Get mean of sample of computing time for iMPC-DCBF\nsigma1=distnmpc.sigma;%Get variance of sample of computing time for NMPC-DCBF\nsigma2=distimpc.sigma;%Get variance of sample of computing time for iMPC-DCBF\n\n\n%Initialize atmosphere parameters\nfunction [tnmpc, timpc, ratiotnmpc, ratiotimpc]=compare(N11,ttsim,samplen,InitialMat)\ntnmpc=[];\ntimpc=[];\nfor i=1:samplen\nN1=N11;\ntsim=ttsim;\nxini1=InitialMat(1,i);\nyini1=InitialMat(2,i);\nthetaini1=InitialMat(3,i);\nvini1=InitialMat(4,i);\nx01=[xini1;yini1;thetaini1;vini1];\nx02=[xini1 yini1 thetaini1 vini1];\nt1 = nmpcdcbf(x01, N1, tsim);\nt2 = impcdcbf(x02, N1, tsim);\ntindex=[N11 i];\ndisp(tindex);\ntnmpc=[tnmpc t1];%Computing time for NMPC-DCBF\ntimpc=[timpc t2];%Computing time for iMPC-DCBF\nend\nnnmpc1 = length(tnmpc);\nnimpc1 = length(timpc);\ntnmpcs = tnmpc;\ntimpcs = timpc;\ntnmpcs(tnmpcs==-1)=[];\ntimpcs(timpcs==-1)=[];\nnnmpc2 = length(tnmpcs);\nnimpc2 = length(timpcs);\nratiotnmpc = (nnmpc1-nnmpc2)/nnmpc1;%Infeasible rate for NMPC-DCBF\nratiotimpc = (nimpc1-nimpc2)/nimpc1;%Infeasible rate for iMPC-DCBF\nend\n\n\n\n\n\nfunction t1 = nmpcdcbf(x00, N1, ttsim)\n%% General Flags\nrun_nmpc_dcbf_one = true;\nrun_nmpc_dcbf_multiple = true;\n\n%% Setup and Parameters\nx0 = x00;\ndt = 0.1;\ntime_total = ttsim *dt;\nP = zeros(4,4);%Weight matrix P\nP(1,1) = 10; P(2,2) = 10; P(3,3) = 10;P(4,4) = 10;\nQ = zeros(4,4);%Weight matrix Q\nQ(1,1) = 10; Q(2,2) = 10; Q(3,3) = 10;Q(4,4) = 10;\nR = zeros(4,4);%Weight matrix R\nR(1,1) = 1; R(2,2) = 1;R(3,3) = 1000;R(4,4) = 1000;\n%Variables range as below\nxmin = [-10; -10; -10;-10];\nxmax = [10; 10; 10;10];\numin = [-7; -5;-inf;-inf];\numax = [7; 5;inf;inf];\n\n%% Discrete-time unicycle model\nsystem.dt = dt;\nsystem.A = [1 0 0 0;\n 0 1 0 0;\n 0 0 1 0;\n 0 0 0 1];\nsystem.B = [x0(4,1)*cos(x0(3,1))*dt;\n x0(4,1)*sin(x0(3,1))*dt;\n 0;\n 0];\nsystem.C =[0 0 0 0;\n 0 0 0 0;\n 1*dt 0 0 0;\n 0 1*dt 0 0];\nsystem.xl = xmin;\nsystem.xu = xmax;\nsystem.ul = umin;\nsystem.uu = umax;\n\n%% NMPC-DCBF parameters\nparams_nmpc_dcbf.Q = Q;\nparams_nmpc_dcbf.R = R;\nparams_nmpc_dcbf.P = P;\nparams_nmpc_dcbf.gamma1 = 0.6;\nparams_nmpc_dcbf.gamma2 = 0.6;\n\n%% Obstacle\nobs.pos1 = [0; 0];\nobs.r1 = 1;\n\n\n\n%% Simulate NMPC-DCBF with other N\nparams_nmpc_dcbf.N = N1;\nif run_nmpc_dcbf_one\n fprintf('Run NMPC-DCBF-8\\n');\n controller_nmpc_dcbf_multiple8 = NMPCDCBF2(x0, system, params_nmpc_dcbf);%Highest order mcbf=2\n controller_nmpc_dcbf_multiple8.obs = obs;\n controller_nmpc_dcbf_multiple8.sim(time_total);\nend\nt1=controller_nmpc_dcbf_multiple8.tt;\nend\n\n\nfunction t2=impcdcbf(x00, N1, ttsim)\nt2=0;\nxo = 0;\nyo = 0;\nr = 1;\nN = N1;%Number of horizon\nK1 = 1000;%Maximum iteration times, jmax\nK = 1000;%Maximum iteration times, jmax\ndt = 0.1;\ngamma1 = 6;\ngamma2 = 6;\nnsim = ttsim;\n\ntic;\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 = x00;\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);%First order CBF constraints\nlcbf = -abc(3, :);\nlcbf(1) = [];\nlcbf = lcbf';\nucbf = inf * ones(N, 1);\nA2cbf = cbfmat2(abc, nx, nu, dt, gamma1, gamma2, x0);%Second order CBF constraints\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];\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!')\n t2=-1;\n return\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)%Iterations for the first time-step\n storagex = ctrlx;%store the state variables and inputs in order to compare them with the next iteration\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];\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 t2=-1;\n return\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);\nt2=t2+toc;\nreturn\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)%Iterations for the left time steps\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];\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 t2=-1;\n return\n end\n ctrlx = res.x(1:(N+1)*nx);\n ctrlu = res.x((N+1)*nx+1:(N+1)*nx+N*nu);\n x0 = ctrlx(1:nx);\n testx0 = [testx0 x0];\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\nend\n\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/benchmark/gamma1-0p6gamma2-0p6/test_each_horizon/test_N8.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.31943735283726377}} {"text": "function [C,phi,S12,S1,S2,f,zerosp,confC,phistd,Cerr]=coherencycpb(data1,data2,params,fscorr)\n% Multi-taper coherency,cross-spectrum and individual spectra - continuous and binned point process data\n%\n% Usage:\n%\n% [C,phi,S12,S1,S2,f,zerosp,confC,phistd,Cerr]=coherencycpb(data1,data2,params,fscorr)\n% Inputs: \n% data1 (continuous data in form samples x trials) -- required\n% data2 (binned spike data in form samples x trials) -- required\n% params: structure with fields tapers, pad, Fs, fpass, err, trialave\n% - optional\n% tapers : precalculated tapers from dpss or in the one of the following\n% forms: \n% (1) A numeric vector [TW K] where TW is the\n% time-bandwidth product and K is the number of\n% tapers to be used (less than or equal to\n% 2TW-1). \n% (2) A numeric vector [W T p] where W is the\n% bandwidth, T is the duration of the data and p \n% is an integer such that 2TW-p tapers are used. In\n% this form there is no default i.e. to specify\n% the bandwidth, you have to specify T and p as\n% well. Note that the units of W and T have to be\n% consistent: if W is in Hz, T must be in seconds\n% and vice versa. Note that these units must also\n% be consistent with the units of params.Fs: W can\n% be in Hz if and only if params.Fs is in Hz.\n% The default is to use form 1 with TW=3 and K=5\n%\n%\t pad\t\t (padding factor for the FFT) - optional (can take values -1,0,1,2...). \n% -1 corresponds to no padding, 0 corresponds to padding\n% to the next highest power of 2 etc.\n%\t\t\t \t e.g. For N = 500, if PAD = -1, we do not pad; if PAD = 0, we pad the FFT\n%\t\t\t \t to 512 points, if pad=1, we pad to 1024 points etc.\n%\t\t\t \t Defaults to 0.\n% Fs (sampling frequency) - optional. Default 1.\n% fpass (frequency band to be used in the calculation in the form\n% [fmin fmax])- optional. \n% Default all frequencies between 0 and Fs/2\n% err (error calculation [1 p] - Theoretical error bars; [2 p] - Jackknife error bars\n% [0 p] or 0 - no error bars) - optional. Default 0.\n% trialave (average over trials when 1, don't average when 0) - optional. Default 0\n% fscorr (finite size corrections, 0 (don't use finite size corrections) or 1 \n% (use finite size corrections) - optional (available only for spikes). Defaults 0.\n% Outputs:\n% C (magnitude of coherency - frequencies x trials if trialave=0; dimension frequencies if trialave=1)\n% phi (phase of coherency - frequencies x trials if trialave=0; dimension frequencies if trialave=1)\n% S12 (cross spectrum - frequencies x trials if trialave=0; dimension frequencies if trialave=1)\n% S1 (spectrum 1 - frequencies x trials if trialave=0; dimension frequencies if trialave=1)\n% S2 (spectrum 2 - frequencies x trials if trialave=0; dimension frequencies if trialave=1)\n% f (frequencies) \n% zerosp (1 for trials where no spikes were found, 0 otherwise)\n% confC (confidence level for C at 1-p %) - only for err(1)>=1\n% phistd - theoretical/jackknife (depending on err(1)=1/err(1)=2) standard deviation for phi \n% Note that phi + 2 phistd and phi - 2 phistd will give 95% confidence\n% bands for phi - only for err(1)>=1 \n% Cerr (Jackknife error bars for C - use only for Jackknife - err(1)=2) \n\nif nargin < 2; error('Need data1 and data2'); end\nif nargin < 3; params=[]; end;\n[tapers,pad,Fs,fpass,err,trialave,params]=getparams(params);\nclear params\nif nargin < 4 || isempty(fscorr); fscorr=0; end;\n\nif nargout > 7 && err(1)==0;\n%Cannot compute error bars if err(1)=0. Need to change params and run again. \n error('When errors are desired, err(1) has to be non-zero.'); \nend;\nif nargout > 9 && err(1)~=2; \n error('Cerr computed only for Jackknife. Correct inputs and run again');\nend;\n[N,Ch]=check_consistency(data1,data2);\nzerosp=zeros(1,Ch); % intialize the zerosp variable\n\nnfft=max(2^(nextpow2(N)+pad),N);\n[f,findx]=getfgrid(Fs,nfft,fpass); \ntapers=dpsschk(tapers,N,Fs); % check tapers\nJ1=mtfftc(data1,tapers,nfft,Fs); % fourier transform of continuous data\n[J2,Msp2,Nsp2]=mtfftpb(data2,tapers,nfft); % fourier transform of point process data\nzerosp(Nsp2==0)=1; % set the trials where no spikes were found to have zerosp=1\nJ1=J1(findx,:,:);\nJ2=J2(findx,:,:);\nS12=squeeze(mean(conj(J1).*J2,2));\nS1=squeeze(mean(conj(J1).*J1,2));\nS2=squeeze(mean(conj(J2).*J2,2));\nif trialave; S12=squeeze(mean(S12,2)); S1=squeeze(mean(S1,2)); S2=squeeze(mean(S2,2)); end;\nC12=S12./sqrt(S1.*S2);\nC=abs(C12);\nphi=angle(C12);\nif nargout==10; \n if fscorr==1; \n [confC,phistd,Cerr]=coherr(C,J1,J2,err,trialave,[],Nsp2);\n else\n [confC,phistd,Cerr]=coherr(C,J1,J2,err,trialave);\n end;\nelseif nargout==9;\n if fscorr==1; \n [confC,phistd]=coherr(C,J1,J2,err,trialave,[],Nsp2);\n else\n [confC,phistd]=coherr(C,J1,J2,err,trialave);\n end;\nend;\nclear Msp2\n", "meta": {"author": "buzsakilab", "repo": "buzcode", "sha": "2d700a38b3c2a860ad1333be90f14d7a37a72815", "save_path": "github-repos/MATLAB/buzsakilab-buzcode", "path": "github-repos/MATLAB/buzsakilab-buzcode/buzcode-2d700a38b3c2a860ad1333be90f14d7a37a72815/externalPackages/chronux_2_12/spectral_analysis/hybrid/coherencycpb.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6334102775181399, "lm_q2_score": 0.5039061705290806, "lm_q1q2_score": 0.3191793473179281}} {"text": " function [ob,m,mz] = Gocrf(k,fov,N,mdomswitch,dt,varargin)\n%function [ob,m,mz] = Gocrf(k,fov,N,m0,mdomswitch,dt,varargin)\n%\n% Construct Gocrf object for fast optimal control large-tip-angle \n% multidimensional (and parallel) MR RF pulse design. Used in \n% conjunction with an optimization routine, this object can be \n% used to design small pulse updates that, when summed with an \n% underlying pulse, result in an accurate excitation.\n% The vectors m and mz are the results of initial Bloch sim at \n% object creation.\n%\n% The object is created by calling:\n% Gocrf = Gocrf( ... );\n% and it is then used by commands like:\n% y = Gocrf * x;\n% which will evaluate perturbations to the magnetization\n% produced by pulse perturbations x. It also passes x with \n% unit weighting, so that if G is the sub-object relating \n% x to its perturbations, then y = [G;I]*x\n%\n% in: \n% k [Nt,d] excitation k-space trajectory\n% (= -gam int_t^T g(t') dt')\n% (inverse fov units)\n% fov [d,1] field of view in each dimension\n% N [d,1] size of design grid in each\n% dimension\n% mdomswitch [1] switch to evaluate magnetization\n% or spinors (spinors not tested yet)\n% dt [1] RF sampling period \n%\n% options: \n% m0 [3,1] initial magnetization state\n% (e.g., if equilibrium, [0 0 1] (default))\n% 'sens' [prod(N),Ncoils] transmit (B1+) sensitivities\n% 'd' [[N]] desired excitation pattern, in \n% arbitrary flip angle units. this is used\n% to determine sub-space over which to\n% simulate\n% 'indmask' [[N]] mask to choose sub-space points from\n% 'baseB1' [Ncoils*Nt] baseline RF pulse(s), used for\n% initial Bloch simulation during \n% object creation\n% 'g' [Nt,d] gradient waveforms, for Bloch simulation\n% (gauss/fov units)\n% 'Nsvd' [1] # of baseline excitation expansion terms\n% (default is 4)\n% 'a0B','b0B' [Nt,Nsvd] baseline temporal basis function\n% matrices\n% 'a0Ct','b0Ct' [prod(N),Nsvd] baseline spatial coefficient\n% matrices\n% 'a0','b0' [prod(N),1] final baseline spinors\n% 'nufft' cell nufft arguments (passed to Gmri_SENSE)\n% 'RFbasis' [Nt,Nbasis] RF pulse basis functions for\n% parameterized pulse design\n% \n% options for field-corrected pulse design (untested in this object!):\n% 'ti' [Nt,1] sample times (0:T in seconds)\n% 'we' [[N]] field_map (Hz)\n% 'L' [1] # of approximation terms (default is 4)\n% \n% After building this object, the user can Bloch-simulate\n% a new pulse and update the object using:\n% [ob,m,mz] = feval(ob.arg.update, ob, baseB1);\n%\n% or a Bloch simulation (without object update) can be performed\n% using:\n% [m,mz,a0,b0] = feval(ob.arg.blochsim,baseB1,arg,pos,sens,we);\n%\n% OR an update can be made (without Bloch sim) using:\n% ob = feval(ob.arg.new_B_Ct,ob,a0B,a0Ct,b0B,b0Ct,a0,b0)\n% \n% Copyright 2008-10-8, Will Grissom, Stanford University\n\nif nargin < 6, help(mfilename), error(mfilename), end\n\n%\n% default object\n%\n% Gmri objects \narg.a0G = [];arg.b0G = [];\n% svd matrices\narg.a0B = [];arg.a0Ct = [];arg.b0B = [];arg.b0Ct = [];\n% underlying final alpha0, beta0\narg.a0 = [];arg.b0 = [];\n% initial mag (global)\narg.bsq = 0; % \narg.exc = 0; % just return mxy\narg.rfb = 0; % no rf basis\narg.m0 = [0 0 1];\narg.mdomswitch = mdomswitch;\narg.we = [];\narg.nufft_args = {N,6*ones(size(N)),2*N,N/2,'table',2^10,'minmax:kb'}; \narg.new_B_Ct = @Gocrf_new_B_Ct; \narg.blochsim = @Gocrf_blochsim;\narg.subindcalc = @Gocrf_subindcalc;\narg.update = @Gocrf_update;\narg.subind = []; % set of points to Bloch sim and do SVD on\narg.nsubbins = 10; % default # of histogram bins to choose sub-points from\narg.simpos = []; % spatial locations for Bloch sim\narg.sens = []; % need sens for Bloch sims\narg.d = []; % desired pattern (for subind calc)\narg.indmask = []; % mask (for subind calc)\narg.simmask = []; % mask for Bloch simulation\narg.dt = dt; % sampling period\narg.ti = []; % time points (for field-map corrected design)\narg.fov = fov; \narg.k = k; % excitation k-space traj \narg.N = N; % spatial dimensions\narg.L = 4;\narg.Nsvd = 4;\narg.subindlen = 15*arg.Nsvd; % default # of sub-points for svd sim\n% field map bases and coeffs\narg.B = [];arg.Ct = [];\narg.baseB1 = []; % base B1 pulses (for Bloch sim)\narg.g = []; % gradient waveforms (for Bloch sim)\narg.fmod = []; % modulation freq (for eg dual band designs)\narg.aux1 = 1; % vector to multiply a or mxy by\narg.aux2 = 1; % vector to multiply b or b^2 or mz by\narg.RFbasis = [];\nob.Nbasis = 0;\n% Bloch-simulated patterns (will be empty if basis and coeff\n% matrices are provided)\nm = [];mz = [];\n\ngambar = 4257; % gamma/2pi in Hz/g\ngam = gambar*2*pi; % gamma in radians/g\n\narg = vararg_pair(arg, varargin, 'subs', ...\n\t{'basis', 'basis_args'; 'nufft', 'nufft_args'});\n\n% if not provided, get the subindices for Bloch sim\nif isempty(arg.subind) & ~isempty(arg.d) & ~isempty(arg.indmask)\n arg = Gocrf_subindcalc(arg,arg.d,arg.indmask);\nelseif isempty(arg.subind)\n disp ['No sub indices or means to calculate them provided. update() ' ...\n 'will not work'];\nend\n\nktmp = -[arg.k - repmat(arg.k(1,:)/2,[size(arg.k,1) 1])];\nif isempty(arg.we) || sum(abs(arg.we(:))) == 0 % no field map\n \n\tif ~isempty(arg.sens)\n\t\targ.a0G = Gmri_SENSE(ktmp,true(N),'fov',fov, ...\n\t\t\t'basis',{'dirac'},'nufft',arg.nufft_args, ...\n\t\t\t'exact',0,'sens',arg.sens*(-1i*gam*arg.dt/2))';\n\t\targ.b0G = Gmri_SENSE(ktmp,true(N),'fov',fov, ...\n\t\t\t'basis',{'dirac'},'nufft',arg.nufft_args, ...\n\t\t\t'exact',0,'sens',arg.sens*(1i*gam*arg.dt/2))';\n\telse\n%{\n\t\targ.a0G = Gmri_SENSE(ktmp,true(N),'fov',fov,'basis',{'dirac'},'nufft',arg.nufft_args, ...\n 'exact',0,'sens',ones(prod(N),1)*(-1i*gam*arg.dt/2))';\n\t\targ.b0G = Gmri_SENSE(ktmp,true(N),'fov',fov,'basis',{'dirac'},'nufft',arg.nufft_args, ...\n 'exact',0,'sens',ones(prod(N),1)*(1i*gam*arg.dt/2))';\n%}\n\t\t% jf version:\n\t\targ.a0G = (-1i*gam*arg.dt/2)' * ...\n\t\t\tGmri(ktmp, true(N), 'fov', fov, 'basis', {'dirac'}, ...\n\t\t\t\t'nufft',arg.nufft_args)';\n\t\targ.b0G = (1i*gam*arg.dt/2)' * ...\n\t\t\tGmri(ktmp, true(N), 'fov', fov, 'basis', {'dirac'}, ...\n\t\t\t\t'nufft', arg.nufft_args)';\n\n\tend\n\nelse % non-zero field map\n \n\tif ~isempty(arg.sens)\n\t\targ.a0G = Gmri_SENSE(ktmp,true(N),'fov',fov,...\n\t\t\t'basis',{'dirac'},'nufft',arg.nufft_args, ...\n\t\t\t'exact',0,'sens',arg.sens*(-1i*gam*arg.dt/2), ...\n\t\t\t'ti',-arg.ti+arg.ti(end)/2,...\n\t\t\t'zmap',1i*2*pi/2*arg.we,'L',arg.L)';\n\t\targ.b0G = Gmri_SENSE(ktmp,true(N),'fov',fov,...\n\t\t\t'basis',{'dirac'},'nufft',arg.nufft_args, ...\n\t\t\t'exact',0,'sens',arg.sens*(1i*gam*arg.dt/2), ...\n\t\t\t'ti',-arg.ti+arg.ti(end)/2, ...\n\t\t\t'zmap',1i*2*pi/2*arg.we,'L',arg.L)';\n\telse\n%{\n\t\targ.a0G = Gmri_SENSE(ktmp,true(N),'fov',fov,...\n\t\t\t'basis',{'dirac'},'nufft',arg.nufft_args, ...\n\t\t\t'exact',0,'sens',ones(prod(N),1)*(-1i*gam*arg.dt/2), ...\n\t\t\t'ti',-arg.ti+arg.ti(end)/2, ...\n\t\t\t'zmap',1i*2*pi/2*arg.we,'L',arg.L)';\n\t\targ.b0G = Gmri_SENSE(ktmp,true(N),'fov',fov, ...\n\t\t\t'basis',{'dirac'},'nufft',arg.nufft_args, ...\n\t\t\t'exact',0,'sens',ones(prod(N),1)*(1i*gam*arg.dt/2), ...\n \t\t\t'ti',-arg.ti+arg.ti(end)/2, ...\n\t\t\t'zmap',1i*2*pi/2*arg.we,'L',arg.L)';\n%}\n\t\t% jf version:\n\t\targ.a0G =(-1i*gam*arg.dt/2)' * ...\n\t\t\tGmri(ktmp,true(N),'fov',fov,...\n\t\t\t\t'basis',{'dirac'},'nufft',arg.nufft_args, ...\n\t\t\t\t'ti',-arg.ti+arg.ti(end)/2, ...\n\t\t\t\t'zmap',1i*2*pi/2*arg.we,'L',arg.L)';\n\t\targ.b0G = (1i*gam*arg.dt/2)' * ...\n\t\t\tGmri(ktmp,true(N),'fov',fov, ...\n\t\t\t\t'basis',{'dirac'},'nufft',arg.nufft_args, ...\n \t\t\t\t'ti',-arg.ti+arg.ti(end)/2, ...\n\t\t\t\t'zmap',1i*2*pi/2*arg.we,'L',arg.L)';\n\tend\n\n\targ.B = arg.a0G.arg.B;\n\targ.Ct = arg.a0G.arg.Ct;\nend\n\ntmp = arg.a0G;\n[dim1,dim2] = size(tmp);\nif arg.exc\n arg.dim = [dim1 + 2*dim2, 2*dim2];\nelse\n arg.dim = [2*dim1+2*dim2, 2*dim2];\nend\n\nif ~isempty(arg.RFbasis)\n\n arg.rfb = 1; \n arg.Nbasis = size(arg.RFbasis,2);\n \n % assuming that there is only one coil when we parameterize the\n % pulse, adjust object dims\n if arg.exc\n arg.dim = [dim1 + 2*arg.Nbasis, 2*arg.Nbasis];\n else\n arg.dim = [2*dim1 + 2*arg.Nbasis, 2*arg.Nbasis];\n end\n \n % allocate space for basis perturbations\n arg.Gat = zeros(dim1,arg.Nbasis);\n arg.Gbt = zeros(dim1,arg.Nbasis);\n \nend\n \narg.is.empty = false;\n\n% now build object\n%ob = Fatrix(arg.dim, arg, 'caller', mfilename, ...\n%\t'forw', @Gocrf_forw, 'back', @Gocrf_back);\nob = fatrix2('odim', arg.dim(1), 'idim', arg.dim(2), ...\n\t'arg', arg, ...\n\t'forw', @Gocrf_forw, 'back', @Gocrf_back); % jf\n\n% if SVD matrices not supplied, do the necessary Bloch sims\nif isempty(ob.arg.a0B)\n % get Bloch simulation grid\n ndgridarg = ['-fov(1)/2:fov(1)/N(1):fov(1)/2-fov(1)/N(1)'];\n posarg = ['x1'];\n for ii = 2:length(N)\n ndgridarg = [ndgridarg sprintf(',-fov(%d)/2:fov(%d)/N(%d):fov(%d)/2-fov(%d)/N(%d)',ii,ii,ii,ii,ii,ii)];\n posarg = [posarg sprintf(',x%d',ii)];\n end\n eval(sprintf('[%s] = ndgrid(%s);',posarg,ndgridarg));\n ob.arg.simpos = [x1(:)];\n for ii = 2:length(N)\n ob.arg.simpos = [ob.arg.simpos eval(sprintf('x%d(:)',ii))];\n end\n % do the Bloch sims and expansion calc\n [ob,m,mz] = Gocrf_update(ob,ob.arg.baseB1);\n % we don't need base B1 anymore\n ob.arg.baseB1 = [];\nend\n \n\n%\n% Gocrf_new_B_Ct()\n% new values of (svd) bases and coefficients\n%\nfunction G = Gocrf_new_B_Ct(G, a0B, a0Ct, b0B, b0Ct, a0, b0)\n\n% apply frequency modulation to basis matrices\nif ~isempty(G.arg.fmod)\n t = [0:G.arg.dt:(size(G.arg.k,1)-1)*G.arg.dt] - size(G.arg.k,1)*G.arg.dt/2;\n Amod = repmat(exp(1i*2*pi*G.arg.fmod*t(:)),[1 G.arg.Nsvd]);\n a0B = a0B .* Amod;\n b0B = b0B .* Amod;\nend\n\nif ~isempty(G.arg.we) & sum(abs(G.arg.we(:))) ~= 0\n % multiply out new expansion with field map expansion\n newa0B = [];newa0Ct = [];\n newb0B = [];newb0Ct = [];\n for ll = 1:G.arg.L\n newa0B = [newa0B spdiag(G.arg.B(:,ll))*a0B];\n newa0Ct = [newa0Ct spdiag(G.arg.Ct(:,ll))*a0Ct];\n newb0B = [newb0B spdiag(G.arg.B(:,ll))*b0B];\n newb0Ct = [newb0Ct spdiag(G.arg.Ct(:,ll))*b0Ct];\n end\n % update G with provided B and C.' matrices\n G.arg.a0G = feval(G.arg.a0G.arg.new_B_Ct,G.arg.a0G,newa0B,newa0Ct);\n G.arg.b0G = feval(G.arg.b0G.arg.new_B_Ct,G.arg.b0G,newb0B,newb0Ct);\nelse\n % set the expansion directly\n G.arg.a0G = feval(G.arg.a0G.arg.new_B_Ct,G.arg.a0G,a0B,a0Ct);\n G.arg.b0G = feval(G.arg.b0G.arg.new_B_Ct,G.arg.b0G,b0B,b0Ct);\nend\n\nG.arg.a0 = a0;\nG.arg.b0 = b0;\n\n\n% \n% Gocrf_forw(): y = G * x\n%\nfunction v = Gocrf_forw(arg, u)\n\n% assume the RF vector is [real(db1); imag(db1)]\ndb1 = u(1:length(u)/2) + 1i*u(length(u)/2+1:end);\n\nif ~arg.rfb\n if any(db1)\n at = arg.b0G * conj(db1);\n bt = arg.a0G * conj(db1);\n else\n at = zeros(size(arg.b0G,1),1);\n bt = zeros(size(arg.a0G,1),1);\n end\nelse % pulse is parameterized\n if any(db1)\n at = arg.Gat * conj(db1);\n bt = arg.Gbt * conj(db1);\n else\n at = zeros(size(arg.Gat,1),1);\n bt = zeros(size(arg.Gbt,1),1);\n end\nend\n\nif arg.mdomswitch\n % dm terms, equilibrium\n dm = 0;dmz = 0;\n if arg.m0(3) ~= 0\n % dm terms, equilibrium\n dm = -2*arg.m0(3)*conj(arg.a0(:).*bt + at.*arg.b0(:));\n % dmz, equilibrium\n dmz = 2*arg.m0(3)*real(arg.a0(:).*conj(at)) - 2*arg.m0(3)*real(arg.b0(:).*conj(bt));\n end\n if any(arg.m0(1:2) ~= 0)\n % dm terms, non-equilibrium\n dm = dm - (arg.m0(1)-1i*arg.m0(2))*conj(2*arg.b0(:).*bt);\n dm = dm + (arg.m0(1)+1i*arg.m0(2))*conj(2*arg.a0(:).*at);\n % dmz, non-equilibrium\n dmz = dmz + 2*real((arg.m0(1)+1i*arg.m0(2))*(conj(arg.a0(:)).*bt + conj(at).*arg.b0(:)));\n end\n if ~arg.exc\n v = [arg.aux1.*dm;arg.aux2.*dmz;u];\n else\n v = [arg.aux1.*dm;u];\n end\nelse\n if ~arg.bsq\n v = [arg.aux1.*at;arg.aux2.*bt;u]; \n else\n v = [2*arg.aux1.*arg.a0(:).*at;2*arg.aux2.*arg.b0(:).*bt;u];\n end\nend\n\n\n% \n% Gocrf_back(): x = G' * y\n%\nfunction v = Gocrf_back(arg,u)\n\nv = zeros(size(arg.a0G,2),1);\nNs = size(arg.a0G,1);\ntmp1 = 0; tmp2 = 0;\n\n% tmp1 contains terms that will multiply by system matrix for at\nif arg.mdomswitch\n if arg.m0(3) ~= 0\n if ~arg.exc\n tmp1 = arg.m0(3)*2*conj(-arg.b0(:).*u(1:Ns)+conj(arg.a0(:)).*u(Ns+1:2*Ns));\n else\n tmp1 = arg.m0(3)*2*conj(-arg.b0(:).*u(1:Ns));\n end\n end\n if any(arg.m0(1:2) ~= 0)\n % additional alphat terms from Mxy, if non-equilibrium ic\n tmp1 = tmp1 + 2*conj((arg.m0(1)-1i*arg.m0(2))*arg.a0(:).*u(1:Ns)); \n % additional alphat terms from Mz, if non-equilibrium ic\n if ~arg.exc\n tmp1 = tmp1 + 2*(arg.m0(1)+1i*arg.m0(2))*arg.b0(:).*conj(u(Ns+1:2*Ns));\n end\n end\n % tmp2 contains terms that will multiply by system matrix for betat\n if arg.m0(3) ~= 0\n if ~arg.exc\n tmp2 = -arg.m0(3)*2*conj(arg.a0(:).*u(1:Ns)+conj(arg.b0(:)).*u(Ns+1:2*Ns));\n else\n tmp2 = -arg.m0(3)*2*conj(arg.a0(:).*u(1:Ns));\n end\n end\n if any(arg.m0(1:2) ~= 0)\n % additional betat terms from Mxy, if non-equilibrium ic\n tmp2 = tmp2 - 2*conj((arg.m0(1)+1i*arg.m0(2))*arg.b0(:).*u(1:Ns)); \n % additional betat terms from Mz, if non-equilibrium ic\n if ~arg.exc\n tmp2 = tmp2 + 2*conj((arg.m0(1)+1i*arg.m0(2))*conj(arg.a0(:)).*u(Ns+1:2*Ns));\n end\n end\nelse\n\n if ~arg.bsq\n tmp1 = u(1:Ns);\n tmp2 = u(Ns+1:2*Ns);\n else\n tmp1 = 2*conj(arg.a0(:)).*u(1:Ns);\n tmp2 = 2*conj(arg.b0(:)).*u(Ns+1:2*Ns);\n end\nend\n\nif ~arg.rfb\n v = conj(arg.a0G' * (conj(arg.aux2).*tmp2));\n v = v + conj(arg.b0G' * (conj(arg.aux1).*tmp1));\nelse\n v = conj(arg.Gbt' * (conj(arg.aux2).*tmp2));\n v = v + conj(arg.Gat' * (conj(arg.aux1).*tmp1));\nend\n\nif ~arg.exc\n v = [real(v);imag(v)] + u(2*Ns+1:end);\nelse\n v = [real(v);imag(v)] + u(Ns+1:end);\nend\n\n\n% \n% Gocrf_subindcalc(): Determine subset of points to simulate for \n% SVD evaluation\nfunction arg = Gocrf_subindcalc(arg,d,indmask)\n\n% get bin centers\nif min(d(:)) == max(d(:))\n fa = min(d(:))*ones(arg.nsubbins+1,1);\nelse\n fa = min(d(:)):(max(d(:))-min(d(:)))/arg.nsubbins:max(d(:));\nend\n\ndind = 1:prod(size(d));\n\n% arrange indices into bins\nindices{1} = dind(col(logical(indmask.*(d >= fa(1) & d <= fa(2)))));\nfor ii = 2:length(fa)-1\n indices{ii} = dind(col(logical(indmask.*(d > fa(ii) & d <= fa(ii+1)))));\nend\n \n% loop through bins again and again, pulling one from each bin\n% each time around at random (use rand*size(bin)), until \n% index vector is full. This works much better than my\n% previous method, which failed for filter-based desired patterns\nindvec = [];\nindind = 0;\nrand('twister',1000);\nwhile length(indvec) < arg.subindlen\n if ~isempty(indices{indind+1})\n binind = ceil(length(indices{indind+1})*rand(1,1));\n indvec = [indvec indices{indind+1}(binind)];\n indices{indind+1} = [indices{indind+1}(1:binind-1) ...\n indices{indind+1}(binind+1:end)];\n end\n indind = mod(indind + 1,arg.nsubbins);\nend\n\narg.subind = indvec;\n\n\n%\n% Gocrf_update(): Perform Bloch sims to update SVD expansions\n% \nfunction [G,m,mz] = Gocrf_update(G,baseB1) \n\n% perform reduced Bloch sim\nif isfield(G.arg, 'sens') && ~isempty(G.arg.sens) % jf\n\n if ~isempty(G.arg.we) & sum(abs(G.arg.we(:))) ~= 0\n [foo,fooz,alpha0,beta0] = Gocrf_blochsim(baseB1,G.arg,G.arg.simpos(G.arg.subind,:), ...\n G.arg.sens(G.arg.subind,:),G.arg.we(G.arg.subind));\n else\n [foo,fooz,alpha0,beta0] = Gocrf_blochsim(baseB1,G.arg,G.arg.simpos(G.arg.subind,:), ...\n G.arg.sens(G.arg.subind,:),G.arg.we);\n end\n\nelse\n\n if ~isempty(G.arg.we) & sum(abs(G.arg.we(:))) ~= 0\n [foo,fooz,alpha0,beta0] = Gocrf_blochsim(baseB1,G.arg,G.arg.simpos(G.arg.subind,:), ...\n ones(size(G.arg.subind)),G.arg.we(G.arg.subind));\n else\n [foo,fooz,alpha0,beta0] = Gocrf_blochsim(baseB1,G.arg,G.arg.simpos(G.arg.subind,:), ...\n ones(size(G.arg.subind)),G.arg.we);\n end\n\nend\n\n% calculate rotating frame transformation\nktmp = -[G.arg.k - repmat(G.arg.k(1,:),[size(G.arg.k,1) 1])];\nAsub = exp(1i*2*pi/2*G.arg.simpos(G.arg.subind,:)*ktmp');\nif ~isempty(G.arg.fmod)\n t = 0:G.arg.dt:G.arg.dt*(size(G.arg.k,1)-1);\n Asub = Asub.*exp(-1i*2*pi/2*repmat(G.arg.fmod*t,[length(G.arg.subind) 1]));\nend\n\nif ~isempty(G.arg.we) & sum(abs(G.arg.we(:))) ~= 0\n t = 0:G.arg.dt:G.arg.dt*(size(G.arg.k,1)-1);\n Asub = Asub.*exp(-1i*2*pi/2*G.arg.we(G.arg.subind).'*t);\nend\n\n% get temporal basis funcs via svd\n[foo1,foo2,G.arg.a0B] = svd(conj(alpha0)./Asub,'econ');\n[foo1,foo2,G.arg.b0B] = svd(conj(beta0)./Asub,'econ');\n\n% truncate basis\nG.arg.a0B = G.arg.a0B(:,1:G.arg.Nsvd);\nG.arg.b0B = G.arg.b0B(:,1:G.arg.Nsvd);\n\n% re-simulate to get coeffs at all spatial locs\nif ~isempty(G.arg.sens)\n [m,mz,G.arg.a0,G.arg.b0,G.arg.a0Ct,G.arg.b0Ct] = Gocrf_blochsim(baseB1,G.arg,G.arg.simpos,G.arg.sens,G.arg.we,G.arg.simmask);\nelse\n [m,mz,G.arg.a0,G.arg.b0,G.arg.a0Ct,G.arg.b0Ct] = Gocrf_blochsim(baseB1,G.arg,G.arg.simpos,ones(size(G.arg.simpos,1),1),G.arg.we,G.arg.simmask);\nend\n\nm = reshape(m,G.arg.N);\nmz = reshape(mz,G.arg.N);\nG.arg.a0 = reshape(G.arg.a0,G.arg.N);\nG.arg.b0 = reshape(G.arg.b0,G.arg.N);\n\n% recalculate subindices based on Bloch sim results, in\n% anticipation of the next update\n%G.arg = Gocrf_subindcalc(G.arg,real(asin(abs(m))),G.arg.indmask);\njf_tmp = Gocrf_subindcalc(G.arg,real(asin(abs(m))),G.arg.indmask);\nG = subsasgn_trick(G, 'arg', jf_tmp); % jf kludge for now\n\n% then stick them into the Gmri objects\nG = Gocrf_new_B_Ct(G,G.arg.a0B,G.arg.a0Ct,G.arg.b0B,G.arg.b0Ct,G.arg.a0,G.arg.b0);\n\nif ~isempty(G.arg.RFbasis)\n % evaluate perturbations for basis functions\n for ll = 1:G.arg.Nbasis\n G.arg.Gat(:,ll) = G.arg.b0G * conj(G.arg.RFbasis(:,ll));\n G.arg.Gbt(:,ll) = G.arg.a0G * conj(G.arg.RFbasis(:,ll));\n end \nend\n\n\n% \n% Gocrf_blochsim(): Perform a Bloch simulation\n%\nfunction [m,mz,a,b,a0Ct,b0Ct] = Gocrf_blochsim(B1,arg,pos,sens,we,simmask)\n\ngambar = 42570000; % gamma/2pi in Hz/T\ngam = gambar*2*pi/10000; % gamma in radians/g\n\nif nargin == 6\n if ~isempty(simmask)\n % filter out un-sim'd spatial locs\n pos = pos(logical(simmask(:)),:);\n sens = sens(logical(simmask(:)),:);\n if ~isempty(we)\n we = we(logical(simmask));\n end\n end\nend\n\nNs = size(pos,1);\nNt = size(arg.g,1);\n\nstatea = ones(Ns,1);\nstateb = zeros(Ns,1);\n\n% sum up RF over coils\nB1 = reshape(B1,[size(arg.g,1) size(sens,2)]).';\nbxy = sens * B1;\n\n% sum up gradient over channels\nbz = pos * arg.g';\n\n% add off-resonance\nif ~isempty(we) & sum(abs(we(:))) ~= 0\n bz = bz + repmat(we(:)/gam*2*pi,1,Nt);\nend\n\nif ~isempty(arg.fmod)\n bz = bz + arg.fmod/gam*2*pi;\nend\n\ntmp = zeros(2*Ns,1);\n\nif nargout == 4\n % if we are only calling it with four output args,\n % assume we are doing the subspace sim and return all\n % states. Otherwise, we only return the final state.\n returnallstate = 1;\n a = zeros(Ns,Nt);\n b = zeros(Ns,Nt);\nelse; returnallstate = 0; end\n\n% check if we need to do the running inner product to get spatial coeffs\nif nargout == 6; \n inprod = 1; \n a0Ct = 0;b0Ct = 0;\n tvec = 0:arg.dt:(Nt-1)*arg.dt;\nelse; inprod = 0; end\n\nktmp = -[arg.k - repmat(arg.k(1,:),[size(arg.k,1) 1])];\n\nfor tt = 1:Nt\n \n phi = arg.dt*gam*(abs(bxy(:,tt)).^2+bz(:,tt).^2).^0.5;\n normfact = arg.dt*gam*(phi.^(-1));normfact(~isfinite(normfact)) = 0;\n nxy = normfact.*bxy(:,tt);nxy(~isfinite(nxy)) = 0;\n nz = normfact.*bz(:,tt);nz(~isfinite(nz)) = 0;\n cp = cos(phi/2);\n sp = sin(phi/2);\n alpha = cp+1i*nz.*sp;\n beta = 1i*conj(nxy).*sp;\n \n tmpa = alpha.*statea + beta.*stateb;\n tmpb = -conj(beta).*statea + conj(alpha).*stateb;\n \n statea = tmpa;stateb = tmpb;\n if any(~isfinite(statea)); keyboard; end;\n if any(~isfinite(stateb)); keyboard; end;\n if returnallstate\n a(:,tt) = statea;\n b(:,tt) = -conj(stateb); \n end\n\n if inprod\n % build drf transform vector\n Asub = exp(-1i*2*pi/2*pos*ktmp(tt,:).');\n if ~isempty(we) & sum(abs(we(:))) ~= 0\n Asub = Asub.*exp(1i*2*pi/2*we(:)*tvec(tt));\n end\n if ~isempty(arg.fmod)\n Asub = Asub.*exp(1i*2*pi/2*arg.fmod*ones(size(pos,1),1)*tvec(tt));\n end\n % get B matrix coeffs\n a0Ct = a0Ct + conj((conj(statea).*Asub)*arg.a0B(tt,:));\n b0Ct = b0Ct - conj((stateb.*Asub)*arg.b0B(tt,:));\n end\n \nend\n\n% return final alpha, beta if not returning the whole \n% state progression\nif ~returnallstate\n a = statea;\n b = -conj(stateb);\nend\n\n% calculate final magnetization state\nmxy0 = arg.m0(1)+1i*arg.m0(2);\nmz0 = arg.m0(3);\nm = mz0*2*conj(statea).*stateb;\nm = m + mxy0*conj(statea).^2;\nm = m - conj(mxy0)*stateb.^2;\nmz = mz0*(statea.*conj(statea) - stateb.*conj(stateb));\nmz = mz + 2*real(mxy0*conj(statea).*-conj(stateb));\n\n% embed results, if we did a masked sim\nif nargin == 6\n if ~isempty(simmask)\n tmp = zeros(size(simmask(:)));tmp(logical(simmask)) = a;a = tmp;\n tmp = zeros(size(simmask(:)));tmp(logical(simmask)) = b;b = tmp;\n tmp = zeros(size(simmask(:)));tmp(logical(simmask)) = m;m = tmp;\n tmp = zeros(size(simmask(:)));tmp(logical(simmask)) = mz;mz = tmp;\n tmpa0Ct = zeros(length(simmask(:)),size(arg.a0B,2));\n tmpb0Ct = zeros(length(simmask(:)),size(arg.b0B,2));\n for ii = 1:size(arg.a0B,2)\n tmpa0Ct(logical(simmask),ii) = a0Ct(:,ii);\n tmpb0Ct(logical(simmask),ii) = b0Ct(:,ii);\n end\n a0Ct = tmpa0Ct;b0Ct = tmpb0Ct;\n end\nend\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/contrib/grissom-mri-rf-large-tip/Gocrf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.4035668537353746, "lm_q1q2_score": 0.3190318334879437}} {"text": "function [mustUSet, posMustU] = findMustUWithGAMS(model, minFluxesW, maxFluxesW, varargin)\n% This function runs the second step of `optForce`, that is to solve a\n% bilevel mixed integer linear programming problem to find a first order\n% `MustU` set.\n%\n% USAGE:\n%\n% [mustUSet, posMustU] = findMustUWithGAMS(model, minFluxesW, maxFluxesW, varargin)\n%\n%\n% INPUTS:\n% model: (structure) a metabolic model with at\n% least the following fields:\n%\n% * .rxns - Reaction IDs in the model\n% * .mets - Metabolite IDs in the model\n% * .S - Stoichiometric matrix (sparse)\n% * .b - RHS of `Sv = b` (usually zeros)\n% * .c - Objective coefficients\n% * .lb - Lower bounds for fluxes\n% * .ub - Upper bounds for fluxes\n% minFluxesW: (double array of size `n_rxns x 1`) minimum\n% fluxes for each reaction in the model for\n% wild-type strain. This can be obtained by\n% running the function `FVAOptForce` e.g.:\n% `minFluxesW = [-90; -56];`\n% maxFluxesW: (double array of size `n_rxns x 1`) maximum\n% fluxes for each reaction in the model for\n% wild-type strain. This can be obtained by\n% running the function `FVAOptForce` e.g.:\n% `maxFluxesW = [90; 56];`\n%\n% OPTIONAL INPUTS:\n% constrOpt: (Structure) structure containing\n% additional contraints. Include here only\n% reactions whose flux is fixed, i.e.,\n% reactions whose lower and upper bounds\n% have the same value. Do not include here\n% reactions whose lower and upper bounds\n% have different values. Such contraints\n% should be defined in the lower and upper\n% bounds of the model. The structure has the\n% following fields:\n%\n% * .rxnList - Reaction list (cell array)\n% * .values - Values for constrained reactions (double array)\n% e.g.: `struct('rxnList',{{'EX_gluc','R75','EX_suc'}},'values',[-100,0,155.5]');`\n% solverName: (string) Name of the solver used in GAMS.\n% Default = 'cplex'\n% runID: (string) ID for identifying this run\n% outputFolder: (string) name for folder in which\n% results will be stored\n% outputFileName: (string) name for files in which results\n% will be stored\n% printExcel: (double) boolean to describe wheter data\n% must be printed in an excel file or not\n% printText: (double) boolean to describe wheter data\n% must be printed in an plaint text file or\n% not\n% printReport: (double) 1 to generate a report in a\n% plain text file. 0 otherwise.\n% keepInputs: (double) 1 to mantain folder with inputs\n% to run `findMustUU.gms`. 0 otherwise.\n% keepGamsOutputs: (double) 1 to mantain files returned by\n% `findMustUU.gms`. 0 otherwise.\n% verbose: (double) 1 to print results in console.\n% 0 otherwise.\n% OUTPUTS:\n% mustUSet: (cell array of size number of reactions\n% found X 1) Cell array containing the\n% reactions ID which belong to the `Must_U`\n% Set\n% posMustU: (double array of size number of reactions\n% found X 1) double array containing the\n% positions of reactions in the model.\n% outputFileName.xls: (file) File containing one column array\n% with identifiers for reactions in MustU.\n% This file will only be generated if the\n% user entered `printExcel = 1`. Note that the\n% user can choose the name of this file\n% entering the input `outputFileName = 'PutYourOwnFileNameHere';`\n% outputFileName.txt: (file) File containing one column array\n% with identifiers for reactions in MustU.\n% This file will only be generated if the\n% user entered `printText = 1`. Note that the\n% user can choose the name of this file\n% entering the input `outputFileName = 'PutYourOwnFileNameHere';`\n% outputFileName_Info.xls: (file) File containing five column\n% arrays.\n%\n% * C1: identifiers for reactions in `MustU`\n% * C2: min fluxes for reactions according to FVA\n% * C3: max fluxes for reactions according to FVA\n% * C4: min fluxes achieved for reactions,\n% according to `findMustU.gms`\n% * C5: max fluxes achieved for reactions,\n% according to `findMustU.gms`\n% This file will only be generated if the\n% user entered `printExcel = 1`. Note that the\n% user can choose the name of this file\n% entering the input `outputFileName = 'PutYourOwnFileNameHere';`\n% outputFileName_Info.txt: (file) File containing five column\n% arrays.\n%\n% * C1: identifiers for reactions in MustU\n% * C2: min fluxes for reactions according to FVA\n% * C3: max fluxes for reactions according to FVA\n% * C4: min fluxes achieved for reactions,\n% according to `findMustU.gms`\n% * C5: max fluxes achieved for reactions,\n% according to `findMustU.gms`\n% This file will only be generated if the\n% user entered `printText = 1`. Note that the\n% user can choose the name of this file\n% entering the input `outputFileName = 'PutYourOwnFileNameHere';`\n% findMustU.lst: (file) file autogenerated by GAMS. It\n% contains information about equations,\n% variables, parameters as well as\n% information about the running (values at\n% each iteration). This file only will be\n% saved in the output folder is the user\n% entered `keepGamsOutputs = 1`\n% GtoMU.gdx: (file) file containing values for\n% variables, parameters, etc. which were\n% found by GAMS when solving `findMustU.gms`.\n% This file only will be saved in the output\n% folder is the user entered `keepInputs = 1`\n%\n% NOTE:\n%\n% This function is based in the GAMS files written by Sridhar\n% Ranganathan which were provided by the research group of Costas D.\n% Maranas. For a detailed description of the `optForce` procedure, please\n% see: `Ranganathan S, Suthers PF, Maranas CD (2010) OptForce: An\n% Optimization Procedure for Identifying All Genetic Manipulations\n% Leading to Targeted Overproductions. PLOS Computational Biology 6(4):\n% e1000744`. https://doi.org/10.1371/journal.pcbi.1000744\n%\n% .. Author: - Sebastian Mendoza, May 30th 2017, Center for Mathematical Modeling, University of Chile, snmendoz@uc.cl\n\noptionalParameters = {'constrOpt', 'solverName', 'runID', 'outputFolder', 'outputFileName', ...\n 'printExcel', 'printText', 'printReport', 'keepInputs', 'keepGamsOutputs', 'verbose'};\n\nif (numel(varargin) > 0 && (~ischar(varargin{1}) || ~any(ismember(varargin{1},optionalParameters))))\n\n tempargin = cell(1,2*(numel(varargin)));\n for i = 1:numel(varargin)\n\n tempargin{2*(i-1)+1} = optionalParameters{i};\n tempargin{2*(i-1)+2} = varargin{i};\n end\n varargin = tempargin;\n\nend\n\nparser = inputParser();\nparser.addRequired('model',@(x) isstruct(x) && isfield(x, 'S') && isfield(model, 'rxns')...\n && isfield(model, 'mets') && isfield(model, 'lb') && isfield(model, 'ub') && isfield(model, 'b')...\n && isfield(model, 'c'))\nparser.addRequired('minFluxesW',@isnumeric)\nparser.addRequired('maxFluxesW',@isnumeric)\nparser.addParamValue('constrOpt', struct('rxnList', {{}}, 'values', []), @(x) isstruct(x) && isfield(x, 'rxnList') && isfield(x, 'values') ...\n && length(x.rxnList) == length(x.values) && length(intersect(x.rxnList, model.rxns)) == length(x.rxnList))\nsolvers = checkGAMSSolvers('MIP');\nif isempty(solvers)\n error('there is no GAMS solvers available to solver Mixed Integer Programming problems') ;\nelse\n if ismember('cplex', lower(solvers))\n defaultSolverName = 'cplex';\n else\n defaultSolverName = lower(solvers(1));\n end\nend\nparser.addParamValue('solverName', defaultSolverName, @(x) ischar(x))\nhour = clock; defaultRunID = ['run-' date '-' num2str(hour(4)) 'h' '-' num2str(hour(5)) 'm'];\nparser.addParamValue('runID', defaultRunID, @(x) ischar(x))\nparser.addParamValue('outputFolder', 'OutputsFindMustU', @(x) ischar(x))\nparser.addParamValue('outputFileName', 'MustUSet', @(x) ischar(x))\nparser.addParamValue('printExcel', 1, @(x) isnumeric(x) || islogical(x));\nparser.addParamValue('printText', 1, @(x) isnumeric(x) || islogical(x));\nparser.addParamValue('printReport', 1, @(x) isnumeric(x) || islogical(x));\nparser.addParamValue('keepInputs', 1, @(x) isnumeric(x) || islogical(x));\nparser.addParamValue('keepGamsOutputs', 1, @(x) isnumeric(x) || islogical(x));\nparser.addParamValue('verbose', 1, @(x) isnumeric(x) || islogical(x));\n\nparser.parse(model, minFluxesW, maxFluxesW, varargin{:})\nmodel = parser.Results.model;\nminFluxesW = parser.Results.minFluxesW;\nmaxFluxesW = parser.Results.maxFluxesW;\nconstrOpt= parser.Results.constrOpt;\nsolverName = parser.Results.solverName;\nrunID = parser.Results.runID;\noutputFolder = parser.Results.outputFolder;\noutputFileName = parser.Results.outputFileName;\nprintExcel = parser.Results.printExcel;\nprintText = parser.Results.printText;\nprintReport = parser.Results.printReport;\nkeepInputs = parser.Results.keepInputs;\nkeepGamsOutputs = parser.Results.keepGamsOutputs;\nverbose = parser.Results.verbose;\n\n% correct size of constrOpt\nif ~isempty(constrOpt.rxnList)\n if size(constrOpt.rxnList, 1) > size(constrOpt.rxnList,2); constrOpt.rxnList = constrOpt.rxnList'; end;\n if size(constrOpt.values, 1) > size(constrOpt.values,2); constrOpt.values = constrOpt.values'; end;\nend\n\n% first, verify that GAMS is installed in your system\ngamsPath = which('gams');\nif isempty(gamsPath); error('OptForce: GAMS is not installed in your system. Please install GAMS.'); end;\n\n%name of the function to solve the optimization problem in GAMS\ngamsMustUFunction = 'findMustU.gms';\n%path of that function\npathGamsFunction = which(gamsMustUFunction);\nif isempty(pathGamsFunction); error(['optForce: ' gamsMustUFunction ' not in MATLAB path.']); end;\n%current path\nworkingPath = pwd;\n%go to the path associate to the ID for this run.\nif ~isdir(runID); mkdir(runID); end; cd(runID);\n\n% if the user wants to generate a report.\nif printReport\n %create name for file.\n hour = clock;\n reportFileName = ['report-' date '-' num2str(hour(4)) 'h' '-' num2str(hour(5)) 'm.txt'];\n freport = fopen(reportFileName, 'w');\n reportClosed = 0;\n % print date of running.\n fprintf(freport, ['findMustUWithGAMS.m executed on ' date ' at ' num2str(hour(4)) ':' num2str(hour(5)) '\\n\\n']);\n % print matlab version.\n fprintf(freport, ['MATLAB: Release R' version('-release') '\\n']);\n % print gams version.\n fprintf(freport, ['GAMS: ' regexprep(gamsPath, '\\\\', '\\\\\\') '\\n']);\n % print solver used in GAMS to solve optForce.\n fprintf(freport, ['GAMS solver: ' solverName '\\n']);\n\n %print each of the inputs used in this running.\n fprintf(freport, '\\nThe following inputs were used to run OptForce: \\n');\n fprintf(freport, '\\n------INPUTS------\\n');\n %print model.\n fprintf(freport, '\\nModel:\\n');\n for i = 1:length(model.rxns)\n rxn = printRxnFormula(model, model.rxns{i}, false);\n fprintf(freport, [model.rxns{i} ': ' rxn{1} '\\n']);\n end\n %print lower and upper bounds, minimum and maximum values for each of\n %the reactions in wild-type and mutant strain\n fprintf(freport, '\\nLB\\tUB\\tMin_WT\\tMax_WT\\n');\n for i = 1:length(model.rxns)\n fprintf(freport, '%6.4f\\t%6.4f\\t%6.4f\\t%6.4f\\n', model.lb(i), model.ub(i), minFluxesW(i), maxFluxesW(i));\n end\n\n %print constraints\n fprintf(freport,'\\nConstrained reactions:\\n');\n for i = 1:length(constrOpt.rxnList)\n fprintf(freport,'%s: fixed in %6.4f\\n', constrOpt.rxnList{i}, constrOpt.values(i));\n end\n\n fprintf(freport,'\\nrunID(Main Folder): %s \\n\\noutputFolder: %s \\n\\noutputFileName: %s \\n',...\n runID, outputFolder, outputFileName);\n\n\n fprintf(freport,'\\nprintExcel: %1.0f \\n\\nprintText: %1.0f \\n\\nprintReport: %1.0f \\n\\nkeepInputs: %1.0f \\n\\nkeepGamsOutputs: %1.0f \\n\\nverbose: %1.0f \\n',...\n printExcel, printText, printReport, keepInputs, keepGamsOutputs, verbose);\n\nend\n\ncopyfile(pathGamsFunction);\n\n% export inputs for running the optimization problem in GAMS to find the\n% MustU Set\ninputFolder = 'InputsMustU';\nexportInputsMustToGAMS(model, 'U', minFluxesW, maxFluxesW, constrOpt,inputFolder)\n\n% create a directory to save results if this don't exist\nif ~exist(outputFolder, 'dir')\n mkdir(outputFolder);\nend\n\n%run\nif verbose\n run = system(['gams ' gamsMustUFunction ' lo=3 --myroot=' inputFolder '/ --solverName=' solverName ' gdx=GtoMU']);\nelse\n run = system(['gams ' gamsMustUFunction ' --myroot=' inputFolder '/ --solverName=' solverName ' gdx=GtoMU']);\nend\n\nif printReport; fprintf(freport, '\\n------RESULTS------\\n'); end;\n\n%if user decide not to show inputs files for findMustU.gms\nif ~keepInputs; rmdir(inputFolder,'s'); end;\n\n%if findMustU.gms was executed correctly \"run\" should be 0\nif run == 0\n if printReport; fprintf(freport, '\\nGAMS was executed correctly\\n'); end;\n if verbose; fprintf('GAMS was executed correctly\\nSummary of information exported by GAMS:\\n'); end;\n %show GAMS report in MATLAB console\n if verbose; gdxWhos GtoMU; end;\n\n %if the problem was solved correctly, a variable named findMustU should be\n %inside of GtoMU. Otherwise, the wrong file is being read.\n try\n findMustU.name = 'findMustU';\n rgdx('GtoMU', findMustU);\n if printReport; fprintf(freport, '\\nGAMS variables were read by MATLAB correctly\\n'); end;\n if verbose; fprintf('GAMS variables were read by MATLAB correctly\\n'); end;\n\n %Using GDXMRW to read solutions found by findMustU.gms\n %extract must U set found by findMustU.gms\n must.name = 'must';\n must.compress = 'true';\n must = rgdx('GtoMU', must);\n uelsMust = must.uels{1};\n\n %if the set is not empty\n if ~isempty(uelsMust)\n if printReport; fprintf(freport, '\\na MustU set was found\\n'); end;\n if verbose; fprintf('a MustU set was found\\n'); end;\n mustUSet = uelsMust';\n %find position for reactions of the MustU set in model.rxns\n posMustU = cell2mat(arrayfun(@(x)find(strcmp(x, model.rxns)), mustUSet, 'UniformOutput', false))';\n\n %find values of fluxes achieved by each reaction in MustU set\n minFlux = zeros(size(mustUSet));\n maxFlux = zeros(size(mustUSet));\n\n %extract minimum values\n vmin.name = 'vmin';\n vmin.compress = 'true';\n vmin = rgdx('GtoMU', vmin);\n uels_vmin = vmin.uels{1};\n if ~isempty(uels_vmin)\n val_vmin = vmin.val(:,2);\n for i = 1:length(uels_vmin)\n pos = strcmp(mustUSet, uels_vmin{i});\n minFlux(pos == 1) = val_vmin(i);\n end\n end\n\n %extract miximum values\n vmax.name = 'vmax';\n vmax.compress = 'true';\n vmax = rgdx('GtoMU', vmax);\n uels_vmax = vmax.uels{1};\n if ~isempty(uels_vmax)\n val_vmax = vmax.val(:,2);\n for i = 1:length(uels_vmax)\n pos = strcmp(mustUSet, uels_vmax{i});\n maxFlux(pos == 1) = val_vmax(i);\n end\n end\n else\n if printReport; fprintf(freport, '\\na MustU set was not found\\n'); end;\n if verbose; fprintf('a MustU set was not found\\n'); end;\n end\n\n % print info into an excel file if required by the user\n if printExcel\n if ~isempty(mustUSet)\n currentFolder = pwd;\n cd(outputFolder);\n Info = [{'Reactions'},{'Min Flux in Wild-type strain'},{'Max Flux in Wild-type strain'},{'Min Flux in Mutant strain'},{'Max Flux in Mutant strain'}];\n Info = [Info; [mustUSet, num2cell(minFluxesW(posMustU)), num2cell(maxFluxesW(posMustU)), num2cell(minFlux) ,num2cell(maxFlux)]];\n xlswrite('MustU_Info', Info);\n xlswrite(outputFileName, mustUSet);\n cd(currentFolder);\n if verbose; fprintf(['MustU set was printed in ' outputFileName '.xls \\n']); end;\n if printReport; fprintf(freport, ['\\nMustU set was printed in ' outputFileName '.xls \\n']); end;\n else\n if verbose; fprintf('No mustU set was found. Therefore, no excel file was generated\\n'); end;\n if printReport; fprintf(freport, '\\nNo mustU set was found. Therefore, no excel file was generated\\n'); end;\n end\n end\n\n % print info into a plain text file if required by the user\n if printText\n if ~isempty(mustUSet)\n currentFolder = pwd;\n cd(outputFolder);\n f = fopen('MustU_Info.txt','w');\n fprintf(f, 'Reactions\\tMin Flux in Wild-type strain\\tMax Flux in Wild-type strain\\tMin Flux in Mutant strain\\tMax Flux in Mutant strain\\n');\n for i = 1:length(posMustU)\n fprintf(f, '%s\\t%4.4f\\t%4.4f\\t%4.4f\\t%4.4f\\n', mustUSet{i}, minFluxesW(posMustU(i)), maxFluxesW(posMustU(i)), minFlux(i), maxFlux(i));\n end\n fclose(f);\n f = fopen([outputFileName '.txt'], 'w');\n for i = 1:length(posMustU)\n fprintf(f, '%s\\n', mustUSet{i});\n end\n fclose(f);\n cd(currentFolder);\n if verbose; fprintf(['MustU set was printed in ' outputFileName '.txt \\n']); end;\n if printReport; fprintf(freport, ['\\nMustU set was printed in ' outputFileName '.txt \\n']); end;\n else\n if verbose; fprintf('No mustU set was found. Therefore, no excel file was generated\\n'); end;\n if printReport; fprintf(freport, '\\nNo mustU set was found. Therefore, no excel file was generated\\n'); end;\n end\n end\n\n %close file for saving report\n if printReport; fclose(freport); reportClosed = 1; end;\n if printReport; movefile(reportFileName, outputFolder); end;\n delete(gamsMustUFunction);\n\n %remove or move additional files that were generated during running\n if keepGamsOutputs\n if ~isdir(outputFolder); mkdir(outputFolder); end;\n movefile('GtoMU.gdx',outputFolder);\n movefile(regexprep(gamsMustUFunction, 'gms', 'lst'), outputFolder);\n else\n delete('GtoMU.gdx');\n delete(regexprep(gamsMustUFunction, 'gms', 'lst'));\n end\n\n %go back to the original path\n cd(workingPath);\n\n catch\n %GAMS variables were not read correctly by MATLAB\n if verbose; fprintf('GAMS variables were not read by MATLAB corretly\\n'); end;\n if printReport && ~reportClosed; fprintf(freport, '\\nGAMS variables were not read by MATLAB corretly\\n'); fclose(freport); end;\n cd(workingPath);\n error('OptForce: GAMS variables were not read by MATLAB corretly');\n end\nelse\n %if GAMS was not executed correcttly\n if printReport && ~reportClosed; fprintf(freport, '\\nGAMS was not executed correctly\\n'); fclose(freport); end;\n if verbose; fprintf('GAMS was not executed correctly\\n'); end;\n cd(workingPath);\n error('OptForce: GAMS was not executed correctly');\nend\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/design/optForceGAMS/findMustUWithGAMS.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7090191460821871, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.3186279819438283}} {"text": "function [s, cfg] = ft_statfun_indepsamplesT(cfg, dat, design)\n\n% FT_STATFUN_INDEPSAMPLEST calculates the independent samples T-statistic on the\n% biological data in dat (the dependent variable), using the information on the\n% independent variable (ivar) in design.\n%\n% Use this function by calling one of the high-level statistics functions as\n% [stat] = ft_timelockstatistics(cfg, timelock1, timelock2, ...)\n% [stat] = ft_freqstatistics(cfg, freq1, freq2, ...)\n% [stat] = ft_sourcestatistics(cfg, source1, source2, ...)\n% with the following configuration option\n% cfg.statistic = 'ft_statfun_indepsamplesT'\n%\n% Configuration options\n% cfg.computestat = 'yes' or 'no', calculate the statistic (default='yes')\n% cfg.computecritval = 'yes' or 'no', calculate the critical values of the test statistics (default='no')\n% cfg.computeprob = 'yes' or 'no', calculate the p-values (default='no')\n%\n% The following options are relevant if cfg.computecritval='yes' and/or\n% cfg.computeprob='yes'.\n% cfg.alpha = critical alpha-level of the statistical test (default=0.05)\n% cfg.tail = -1, 0, or 1, left, two-sided, or right (default=1)\n% cfg.tail in combination with cfg.computecritval='yes'\n% determines whether the critical value is computed at\n% quantile cfg.alpha (with cfg.tail=-1), at quantiles\n% cfg.alpha/2 and (1-cfg.alpha/2) (with cfg.tail=0), or at\n% quantile (1-cfg.alpha) (with cfg.tail=1).\n%\n% Design specification\n% cfg.ivar = row number of the design that contains the labels of the conditions that must be\n% compared (default=1). The labels are the numbers 1 and 2.\n%\n% See also FT_TIMELOCKSTATISTICS, FT_FREQSTATISTICS or FT_SOURCESTATISTICS\n\n% Copyright (C) 2006, Eric Maris\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% set the defaults\ncfg.computestat = ft_getopt(cfg, 'computestat', 'yes');\ncfg.computecritval = ft_getopt(cfg, 'computecritval', 'no');\ncfg.computeprob = ft_getopt(cfg, 'computeprob', 'no');\ncfg.alpha = ft_getopt(cfg, 'alpha', 0.05);\ncfg.tail = ft_getopt(cfg, 'tail', 1);\n\n% perform some checks on the configuration\nif strcmp(cfg.computeprob,'yes') && strcmp(cfg.computestat,'no')\n % probabilities can only be calculated if the test statistics are calculated\n cfg.computestat = 'yes';\nend\nif isfield(cfg,'uvar') && ~isempty(cfg.uvar)\n ft_error('cfg.uvar should not exist for an independent samples statistic');\nend\n\n% perform some checks on the design and data\nsel1 = design(cfg.ivar,:)==1;\nsel2 = design(cfg.ivar,:)==2;\nnreplc1 = sum(~isnan(dat(:,sel1)), 2);\nnreplc2 = sum(~isnan(dat(:,sel2)), 2);\nnrepl = nreplc1 + nreplc2;\nhasnans1 = any(nreplc1BUFLN\n tt_2=from-BUFLN;\nelse\n tt_2=0;\nend\naet=0;\n\nt1=8*sps;\nt1 = t1+from;\nT0 = 0;\nn=0;\nfor t = from:t1\n [temp,ebuf,lbuf,tt_2, aet] = slpsamp(t,data,BUFLN,ebuf,lbuf,tt_2, aet,SLPwindow);\n if temp > INVALID_DATA+10\n T0 = T0+temp;\n n=n+1;\n end\nend\nT0 = T0/n; % T0=T0/(t1-from);\nTa = 3 * T0;\n\nlearning=1;\n\n% /* Main loop */\nt = from;\nwhile t <= to\n \n if (learning) \n if (t > from + LPERIOD) \n \t\tlearning = 0;\n \tT1 = T0;\n t = from;\t% /* start over */\n else\n T1 = 2*T0;\n end\n end\n \n\t[temp,ebuf,lbuf,tt_2, aet] = slpsamp(t,data,BUFLN,ebuf,lbuf,tt_2, aet,SLPwindow);\n \n if (temp > T1) % /* found a possible ABP pulse near t */ \n\t timer = 0; \n % /* used for counting the time after previous ABP pulse */\n\t maxd = temp;\n mind = maxd;\n tmax=t;\n for (tt = t + 1: t + EyeClosing-1)\n [temp2 ,ebuf,lbuf,tt_2, aet] = slpsamp(tt,data,BUFLN,ebuf,lbuf,tt_2, aet,SLPwindow);\n if temp2 > maxd\n maxd=temp2;\n tmax=tt;\n end\n end\n if (maxd == temp)\n t=t+1;\n continue;\n end\n \n for tt = tmax :-1: (t - EyeClosing / 2 +1)\n [temp2 ,ebuf,lbuf,tt_2, aet] = slpsamp(tt,data,BUFLN,ebuf,lbuf,tt_2, aet,SLPwindow);\n if temp2< mind\n mind=temp2;\n end\n end\n if maxd>mind+10\n onset=(maxd-mind)/100+2;\n tpq=t-round(0.04*fs);\n maxmin_2_3_threshold=(maxd-mind)*2.0/3;\n for tt=tmax:-1:t-EyeClosing/2+1\n [temp2, ebuf,lbuf,tt_2, aet] = slpsamp(tt,data,BUFLN,ebuf,lbuf,tt_2, aet,SLPwindow);\n if temp2data(valley_i) && data(valley_i)<=data(valley_i-1) && data(valley_i)<=data(valley_i+1)\n valley_v=valley_i;\n end\n end\n \n \n if (~learning) \n \n % If we are looking for the first peak\n if beat_n == 1\n \n % If the proposed peak index > 0\n if round(valley_v) > 0\n ppgOnsets(beat_n) = round(valley_v);\n beat_n = beat_n + 1;\n end\n else\n % Check if rounded valley_v is greater than the prior beat index\n if round(valley_v) > ppgOnsets(beat_n-1)\n ppgOnsets(beat_n) = round(valley_v);\n beat_n = beat_n + 1;\n end\n end\n end\n \n\n % /* Adjust thresholds */\n Ta = Ta + (maxd - Ta)/10;\n T1 = Ta / 3;\n\n % /* Lock out further detections during the eye-closing period */\n t = tpq+EyeClosing;\n end\n else\n if (~learning) \n\t % /* Once past the learning period, decrease threshold if no pulse\n\t % was detected recently. */\n timer = timer+1;\n if (timer > ExpectPeriod && Ta > Tm) \n Ta=Ta-1;\n T1 = Ta / 3;\n end\n end\n end\n \n t=t+1;\n \nend\n\n% Discard first beat because algorithm always finds first minimum value, so trace-back logic\n% will find a fir\n\nend\n\n\nfunction [beat1,ebuf,lbuf,tt_2, aet] = slpsamp(t,data,BUFLN,ebuf,lbuf,tt_2, aet,SLPwindow) \n\n \n while (t > tt_2) \n prevVal=0;\n \n if (tt_2>0) && (tt_2-1>0) && (tt_2= MaxNumIter\n StopFlag = 1;\n Status = 'Maximum number of iterations is reached.';\n else\n StopFlag = 0;\n Status = [];\n end\n\n case 3\n if Nmap >= MaxNumMapEval\n StopFlag = 1;\n Status = 'Maximum number of mapping evaluations is reached.';\n else\n StopFlag = 0;\n Status = [];\n end\n\n case 4\n if T >= TimeLimit\n StopFlag = 1;\n Status = 'Time limit is reached.';\n else\n StopFlag = 0;\n Status = [];\n end\n\n case 5\n if (nfxk <= epsilon || Niter >= MaxNumIter)\n StopFlag = 1;\n if Niter < MaxNumIter\n Status = 'a solution is found.';\n else\n Status = 'Maximum number of iterations is reached.';\n end\n else\n StopFlag = 0;\n Status = [];\n end\n\nend\n\nend\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%% End of StopCritDuplo.m %%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/src/base/solvers/varKin/derFreeMethods/StopCritDuplo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632831725053, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.3176299335587884}} {"text": "function [rankFR, rankFRV, rankFRvanilla, rankFRVvanilla, model] = checkRankFR(model, printLevel)\n% Calculates the rank of `[F R]` and `[F; R]`, when restricted to certain\n% rows and columns\n%\n% USAGE:\n%\n% [rankFR, rankFRV, rankFRvanilla, rankFRVvanilla, model] = checkRankFR(model, printLevel)\n%\n% INPUTS:\n% model: model structure\n% printLevel: verbose level\n%\n% OUTPUTS:\n% rankFR: rank of [`F R`], when using only `FRrows`\n% rankFRV: rank of [`F; R`], when using only `FRVcols`\n% rankFRvanilla: rank of [`F R`], when using all rows\n% rankFRVvanilla: rank of [`F; R`], when using all cols\n% model: structure with fields:\n%\n% * .FRrows - `m x 1` boolean of rows of [`F R`] that are nonzero,\n% unique upto positive scaling and part of the\n% maximal conservation vector\n% * .FRVcols - `n x 1` boolean of cols of [`F; R`] that are nonzero,\n% unique upto positive scaling and part of the\n% maximal conservation vector\n% * .FRirows - `m x 1` boolean of rows of [`F R`] that are independent\n% * .FRdrows - `m x 1` boolean of rows of [`F R`] that are dependent\n% * .FRwrows - `m x 1` boolean of independent rows of [`F R`] that\n% have dependent rows amongst `model.FRdrows`\n% * .FRVdcols - `n x 1` boolean of cols of [`F; R`] that are dependent\n% * model.SConsistentMetBool - `m x 1` boolean vector indicating metabolites involved\n% in the maximal consistent vector\n% * .SConsistentRxnBool - `n x 1` boolean vector indicating metabolites involved\n% in the maximal consistent vector\n% * .FRnonZeroBool - `m x 1` boolean vector indicating metabolites involved\n% in at least one internal reaction\n% * .FRuniqueBool - `m x 1` boolean vector indicating metabolites with\n% reaction stoichiometry unique upto scalar multiplication\n% * .SIntRxnBool - `n x 1` boolean vector indicating the non exchange reactions\n% * .FRVnonZeroBool - `n x 1` boolean vector indicating non exchange reactions\n% with at least one metabolite involved\n% * .FRVuniqueBool - `n x 1` boolean vector indicating non exchange reactions\n% with stoichiometry unique upto scalar multiplication\n% * .connectedRowsFRBool - `m x 1` boolean vector indicating metabolites in connected rows of [`F R`]\n% * .connectedRowsFRVBool - `n x 1` boolean vector indicating complexes in connected columns of [`F; R`]\n% * .V - :math:`S V = 0`; :math:`1^T |V| > 1` for all flux consistent reactions\n\nif ~exist('printLevel','var')\n printLevel=1;\nend\n\n%scaling of stoichiometric matrix may be necessary when badly scaled, off\n%by default\nscaling='none';\n%scaling='gmscal';\n%scaling='minimumCoefficient';\nswitch scaling\n case 'minimumCoefficient'\n %rescale stoichiometric coefficients\n A=abs(model.S);\n minCoefficient=min(min(A(model.S~=0)));\n model.S=model.S*(1000/minCoefficient);\n model.lb=model.lb*(1000/minCoefficient);\n model.ub=model.ub*(1000/minCoefficient);\n case 'gmscal'\n %geometric mean scaling\n [cscale,rscale] = gmscal(model.S,0,0.9);\n\n % model.S =diag(rscale)*model.S*diag(cscale);\n % model.b =diag(rscale)*model.b;\n % model.lb=diag(cscale)*model.lb;\n % model.ub=diag(cscale)*model.ub;\n % model.c =diag(cscale)*model.c;\n\n % only scale columns\n model.S =model.S*diag(cscale);\n model.b =model.b;\n model.lb=diag(cscale)*model.lb;\n model.ub=diag(cscale)*model.ub;\n model.c =diag(cscale)*model.c;\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%vanilla forward and reverse half stoichiometric matrices\nF = -model.S;\nF(F<0) = 0;\nR = model.S;\nR(R<0) = 0;\n\n%vanilla ranks\n[rankFRvanilla,~,~] = getRankLUSOL([F R]);\n[rankFRVvanilla,~,~] = getRankLUSOL([F;R]);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n[nMet,nRxn]=size(model.S);\n\nif ~isfield(model,'SIntRxnBool') || ~isfield(model,'SIntMetBool')\n %finds the reactions in the model which export/import from the model\n %boundary i.e. mass unbalanced reactions\n %e.g. Exchange reactions\n % Demand reactions\n % Sink reactions\n model = findSExRxnInd(model);\nend\nmodel.SIntRxnBool_findSExRxnInd=model.SIntRxnBool;\n\n%mass and charge balance\nif isfield(model,'metFormulas')\n [massImbalance,imBalancedMass,imBalancedCharge,imBalancedRxnBool,Elements,missingFormulaeBool,balancedMetBool]...\n = checkMassChargeBalance(model,printLevel);\n model.balancedRxnBool=~imBalancedRxnBool;\n model.balancedMetBool=balancedMetBool;\n model.Elements=Elements;\n model.missingFormulaeBool=missingFormulaeBool;\n\n if nnz(model.missingFormulaeBool)0\n fprintf('%u%s\\n',nnz(~model.SIntRxnBool),' exchange reactions (imbalanced elementally, or involves a stoichiometrically inconsistent molecular species)')\n for i=1:nRxn\n if ~model.SIntRxnBool(i) && model.SIntRxnBool_findSExRxnInd(i)\n fprintf('%s%s\\n',model.rxns{i},': deemed an exchange reaction')\n end\n end\n fprintf('---------\\n')\nend\n\nif any(~model.SIntMetBool) & printLevel>0\n fprintf('%u%s\\n',nnz(~model.SIntMetBool),' rows of S only involved in exchange reactions')\n for i=1:nMet\n if ~model.SIntMetBool(i)\n fprintf('%s%s\\n',model.mets{i}',': deemed a molecular species only involved in exchange reactions')\n end\n end\n fprintf('---------\\n')\nend\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%metBool1=(model.SConsistentMetBool | ~model.SIntMetBool); %incorrect to\n%include mets that are only exchanged\nmetBool1=model.SConsistentMetBool;\nrxnBool1=(model.SConsistentRxnBool | ~model.SIntRxnBool);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%find rows that are not all zero when a subset of reactions omitted\nA1=[F(:,rxnBool1) R(:,rxnBool1)];\nmodel.FRnonZeroRowBool1 = any(A1,2);\n\n%find cols that are not all zero when a subset of metabolites omitted\nA1=[F(metBool1,:); R(metBool1,:)];\nmodel.FRnonZeroColBool1 = any(A1,1)';\n\n%only report for the consistent rows\nif any(~model.FRnonZeroRowBool1 & metBool1) & printLevel>0\n fprintf('%u%s\\n',nnz(~model.FRnonZeroRowBool1 & metBool1),' zero rows of [F,R]')\n for i=1:nMet\n if ~model.FRnonZeroRowBool1(i) && metBool1(i)\n fprintf('%s%s\\n',model.mets{i},': is a zero row of [F,R]')\n end\n end\n fprintf('\\n')\nend\n\n%only report for the consistent cols\nif any(~model.FRnonZeroColBool1 & rxnBool1) && 0\n fprintf('%u%s\\n',nnz(~model.FRnonZeroColBool1 & rxnBool1),' zero cols of consistent [F;R]')\n for i=1:nRxn\n if ~model.FRnonZeroColBool1(i) && rxnBool1(i)\n fprintf('%s%s\\n',model.rxns{i},': is a zero col of consistent [F;R]')\n end\n end\n fprintf('\\n')\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nA=[F,R];%depends on the direction of reaction\n\n%detect the rows of A that are identical upto scalar multiplication\n%divide each row by the sum of each row.\nsumA2 = sum(A,2);\nsumA2(sumA2==0) = 1;\nnormalA2 = diag(1./sumA2)*A;\n\n%get unique rows, but do not change the order\n% [C,IA,IC] = unique(A,'rows') also returns index vectors IA and IC such\n% that C = A(IA,:) and A = C(IC,:).\n[uniqueRowsA,IA,IC] = unique(normalA2,'rows','stable');\nmodel.FRuniqueRowBool=zeros(nMet,1);\nmodel.FRuniqueRowBool(IA)=1;\n\nif any(~model.FRuniqueRowBool & metBool1) & printLevel>0\n fprintf('%u%s\\n',nnz(~model.FRuniqueRowBool & metBool1),' non-unique rows of stoich consistent [F,R]')\n for i=1:nMet\n if ~model.FRuniqueRowBool(i) && metBool1(i)\n fprintf('%s%s\\n',model.mets{i},': not unique row of stoich consistent [F,R]')\n end\n end\n fprintf('\\n')\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nA=F+R;%invariant to direction of reaction\n\n%detect the cols of A that are identical upto scalar multiplication\n%divide each col by the sum of each row.\nsumA1 = sum(A,1);\nsumA1(sumA1==0) = 1;\nnormalA1 = A*diag(1./sumA1);\n\n%get unique cols, but do not change the order\n% [C,IA,IC] = unique(A,'rows') also returns index vectors IA and IC such\n% that C = A(IA,:) and A = C(IC,:).\n[uniqueColsA,IA,IC] = unique(normalA1','rows','stable');\nmodel.FRuniqueColBool=zeros(nRxn,1);\nmodel.FRuniqueColBool(IA)=1;\n\nif any(~model.FRuniqueColBool & rxnBool1) & printLevel>0\n fprintf('%u%s\\n',nnz(~model.FRuniqueColBool & rxnBool1),' non-unique cols of stoich consistent [F;R]')\n for i=1:nRxn\n if ~model.FRuniqueColBool(i) && rxnBool1(i)\n fprintf('%s%s\\n',model.rxns{i},': not unique col of stoich consistent [F;R]')\n end\n end\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nif printLevel>0\n fprintf('\\n%s\\n','Diagnostics on size of boolean vectors for rows:')\n fprintf('%s%u\\n','SIntMetBool: ',nnz(model.SIntMetBool))\n fprintf('%s%u\\n','SConsistentMetBool: ',nnz(model.SConsistentMetBool))\n fprintf('%s%u\\n','FRnonZeroRowBool1: ',nnz(model.FRnonZeroRowBool1))\n fprintf('%s%u\\n','FRuniqueRowBool: ',nnz(model.FRuniqueRowBool))\n\n fprintf('\\n%s\\n','Diagnostics on size of boolean vectors for cols:')\n fprintf('%s%u\\n','SIntRxnBool: ',nnz(model.SIntRxnBool))\n fprintf('%s%u\\n','SConsistentRxnBool: ',nnz(model.SConsistentRxnBool))\n fprintf('%s%u\\n','FRnonzeroColBool: ',nnz(model.FRnonZeroColBool1))\n fprintf('%s%u\\n','FRuniqueColBool: ',nnz(model.FRuniqueColBool))\n fprintf('\\n')\nend\n\nif ~isempty(find(strcmp(model.mets(~model.SConsistentMetBool),'h[c]')))\n warning('h[c] is one of the inconsistent molecules')\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nmetBool2=model.SConsistentMetBool & model.FRuniqueRowBool & model.FRnonZeroRowBool1;\n\n% rxnBool2=(model.SConsistentRxnBool | ~model.SIntRxnBool);\nrxnBool2=(model.SConsistentRxnBool | ~model.SIntRxnBool) & model.FRuniqueColBool;\n\n%the uniqueness check has to be done before flux consistency since some\n%models have a forward and backward reaction in separately, but these are\n%the same reaction when both considered reversible.\n\n%from the unique exchange reactions, and the subset of the unique non-exchange\n%reactions that form a matrix with stoichiometrically consistent rows,\n%check for reactions that are also flux consistent, with all reactions\n%reversible\nmodelRev.S = model.S(metBool2,rxnBool2);\n\n%infinite bounds may be necessary when stoichiometric matrix is badly\n%scaled, in that case the minimum flux required (epsilon) is set to 1, the\n%default lower and upper bounds are {-1000, 1000}, with epsilon getCobraSolverParams('LP', 'feasTol')*100,\n%as that is two orders of magnitude higher than the typical feasibility\n%tolerance for volation of mass balance constraints.\nfluxConsistencyBounds='aThousand';\nswitch fluxConsistencyBounds\n case 'aThousand'\n %use all reactions reversible\n modelRev.lb=-1000*ones(size(modelRev.S,2),1);\n modelRev.ub= 1000*ones(size(modelRev.S,2),1);\n epsilon = getCobraSolverParams('LP', 'feasTol')*100;\n case 'infinity'\n %use all reactions reversible\n modelRev.lb=-inf*ones(size(modelRev.S,2),1);\n modelRev.ub= inf*ones(size(modelRev.S,2),1);\n epsilon = 1;\n case 'reconstruction'\n %use reconstruction reactions\n modelRev.lb=model.lb(rxnBool2);\n modelRev.ub=model.ub(rxnBool2);\n epsilon = getCobraSolverParams('LP', 'feasTol')*100;\nend\nmodelRev.mets=model.mets(metBool2);\nmodelRev.rxns=model.rxns(rxnBool2);\n\n%fast consistency check code from Nikos Vlassis et al\nmodeFlag=1;\n[indFluxConsist,~,V0]=fastcc(modelRev,epsilon,printLevel-1,modeFlag);\nmodelRev.fluxConsistentRxnBool=false(size(modelRev.S,2),1);\nmodelRev.fluxConsistentRxnBool(indFluxConsist)=1;\n\n%build the vector the same size as the original S\nmodel.fluxConsistentRxnBool=false(nRxn,1);\n%assign the boolean state to the original size model\nmodel.fluxConsistentRxnBool(rxnBool2)=modelRev.fluxConsistentRxnBool;\n\n%pad out V0 to correspond to the original size of S\nmodel.V=sparse(nRxn,size(V0,2));\nmodel.V(rxnBool2,:)=V0;\n\n%check to make sure booleans are correct\nif nnz(model.SConsistentRxnBool & ~model.SIntRxnBool)~=0\n error('No exchange reaction should be stoichiometrically consistent')\nend\n\n%check to make sure that V in nullspace of S.\ntmp=norm(full(model.S(metBool2,model.SConsistentRxnBool & model.SIntRxnBool)*model.V(model.SConsistentRxnBool & model.SIntRxnBool,:)...\n + model.S(metBool2,~model.SIntRxnBool)*model.V(~model.SIntRxnBool,:)));\n%two extra digits spare\nif tmp>100*epsilon\n disp(tmp)\n error('Not flux consistent')\nend\n%create a stoichiometric matrix of perpetireactions only for\n%stoichiometrically and flux consistent part\nmodel.P=sparse(nMet,size(V0,2));\nmodel.P(metBool2,:)=model.S(metBool2,~model.SIntRxnBool)*model.V(~model.SIntRxnBool,:);\n\n% model.fluxConsistentRxnBool=true(nRxn,1);\n\n%rows corresponding to flux consistent reactions\nmodel.fluxConsistentMetBool = sum(model.S(:,model.fluxConsistentRxnBool)~=0,2)~=0;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%eliminate the metabolites and reactions that are stoichiometrically\n%inconsistent or flux inconsistent from further consideration, but keep the\n%flux consistent exchange reactions, also eliminate scalar multiples\nmetBool3=model.SConsistentMetBool & model.fluxConsistentMetBool & model.FRuniqueRowBool & model.FRnonZeroRowBool1;\nrxnBool3=(model.SConsistentRxnBool | ~model.SIntRxnBool) & model.FRuniqueColBool & model.fluxConsistentRxnBool;\n\n%find rows that are not all zero when a subset of reactions omitted\nA3=[F(:,rxnBool3) R(:,rxnBool3)];\nmodel.FRnonZeroRowBool = any(A3,2);\n\n%find cols that are not all zero when a subset of metabolites omitted\nA3=[F(metBool3,:); R(metBool3,:)];\nmodel.FRnonZeroColBool = any(A3,1)';\n\n%only report for the latest subset of rows\nif any(~model.FRnonZeroRowBool & metBool3) & printLevel>0\n fprintf('%u%s\\n',nnz(~model.FRnonZeroRowBool & metBool3),' zero rows of [F,R]')\n for i=1:nMet\n if ~model.FRnonZeroRowBool(i) && metBool3(i)\n fprintf('%s%s\\n',model.mets{i},': is a zero row of [F,R]')\n end\n end\n fprintf('\\n')\nend\n\n%only report for the latest subset of cols\nif any(~model.FRnonZeroColBool & rxnBool3) && 0\n fprintf('%u%s\\n',nnz(~model.FRnonZeroColBool & rxnBool3),' zero cols of consistent [F;R]')\n for i=1:nRxn\n if ~model.FRnonZeroColBool(i) && rxnBool3(i)\n fprintf('%s%s\\n',model.rxns{i},': is a zero col of consistent [F;R]')\n end\n end\n fprintf('\\n')\nend\n\n%pause(eps)\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% A4=F(:,rxnBool3)+R(:,rxnBool3);%invariant to direction of reaction\n%\n% %detect the cols of A that are identical upto scalar multiplication\n% %divide each col by the sum of each row.\n% sumA4 = sum(A4,1);\n% sumA4(sumA4==0) = 1;\n% normalA4 = A4*diag(1./sumA4);\n%\n% %get unique cols, but do not change the order\n% % [C,IA,IC] = unique(A,'rows') also returns index vectors IA and IC such\n% % that C = A(IA,:) and A = C(IC,:).\n% [uniqueColsA,IA,IC] = unique(normalA4','rows','stable');\n% model.FRuniqueColBool2=zeros(nRxn,1);\n% model.FRuniqueColBool2(IA)=1;\n%\n% if any(~model.FRuniqueColBool2 & rxnBool3)\n% fprintf('%u%s\\n',nnz(~model.FRuniqueColBool2 & rxnBool3),' non-unique cols of consistent [F;R]')\n% for i=1:nRxn\n% if ~model.FRuniqueColBool(i) && rxnBool1(i)\n% fprintf('%s%s\\n',model.rxns{i},': not unique col of consistent [F;R]')\n% end\n% end\n% end\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% The largest connected component - not necessary, flux consistency takes\n% care of this connected rows of [F,R] and columns of [F;R]\n% [model.connectedRowsFRBool,model.connectedColsFRVBool]=connectedFR(F,R);\n% [~,maxInd]=max(sum(model.connectedRowsFRBool,1));\n% model.largestConnectedRowsFRBool=model.connectedRowsFRBool(:,maxInd);\n% [~,maxInd]=max(sum(model.connectedColsFRVBool,1));\n% model.largestConnectedColsFRVBool=model.connectedColsFRVBool(:,maxInd);\n\n%bypass test for connectedness\nmodel.largestConnectedRowsFRBool=true(nMet,1);\nmodel.largestConnectedColsFRVBool=true(nRxn,1);\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%diagnostics\nif printLevel>0\n fprintf('\\n%s\\n','Diagnostics on size of boolean vectors for rows:')\n fprintf('%s%u\\n','SConsistentMetBool: ',nnz(model.SConsistentMetBool))\n fprintf('%s%u\\n','fluxConsistentMetBool: ',nnz(model.fluxConsistentMetBool))\n fprintf('%s%u\\n','FRuniqueRowBool: ',nnz(model.FRuniqueRowBool))\n fprintf('%s%u\\n','FRnonZeroRowBool1: ',nnz(model.FRnonZeroRowBool1))\n fprintf('%s%u\\n','FRnonZeroRowBool: ',nnz(model.FRnonZeroRowBool))\n % fprintf('%s%u\\n','largestConnectedRowsFRBool: ',nnz(model.largestConnectedRowsFRBool))\n\n fprintf('\\n%s\\n','Diagnostics on size of boolean vectors for cols:')\n fprintf('%s%u\\n','SIntRxnBool: ',nnz(model.SIntRxnBool))\n fprintf('%s%u\\n','SConsistentRxnBool: ',nnz(model.SConsistentRxnBool))\n fprintf('%s%u\\n','fluxConsistentRxnBool: ',nnz(model.fluxConsistentRxnBool))\n fprintf('%s%u\\n','FRuniqueColBool: ',nnz(model.FRuniqueColBool))\n fprintf('%s%u\\n','FRnonZeroColBool1: ',nnz(model.FRnonZeroColBool1))\n fprintf('%s%u\\n','FRnonZeroColBool: ',nnz(model.FRnonZeroColBool))\n %fprintf('%s%u\\n','largestConnectedColsFRVBool: ',nnz(model.largestConnectedColsFRVBool))\n fprintf('\\n')\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%only use rows that are nonzero, unique upto positive scaling, part of\n%the maximal conservation vector, and part of the largest component\nselection='c';\nswitch selection\n case 'a'\n model.FRrows = model.SConsistentMetBool...\n & model.fluxConsistentMetBool...\n & model.FRnonZeroRowBool...\n & model.FRuniqueRowBool;\n model.FRVcols = (model.SConsistentRxnBool | ~model.SIntRxnBool)...\n & model.fluxConsistentRxnBool...\n & model.FRuniqueColBool...\n & model.FRnonZeroColBool;\n case 'b'\n %exchange reactions not considered when rank([F,R]) measured\n model.FRrows = model.SConsistentMetBool...\n & model.fluxConsistentMetBool...\n & model.FRnonZeroRowBool...\n & model.FRuniqueRowBool;\n model.FRVcols = model.SConsistentRxnBool...\n & model.fluxConsistentRxnBool...\n & model.FRuniqueColBool...\n & model.FRnonZeroColBool;\n case 'c'\n model.FRrows = model.SConsistentMetBool...\n & model.fluxConsistentMetBool...\n & model.FRnonZeroRowBool1...\n & model.FRnonZeroRowBool...\n & model.FRuniqueRowBool;\n model.FRVcols = (model.SConsistentRxnBool | ~model.SIntRxnBool)...\n & model.fluxConsistentRxnBool...\n & model.FRuniqueColBool...\n & model.FRnonZeroColBool;\n case 'd'\n model.FRrows = model.SConsistentMetBool...\n & model.fluxConsistentMetBool...\n & model.FRnonZeroRowBool1...\n & model.FRnonZeroRowBool...\n & model.FRuniqueRowBool;\n model.FRVcols = (model.SConsistentRxnBool | ~model.SIntRxnBool)...\n & model.fluxConsistentRxnBool;\nend\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%omit both the rows and the columns as specified above\nFr = F(model.FRrows,model.FRVcols);\nRr = R(model.FRrows,model.FRVcols);\nFc = F(model.FRrows,model.FRVcols);\nRc = R(model.FRrows,model.FRVcols);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% method.interface='solveCobraLP';\n% method.solver='mosek';\n% method.param.MSK_IPAR_OPTIMIZER='MSK_OPTIMIZER_DUAL_SIMPLEX';\n\nmethod.interface='solveCobraLP';\nmethod.solver='gurobi5';\nmethod.param.Method=1;\n\nmodelCheck.S = Rr-Fr;\nmodelCheck.SIntRxnBool=model.SIntRxnBool;\nmodelCheck.SIntMetBool=model.SIntMetBool(model.FRrows);\n[informC,mC,~]=checkStoichiometricConsistency(modelCheck,0,method);\n%save check on consistency\nmodel.mC=mC;\nif informC~=1\n disp(length(mC)-nnz(mC))\n error('(R-F) not stoichiometrically consistent')\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% [A,B,C]=bilinearDecomposition(model.S(model.FRrows,model.FRVcols));\n% %forward and reverse half stoichiometric matrices\n% Fb = -B;\n% Fb(Fb<0) = 0;\n% Rb = B;\n% Rb(Rb<0) = 0;\n% Fb(Fb~=0) = 1;\n% Rb(Rb~=0) = 1;\n% adj = inc2adj([Fb Rb]);\n%\n% % Test whether a graph is bipartite, if yes, return the two vertex sets\n% % Inputs: graph in the form of adjancency list (neighbor list, see adj2adjL.m)\n% % Outputs: True/False (boolean), empty set (if False) or two sets of vertices\n% tic\n% [isit,partA,partB]=isbipartite(adj2adjL(adj));\n% toc\n% %pause(eps)\n\n\n%check rank of bilinear version\n[A,B,C]=bilinearDecomposition(Fr-Rr);\n%forward and reverse half stoichiometric matrices\nFrb = -B;\nFrb(Frb<0) = 0;\nRrb = B;\nRrb(Rrb<0) = 0;\n\n%rank of [F R]\n[rankBilinearFrRr,bilinearFrRrp,bilinearFrRrq] = getRankLUSOL([Frb Rrb]);\nmodel.Frb=Frb;\nmodel.Rrb=Rrb;\nmodel.rankBilinearFrRr=rankBilinearFrRr;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%rank of [F R]\n[rankFR,FRp,FRq] = getRankLUSOL([Fr Rr]);\n\n%indices of rows that are dependent\nind=find(model.FRrows);\niR=ind(FRp(1:rankFR));\ndR=ind(FRp(rankFR+1:length(FRp)));\nmodel.FRdrows=false(nMet,1);\nmodel.FRdrows(dR)=1;\nmodel.FRirows=false(nMet,1);\nmodel.FRirows(iR)=1;\nmodel.FRq=FRq;\nmodel.FRp=FRp;\nmodel.Fr=Fr;\nmodel.Rr=Rr;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%rank of [F;R]\n[rankFRV,FRVp,FRVq] = getRankLUSOL([Fc;Rc]);\n\n%boolean of non-exchange columns that are dependent\nvertInd=find(model.FRVcols);\niC=vertInd(FRVq(1:rankFRV));\ndC=vertInd(FRVq(rankFRV+1:length(FRVq)));\nmodel.FRVdcols=false(nRxn,1);\nmodel.FRVdcols(dC)=1;\nmodel.FRVicols=false(nRxn,1);\nmodel.FRVicols(iC)=1;\nmodel.FRVq=FRVq;\nmodel.FRVp=FRVp;\nmodel.Fc=Fc;\nmodel.Rc=Rc;\n\n%sanity check\nif nnz(model.FRrows) ~= nnz(model.FRrows & model.FRdrows)\n error('')\nend\nif nnz(model.FRVcols) ~= nnz(model.FRVcols & model.FRVdcols)\n error('')\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%examine the dependencies between rows and columns if any\nmodel.FRrowRankDeficiency=nnz(model.FRrows)-rankFR;\nif model.FRrowRankDeficiency>0\n T = [Fr Rr];\n %code from Michael\n C1 = T(FRp(1:rankFR),:);\n C2 = T(FRp(rankFR+1:length(FRp)),:);\n W0 = C1' \\ C2'; % solves LS problems min ||C1'*W_k - C2_k'||\n\n model.FRW=sparse(model.FRrowRankDeficiency,nMet);\n model.FRW(:,iR)=W0';%L\n model.FRW(:,dR)=-speye(model.FRrowRankDeficiency);\n\n %indices of independent rows that other rows are dependent on\n wR=find(sum(abs(model.FRW),1)>0)';\n model.FRwrows=false(nMet,1);\n model.FRwrows(wR)=1;\n\n %sanity checks\n disp(norm(C1'*W0 - C2',inf)) %should be zero\n disp(norm([W0',-speye(model.FRrowRankDeficiency)]*[C1;C2],inf)) %should be zero\n\n W = sparse(model.FRrowRankDeficiency,size([Fr Rr],1));\n W(:,FRp(1:rankFR))=W0';\n W(:,FRp(rankFR+1:length(FRp)))=-speye(model.FRrowRankDeficiency);\n disp(norm(W*[Fr Rr],inf)) %should be zero\n\n model.FRW=sparse(model.FRrowRankDeficiency,nMet);\n model.FRW(:,model.FRrows)=W;\n disp(norm(model.FRW*[F(:,model.FRVcols), R(:,model.FRVcols)],inf)) %should be zero\n %%%%% N B %%%%\n disp(norm(model.FRW*[F,R],inf)) % will not in general be zero as other columns of [F R] could contribute\n\n % nnz(W)\n % figure; spy(W)\n % figure; spy(abs(W) > 1e-3) % say\nend\n\nmodel.FRcolRankDeficiency=nnz(model.FRVcols)-rankFRV;\nif model.FRcolRankDeficiency>0\n VT = [Fc;Rc];\n %code from Michael\n VC1 = VT(:,model.FRVq(1:rankFRV)); % independent columns\n VC2 = VT(:,model.FRVq(rankFRV+1:size(VT,2))); % dependent columns\n VW0 = VC1 \\ VC2; % solves LS problems min ||VC1*WV_k - VC2_k||\n\n model.FRVW=sparse(nRxn,model.FRcolRankDeficiency);\n model.FRVW(iC,:)=VW0; % independent columns\n model.FRVW(dC,:)=-speye(model.FRcolRankDeficiency); % dependent columns\n\n %indices of independent cols that other cols are dependent on\n wC=find(sum(abs(model.FRVW),2)>0);\n model.FRVwcols=false(nRxn,1);\n model.FRVwcols(wC)=1;\n\n if printLevel>2\n %sanity check\n disp(norm([F(model.FRrows,:); R(model.FRrows,:)]*model.FRVW,inf))%should be zero\n %%%%% N B %%%%\n disp(norm([F;R]*model.FRVW,inf)) % will not in general be zero as other rows [F;R] could contribute\n end\n\n % nnz(VW0)\n % figure; spy(VW0)\n % figure; spy(abs(VW0) > 1e-3) % say\nend\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/src/analysis/topology/FR/checkRankFR.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.682573734412324, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.3173296017064914}} {"text": "function fem = update1320nbr(fem_struct,jj)\n% update1320nbr takes a node with connectivity between 13 and 20\n% and adds six new nodes and uses delanunay trianglulation to \n% create the new elements. The region is then sprung. An nei is\n% not required but if one is not present, it will be generated.\n%\n% Variables\n% fem_struct -- finite element structure from opnml.\n% jj -- the node number that has 12 elements connected to it.\n% fem -- the updated finite element structure.\n% Note: Only fem.x,fem.y,fem.z,fem.e, and fem.nei\n% get updated. fem.bnd does not need to be updated.\n%\n% Usage -- fem = update1320nbr(fem_struct,jj)\n%\n% FileName: update1320nbr.m\n% Written by: Ben Holladay (SEAP Student 2004)\n% Date: July 7,2004\n% Modified: August 30, 2004 -- Chris Massey\n% June 14,2005 -- Ben Holladay\n% Fix: Ensure that delaunay doesn't create elements\n% outside the patch.\n% Last Modifed: \n% Sept. 19, 2006 -- Chris Massey, NRL Code 7322, S.S.C. MS 39529\n% % Add test to make sure the correct nodal neighbor\n% connectivity existed for the requested update\n% July 14, 2008 -- Chris Massey, NRL Code 7322\n% moved test for 4 neighbors to after the test for nei.\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%Checks if the fem_struct has an nei. If not one is generated.\ntry\n nei = fem_struct.nei;\ncatch\n fem_struct.nei = ele2nei(fem_struct.e,fem_struct.x,fem_struct.y);\n nei = fem_struct.nei;\nend\n\ntempnc = sum(~ismember((fem_struct.nei(jj,:)),0));\nif (tempnc < 13 | tempnc > 20)\n error(['There are ',num2str(tempnc),' nodal neighbors for node number ',...\n num2str(jj),'. This routine only works for 13-20 nodal neighbors.']);\nend\n\n%Sets the intial fem_struct variables.\nx = fem_struct.x;\ny = fem_struct.y;\nz = fem_struct.z;\nenodes = fem_struct.e;\n\n%Adds new nodes,determines connectivity, and labels the bad node, \n%neighboring nodesm and neighboring elements.\nbadnode = jj;\n[nbrelem,~] = find(enodes == badnode);\n[nnodes,trnc] = size(nei);\ntemp1 = sum(ismember(nei(jj,:),0));\nnc = trnc - temp1;\nnbrnode = nei(badnode,1:nc);\nnewnode = nnodes + [1:6];\nvod = ([1:nc,1:nc]);\ninrad = max(sqrt((x(nbrnode)-x(badnode)).^2 + (y(nbrnode)-y(badnode)).^2));\n\n%Computes the center angle of each element.\nb2 = (x(nbrnode(:))-x(badnode)).^2 + (y(nbrnode(:))-y(badnode)).^2;\na2 = (x(nbrnode(:))-x(nbrnode([2:nc,1]))).^2 + (y(nbrnode(:))-y(nbrnode([2:nc,1]))).^2;\nA = (180/pi)*acos((b2+b2([2:nc,1])-a2)./(2*sqrt(b2).*sqrt(b2([2:nc,1]))));\nang = A;\n\n%Sets the patterns for how to add the nodes.\naddnode(1,:) = ([2,2,2,2,2,3]);\naddnode(2,:) = ([2,2,3,2,2,3]);\naddnode(3,:) = ([2,3,2,3,2,3]);\naddnode(4,:) = ([3,3,2,3,3,2]);\naddnode(5,:) = ([2,3,3,3,3,3]);\naddnode(6,:) = ([3,3,3,3,3,3]);\naddnode(7,:) = ([3,3,3,3,3,4]);\naddnode(8,:) = ([3,3,4,3,3,4]);\n\n%Determines the appropriate pattern for adding nodes\naddnodepat = addnode((nc - 12),:);\n\n%Labels reference nodes to be use to determine the new nodes locations.\nspb(1) = 1;\nspb(2) = spb(1) + addnodepat(1);\nspb(3) = spb(2) + addnodepat(2);\nspb(4) = spb(3) + addnodepat(3);\nspb(5) = spb(4) + addnodepat(4);\nspb(6) = spb(5) + addnodepat(5);\n\n%Determines the total angle that each node will cover.\ntestang(1) = sum([ang([spb(1):(spb(2)-1)])]);\ntestang(2) = sum([ang([spb(2):(spb(3)-1)])]);\ntestang(3) = sum([ang([spb(3):(spb(4)-1)])]);\ntestang(4) = sum([ang([spb(4):(spb(5)-1)])]);\ntestang(5) = sum([ang([spb(5):(spb(6)-1)])]);\ntestang(6) = sum([ang([spb(6):nc])]);\n\n%Test to make sure no node is trying to cover more than half of the \n%circle.\ntest = find(testang > 180);\nwhile ~isempty(test)\n hightemp = find(testang > 180);\n hhtempplus = hightemp + 1;\n if hhtempplus == 7; break; end\n spb(vod(hhtempplus)) = spb(vod(hhtempplus)) - 1;\n testang(1) = sum([ang([spb(1):(spb(2)-1)])]);\n testang(2) = sum([ang([spb(2):(spb(3)-1)])]);\n testang(3) = sum([ang([spb(3):(spb(4)-1)])]);\n testang(4) = sum([ang([spb(4):(spb(5)-1)])]);\n testang(5) = sum([ang([spb(5):(spb(6)-1)])]);\n testang(6) = sum([ang([spb(6):nc])]);\n test = find(testang > 180);\nend \n\n%First guess of the new coordinates and bathymetry.\nM(1,1) = sum(x([(nbrnode([spb(1):spb(2)])),badnode,badnode]));\nM(1,2) = sum(y([(nbrnode([spb(1):spb(2)])),badnode,badnode]));\nM(1,3) = sum(z([(nbrnode([spb(1):spb(2)])),badnode,badnode]));\n\nM(2,1) = sum(x([(nbrnode([spb(2):spb(3)])),badnode,badnode]));\nM(2,2) = sum(y([(nbrnode([spb(2):spb(3)])),badnode,badnode]));\nM(2,3) = sum(z([(nbrnode([spb(2):spb(3)])),badnode,badnode]));\n\nM(3,1) = sum(x([(nbrnode([spb(3):spb(4)])),badnode,badnode]));\nM(3,2) = sum(y([(nbrnode([spb(3):spb(4)])),badnode,badnode]));\nM(3,3) = sum(z([(nbrnode([spb(3):spb(4)])),badnode,badnode]));\n\nM(4,1) = sum(x([(nbrnode([spb(4):spb(5)])),badnode,badnode]));\nM(4,2) = sum(y([(nbrnode([spb(4):spb(5)])),badnode,badnode]));\nM(4,3) = sum(z([(nbrnode([spb(4):spb(5)])),badnode,badnode]));\n\nM(5,1) = sum(x([(nbrnode([spb(5):spb(6)])),badnode,badnode]));\nM(5,2) = sum(y([(nbrnode([spb(5):spb(6)])),badnode,badnode]));\nM(5,3) = sum(z([(nbrnode([spb(5):spb(6)])),badnode,badnode]));\n\nM(6,1) = sum(x([(nbrnode([spb(6):nc,1])),badnode,badnode]));\nM(6,2) = sum(y([(nbrnode([spb(6):nc,1])),badnode,badnode]));\nM(6,3) = sum(z([(nbrnode([spb(6):nc,1])),badnode,badnode]));\n\nM(7,1) = x(badnode);\nM(7,2) = y(badnode);\nM(7,3) = z(badnode);\n\nM(1,:) = M(1,:) ./ (addnodepat(1) + 3);\nM(2,:) = M(2,:) ./ (addnodepat(2) + 3);\nM(3,:) = M(3,:) ./ (addnodepat(3) + 3);\nM(4,:) = M(4,:) ./ (addnodepat(4) + 3);\nM(5,:) = M(5,:) ./ (addnodepat(5) + 3);\nM(6,:) = M(6,:) ./ (addnodepat(6) + 3);\n\nx([([newnode(1:6)]),badnode]) = ([M(:,1)]);\ny([([newnode(1:6)]),badnode]) = ([M(:,2)]);\nz([([newnode(1:6)]),badnode]) = ([M(:,3)]);\n\n%Uses delaunay trianglulation to created a new and updated element list.\ntempx = x([badnode,newnode(:)',nbrnode(:)']);\ntempy = y([badnode,newnode(:)',nbrnode(:)']);\ntri = delaunay(tempx,tempy);\ntri2 = tri;\n\n%Convertst the local element list from tri back to its global numberiing.\nfor i = 1:nc+7\n temp = find(i == tri);\n tmp = ([badnode,newnode(:)',nbrnode(:)']);\n tri2(temp) = tmp(i);\nend\n\n%Checks if the elements are in CCW order.\nxnodes = x(tri2);\nynodes = y(tri2);\ntemparea = 0.5*(xnodes(:,1).*(ynodes(:,2)-ynodes(:,3))+xnodes(:,2).*...\n (ynodes(:,3)-ynodes(:,1))+xnodes(:,3).*(ynodes(:,1)-ynodes(:,2)));\nItri = find(temparea < 0);\ntri3 = tri2;\ntri3(Itri,2) = tri2(Itri,3);\ntri3(Itri,3) = tri2(Itri,2);\n\n%Removes elements that would be created outside the patch. \n%!!MODIFICATION!!\noldbnd = detbndy(enodes(nbrelem,:));\nnewbnd = detbndy(tri3);\noldbnd = sort(oldbnd,2);\nnewbnd = sort(newbnd,2);\ntemp11 = find(ismember(newbnd,oldbnd,'rows') ~= 1);\nwhile isempty(temp11) == 0\n newbnd = detbndy(tri3);\n newbnd = sort(newbnd,2);\n temp11 = find(ismember(newbnd,oldbnd,'rows') ~= 1);\n temp12 = newbnd(temp11,:);\n for it = 1:size(temp12,1)\n [tr,tc] = find(tri3 == temp12(it,1) | tri3 == temp12(it,2));\n [ta,tb,tc] = unique(tr);\n temp13 = setdiff(1:length(tr),tb);\n temp14 = tr(temp13);\n tri3(temp14,:) = [];\n end\nend \n\n%Finds and throws out bad elements and adds new elements to the global list. \ntempa = setdiff(1:1:length(enodes),nbrelem);\nenodes = enodes(tempa,1:3);\nnelems = size(enodes,1);\ntri3r = size(tri3,1);\nenodes([(nelems + 1):(nelems + tri3r)],:) = tri3;\n\n%Springs the region.\nstoptol = 10e-8 * inrad;\ntol = stoptol + 10;\ni = 1;\nimax = 20;\nwhile i <= imax && tol > stoptol\n M2(7,1) = sum([M(2,1),M(1,1),M(3,1),M(5,1),M(4,1),M(6,1)]);\n M2(7,2) = sum([M(2,2),M(1,2),M(3,2),M(5,2),M(4,2),M(6,2)]);\n M2(7,3) = sum([M(2,3),M(1,3),M(3,3),M(5,3),M(4,3),M(6,3)]);\n\n [r1,c1] = find(enodes == newnode(1));\n nbr1 = unique(enodes(r1,:));\n temp1 = find(nbr1 == newnode(1));\n nbr1(temp1) = [];\n\tM2(1,1) = sum(x([nbr1]));\n M2(1,2) = sum(y([nbr1]));\n M2(1,3) = sum(z([nbr1]));\n \n [r2,c] = find(enodes == newnode(2));\n nbr2 = unique(enodes(r2,:));\n temp2 = find(nbr2 == newnode(2));\n nbr2(temp2) = [];\n\tM2(2,1) = sum(x([nbr2]));\n M2(2,2) = sum(y([nbr2]));\n M2(2,3) = sum(z([nbr2]));\n \n [r3,c3] = find(enodes == newnode(3));\n nbr3 = unique(enodes(r3,:));\n temp3 = find(nbr3 == newnode(3));\n nbr3(temp3) = [];\n\tM2(3,1) = sum(x([nbr3]));\n M2(3,2) = sum(y([nbr3]));\n M2(3,3) = sum(z([nbr3]));\n \n [r4,c4] = find(enodes == newnode(4));\n nbr4 = unique(enodes(r4,:));\n temp4 = find(nbr4 == newnode(4));\n nbr4(temp4) = [];\n\tM2(4,1) = sum(x([nbr4]));\n M2(4,2) = sum(y([nbr4]));\n M2(4,3) = sum(z([nbr4]));\n \n [r5,c5] = find(enodes == newnode(5));\n nbr5 = unique(enodes(r5,:));\n temp5 = find(nbr5 == newnode(5));\n nbr5(temp5) = [];\n\tM2(5,1) = sum(x([nbr5]));\n M2(5,2) = sum(y([nbr5]));\n M2(5,3) = sum(z([nbr5]));\n \n\t[r6,c6] = find(enodes == newnode(6));\n nbr6 = unique(enodes(r6,:));\n temp6 = find(nbr6 == newnode(6));\n nbr6(temp6) = [];\n\tM2(6,1) = sum(x([nbr6]));\n M2(6,2) = sum(y([nbr6]));\n M2(6,3) = sum(z([nbr6]));\n \n M2(1,:) = M2(1,:) ./ (size((nbr1),1));\n M2(2,:) = M2(2,:) ./ (size((nbr2),1));\n M2(3,:) = M2(3,:) ./ (size((nbr3),1));\n M2(4,:) = M2(4,:) ./ (size((nbr4),1));\n M2(5,:) = M2(5,:) ./ (size((nbr5),1));\n M2(6,:) = M2(6,:) ./ (size((nbr6),1));\n M2(7,:) = M2(7,:) ./ 6;\n \n\ttol = max(sqrt((M2(:,1)-M(:,1)).^2 + (M2(:,2)-M(:,2)).^2));\n \n M = M2;\n x([([newnode(1:6)]),badnode]) = ([M(:,1)]);\n y([([newnode(1:6)]),badnode]) = ([M(:,2)]);\n z([([newnode(1:6)]),badnode]) = ([M(:,3)]);\n i = i + 1;\nend \n\n%Updates the nei for the region.\ntempnode = ([newnode,badnode,nbrnode]);\ntempcount = size(tempnode,2);\nfor i = 1:tempcount \n [tr,tc] = find(tempnode(i) == enodes);\n tempnbr = unique(enodes(tr,:));\n tmp1 = find(tempnbr == tempnode(i));\n tempnbr(tmp1) = [];\n tempnbrx = x(tempnbr) - x(tempnode(i));\n tempnbry = y(tempnbr) - y(tempnode(i));\n angle = (atan2(tempnbry,tempnbrx))*(180/pi);\n tempang = find(angle < 0);\n angle(tempang) = angle(tempang) + 360;\n [tmp2,tempi] = sort(angle);\n tempnbr1 = tempnbr(tempi);\n tmpr = size(tempnbr,1);\n nei(tempnode(i),:) = ([tempnbr1(1:tmpr)',zeros(1,trnc-tmpr)]); \nend \n\n%Createst the output structure.\nfem = fem_struct;\nfem.x = x;\nfem.y = y;\nfem.z = z;\nfem.e = enodes;\nfem.nei = nei;\nreturn\n", "meta": {"author": "CHLNDDEV", "repo": "OceanMesh2D", "sha": "56222604a5c1fe897d10c8b08cb3380ef8b43740", "save_path": "github-repos/MATLAB/CHLNDDEV-OceanMesh2D", "path": "github-repos/MATLAB/CHLNDDEV-OceanMesh2D/OceanMesh2D-56222604a5c1fe897d10c8b08cb3380ef8b43740/utilities/Nodal_Reduce_Matlab_Codes/update1320nbr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.4649015713733884, "lm_q1q2_score": 0.3173296017064914}} {"text": "function [fx,tt]=fxrapt(s,fs,mode)\n%FXRAPT RAPT pitch tracker [FX,VUV]=(S,FS)\n%\n% Input: s(ns) Speech signal\n% fs Sample frequency (Hz)\n% mode 'g' will plot a graph [default if no output arguments]\n% 'u' will include unvoiced fames (with fx=NaN)\n%\n% Outputs: fx(nframe) Larynx frequency for each fram,e (or NaN for silent/unvoiced)\n% tt(nframe,3) Start and end samples of each frame. tt(*,3)=1 at the start of each talk spurt\n%\n% Plots a graph if no outputs are specified showing lag candidates and selected path\n%\n\n% Bugs/Suggestions:\n% (1) Include backward DP pass and output the true cost for each candidate.\n% (2) Add an extra state to distinguish between voiceless and silent\n% (3) N-best DP to allow longer term penalties (e.g. for frequent pitch doubling/halving)\n\n% The algorithm is taken from [1] with the following differences:\n%\n% (a) the factor AFACT which in the Talkin algorithm corresponds roughly\n% to the absolute level of harmonic noise in the correlation window. This value\n% is here calculated as the maximum of three figures:\n% (i) an absolute floor set by PP.rapt_absnoise\n% (ii) a multiple of the peak signal set by PP.rapt_signoise\n% (iii) a multiple of the noise floor set by PP.rapt_relnoise\n% (b) The LPC used in calculating the Itakura distance uses a Hamming window rather than\n% a Hanning window.\n%\n% A C implementation of this algorithm by Derek Lin and David Talkin is included as \"get_f0.c\"\n% in the esps.zip package available from http://www.speech.kth.se/esps/esps.zip under the BSD\n% license.\n%\n% Refs:\n% [1] D. Talkin, \"A Robust Algorithm for Pitch Tracking (RAPT)\"\n% in \"Speech Coding & Synthesis\", W B Kleijn, K K Paliwal eds,\n% Elsevier ISBN 0444821694, 1995\n\n% Copyright (C) Mike Brookes 2006\n% Version: $Id: fxrapt.m 3601 2013-10-11 15:27:30Z 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\ns=s(:); % force s to be a column\nif nargin<3\n mode=' ';\nend\ndoback=0; % don't do backwards DP for now\n\n% read in parameters\n\nPP=voicebox;\nf0min=PP.rapt_f0min; % Min F0 (Hz) [50]\nf0max=PP.rapt_f0max; % Max F0 (Hz) [500]\ntframe=PP.rapt_tframe; % frame size (s) [0.01]\ntlpw=PP.rapt_tlpw; % low pass filter window size (s) [0.005]\ntcorw=PP.rapt_tcorw; % correlation window size (s) [0.0075]\ncandtr=PP.rapt_candtr; % minimum peak in NCCF [0.3]\nlagwt=PP.rapt_lagwt; % linear lag taper factor [0.3]\nfreqwt=PP.rapt_freqwt; % cost factor for F0 change [0.02]\nvtranc=PP.rapt_vtranc; % fixed voice-state transition cost [0.005]\nvtrac=PP.rapt_vtrac; % delta amplitude modulated transition cost [0.5]\nvtrsc=PP.rapt_vtrsc; % delta spectrum modulated transition cost [0.5]\nvobias=PP.rapt_vobias; % bias to encourage voiced hypotheses [0.0]\ndoublec=PP.rapt_doublec; % cost of exact doubling or halving [0.35]\nabsnoise=PP.rapt_absnoise; % absolute rms noise level [0]\nrelnoise=PP.rapt_relnoise; % rms noise level relative to noise floor [2.0]\nsignoise=PP.rapt_signoise; % ratio of peak signal rms to noise floor [0.001]\nncands=PP.rapt_ncands; % max hypotheses at each frame [20]\ntrms=PP.rapt_trms; % window length for rms measurement [0.03]\ndtrms=PP.rapt_dtrms; % window spacing for rms measurement [0.02]\npreemph=PP.rapt_preemph; % s-plane position of preemphasis zero [-7000]\nnfullag=PP.rapt_nfullag; % number of full lags to try (must be odd) [7]\n\n% derived parameters (mostly dependent on sample rate fs)\n\nkrms=round(trms*fs); % window length for rms measurement\nkdrms=round(dtrms*fs); % window spacing for rms measurement\nrmswin=hanning(krms).^2;\nkdsmp=round(0.25*fs/f0max);\nhlpw=round(tlpw*fs/2); % force window to be an odd length\nblp=sinc((-hlpw:hlpw)/kdsmp).*hamming(2*hlpw+1).';\nfsd=fs/kdsmp;\nkframed=round(fsd*tframe); % downsampled frame length\nkframe=kframed*kdsmp; % frame increment at full rate\nrmsix=(1:krms)+floor((kdrms-kframe)/2); % rms index according to Talkin; better=(1:krms)+floor((kdrms-krms+1)/2)\nminlag=ceil(fsd/f0max);\nmaxlag=round(fsd/f0min); % use round() only because that is what Talkin does\nkcorwd=round(fsd*tcorw); % downsampled correlation window\nkcorw=kcorwd*kdsmp; % full rate correlation window\nspoff=max(hlpw-floor(kdsmp/2),1+kdrms-rmsix(1)-kframe); % offset for first speech frame at full rate\nsfoff=spoff-hlpw+floor(kdsmp/2); % offset for downsampling filter\nsfi=1:kcorwd; % initial decimated correlation window index array\nsfhi=1:kcorw; % initial correlation window index array\nsfj=1:kcorwd+maxlag;\nsfmi=repmat((minlag:maxlag)',1,kcorwd)+repmat(sfi,maxlag-minlag+1,1);\nlagoff=(minlag-1)*kdsmp; % lag offset when converting to high sample rate\nbeta=lagwt*f0min/fs; % bias towards low lags\nlog2=log(2);\nlpcord=2+round(fs/1000); % lpc order for itakura distance\nhnfullag=floor(nfullag/2);\njumprat=exp((doublec+log2)/2); % lag ratio at which octave jump cost is lowest\nssq=s.^2;\ncsssq=cumsum(ssq);\nsqrt(min(csssq(kcorw+1:end)-csssq(1:end-kcorw))/kcorw);\nafact=max([absnoise^2,max(ssq)*signoise^2,min(csssq(kcorw+1:end)-csssq(1:end-kcorw))*(relnoise/kcorw)^2])^2*kcorw^2;\n\n% downsample signal to approx 2 kHz to speed up autocorrelation calculation\n% kdsmp is the downsample factor\n\nsf=filter(blp/sum(blp),1,s(sfoff+1:end));\nsp=filter([1 exp(preemph/fs)],1,s); % preemphasised speech for LPC calculation\nsf(1:length(blp)-1)=[]; % remove startup transient\nsf=sf(1:kdsmp:end); % downsample to =~2kHz\nnsf=length(sf); % length of downsampled speech\nns=length(s); % length of full rate speech\n\n% Calculate the frame limit to ensure we don't run off the end of the speech or decimated speech:\n% (a) For decimated autocorrelation when calculating sff(): (nframe-1)*kframed+kcorwd+maxlag <= nsf\n% (b) For full rate autocorrelation when calculating sfh(): max(fho)+kcorw+maxlag*kdsamp+hnfllag <= ns\n% (c) For rms ratio window when calculating rr : max(fho)+rmsix(end) <= ns\n% where max(fho) = (nframe-1)*kframe + spoff\n\nnframe=floor(1+min((nsf-kcorwd-maxlag)/kframed,(ns-spoff-max(kcorw-maxlag*kdsmp-hnfullag,rmsix(end)))/kframe));\n\n% now search for autocorrelation peaks in the downsampled signal\n\ncost=zeros(nframe,ncands); % cumulative cost\nprev=zeros(nframe,ncands); % traceback pointer\nmcands=zeros(nframe,1); % number of actual candidates excluding voiceless\nlagval=repmat(NaN,nframe,ncands-1); % lag of each voiced candidate\ntv=zeros(nframe,3); % diagnostics: 1=voiceless cost, 2=min voiced cost, 3:cumulative voiceless-min voiced\nif doback\n costms=cell(nframe,1);\nend\n\n% Main processing loop for each 10 ms frame\n\nfor iframe=1:nframe % loop for each frame (~10 ms)\n\n % Find peaks in the normalized autocorrelation of subsampled (2Khz) speech\n % only keep peaks that are > 30% of highest peak\n\n fho=(iframe-1)*kframe+spoff;\n sff=sf((iframe-1)*kframed+sfj);\n sffdc=mean(sff(sfi)); % mean of initial correlation window length\n sff=sff-sffdc; % subtract off the mean\n nccfd=normxcor(sff(1:kcorwd),sff(minlag+1:end));\n [ipkd,vpkd]=v_findpeaks(nccfd,'q');\n\n % Debugging: execute the line below to plot the autocorrelation peaks.\n % v_findpeaks(nccfd,'q'); xlabel(sprintf('Lag = (x+%d)*%g ms',minlag-1,1000*kdsmp/fs)); ylabel('Normalized Cross Correlation'); title (sprintf('Frame %d/%d',iframe,nframe));\n\n vipkd=[vpkd ipkd];\n vipkd(vpkdncands-1\n vipkd=sortrows(vipkd);\n vipkd(1:size(vipkd,1)-ncands+1,:)=[]; % eliminate lowest to leave only ncands-1\n end\n lagcan=round(vipkd(:,2)*kdsmp+lagoff); % convert the lag candidate values to the full sample rate\n nlcan=length(lagcan);\n else\n nlcan=0;\n end\n\n % If there are any candidate lag values (nlcan>0) then refine their accuracy at the full sample rate\n\n if nlcan\n laglist=reshape(repmat(lagcan(:)',nfullag,1)+repmat((-hnfullag:hnfullag)',1,nlcan),nfullag*nlcan,1);\n sfh=s(fho+(1:kcorw+max(lagcan)+hnfullag));\n sfhdc=mean(sfh(sfhi));\n sfh=sfh-sfhdc;\n e0=sum(sfh(sfhi).^2); % energy of initial correlation window (only needed to store in tv(:,6)\n lagl2=repmat(lagcan(:)',nfullag+kcorw-1,1)+repmat((1-hnfullag:hnfullag+kcorw)',1,nlcan);\n nccf=normxcor(sfh(1:kcorw),sfh(lagl2),afact);\n\n [maxcc,maxcci]=max(nccf,[],1);\n vipk=[maxcc(:) lagcan(:)+maxcci(:)-hnfullag-1];\n vipk=vipk(:,[1 2 2]);\n maxccj=maxcci(:)'+nfullag*(0:nlcan-1); % vector index into nccf array\n msk=mod(maxcci,nfullag-1)~=1 & 2*nccf(maxccj)-nccf(mod(maxccj-2,nfullag*nlcan)+1)-nccf(mod(maxccj,nfullag*nlcan)+1)>0; % don't do quadratic interpolation for the end ones\n if any(msk)\n maxccj=maxccj(msk);\n vipk(msk,3)=vipk(msk,3)+(nccf(maxccj+1)-nccf(maxccj-1))'./(2*(2*nccf(maxccj)-nccf(maxccj-1)-nccf(maxccj+1)))';\n end\n vipk(maxccncands-1\n vipk=sortrows(vipk);\n vipk(1:size(vipk,1)-ncands+1,:)=[]; % eliminate lowest to leave only ncands-1\n end\n\n % vipk(:,1) has NCCF value, vipk(:,2) has integer peak position, vipk(:,3) has refined peak position\n\n mc=size(vipk,1);\n else\n mc=0;\n end\n\n % We now have mc lag candidates at the full sample rate\n\n mc1=mc+1; % total number of candidates including \"unvoiced\" possibility\n mcands(iframe)=mc; % save number of lag candidates (needed for pitch consistency cost calculation)\n if mc\n lagval(iframe,1:mc)=vipk(:,3)';\n cost(iframe,1)=vobias+max(vipk(:,1)); % voiceless cost\n cost(iframe,2:mc1)=1-vipk(:,1)'.*(1-beta*vipk(:,3)'); % local voiced costs\n tv(iframe,2)=min(cost(iframe,2:mc1));\n else\n cost(iframe,1)=vobias; % if no lag candidates (mc=0), then the voiceless case is the only possibility\n end\n tv(iframe,1)=cost(iframe,1);\n if iframe>1 % if it is not the first frame, then calculate pitch consistency and v/uv transition costs\n mcp=mcands(iframe-1);\n costm=zeros(mcp+1,mc1); % cost matrix: rows and cols correspond to candidates in previous and current frames (incl voiceless)\n\n % if both frames have at least one lag candidate, then calculate a pitch consistency cost\n\n if mc*mcp\n lrat=abs(log(repmat(lagval(iframe,1:mc),mcp,1)./repmat(lagval(iframe-1,1:mcp)',1,mc)));\n costm(2:end,2:end)=freqwt*min(lrat,doublec+abs(lrat-log2)); % allow pitch doubling/halving\n end\n\n % if either frame has a lag candidate, then calculate the cost of voiced/voiceless transition and vice versa\n\n if mc+mcp\n rr=sqrt((rmswin'*s(fho+rmsix).^2)/(rmswin'*s(fho+rmsix-kdrms).^2)); % amplitude \"gradient\"\n ss=0.2/(distitar(lpcauto(sp(fho+rmsix),lpcord),lpcauto(sp(fho+rmsix-kdrms),lpcord),'e')-0.8); % Spectral stationarity: note: Talkin uses Hanning instead of Hamming windows for LPC\n costm(1,2:end)= vtranc+vtrsc*ss+vtrac/rr; % voiceless -> voiced cost\n costm(2:end,1)= vtranc+vtrsc*ss+vtrac*rr;\n tv(iframe,4:5)=[costm(1,mc1) costm(mcp+1,1)];\n end\n costm=costm+repmat(cost(iframe-1,1:mcp+1)',1,mc1); % add in cumulative costs\n [costi,previ]=min(costm,[],1);\n cost(iframe,1:mc1)=cost(iframe,1:mc1)+costi;\n prev(iframe,1:mc1)=previ;\n else % first ever frame\n costm=zeros(1,mc1); % create a cost matrix in case doing a backward recursion\n end\n if mc\n tv(iframe,3)=cost(iframe,1)-min(cost(iframe,2:mc1));\n tv(iframe,6)=5*log10(e0*e0/afact);\n end\n if doback\n costms{iframe}=costm; % need to add repmatted cost into this\n end\nend\n\n% now do traceback\n\nbest=zeros(nframe,1);\n[cbest,best(nframe)]=min(cost(nframe,1:mcands(nframe)+1));\nfor i=nframe:-1:2\n best(i-1)=prev(i,best(i));\nend\nvix=find(best>1);\nfx=repmat(NaN,nframe,1); % unvoiced frames will be NaN\nfx(vix)=fs*lagval(vix+nframe*(best(vix)-2)).^(-1); % leave as NaN if unvoiced\ntt=zeros(nframe,3);\ntt(:,1)=(1:nframe)'*kframe+spoff; % find frame times\ntt(:,2)=tt(:,1)+kframe-1;\njratm=(jumprat+1/jumprat)/2;\ntt(2:end,3)=abs(fx(2:end)./fx(1:end-1)-jratm)>jumprat-jratm; % new spurt if frequency ratio is outside (1/jumprat,jumprat)\ntt(1,3)=1; % first frame always starts a spurt\ntt(1+find(isnan(fx(1:end-1))),3)=1; % NaN always forces a new spurt\n\n% plot results if there are no output arguments of if the 'g' mode option is specified\n\nif ~nargout || any(mode=='g')\n tf=spoff+(0:nframe-1)'*kframe; % one sample before start of each frame\n blag=repmat(NaN,nframe,1); % unvoiced frames will be NaN\n blag(vix)=lagval(vix+nframe*(best(vix)-2)); % leave as NaN if unvoiced\n ts=(1:ns)/fs; % time scale for speech samples\n tsa=[1:tf(1) tf(end)+kframe+1:ns]; % indexes for unprocessed speech [-1 term is an error methinks]\n sup=repmat(NaN,ns,1); % unprocessed speech - plot in black\n sup(tsa)=s(tsa);\n sv=reshape(s(tf(1)+1:tf(end)+kframe),kframe,nframe); % processed speech\n su=sv;\n su(:,best>1)=NaN; % delete all voiced samples\n sv(:,best==1)=NaN; % delete all unvoiced samples\n tsuv=(tf(1)+1:tf(end)+kframe)/fs;\n su=su(:);\n sv=sv(:);\n ax=zeros(2,1);\n ax(1)=subplot(211);\n plot(ts,sup,'-k',tsuv,su,'r-',tsuv,sv,'b-');\n title('Speech');\n ax(2)=subplot(212);\n plot((tf+(kframe+1)/2)/fs,lagval*1000/fs,'xr',(tf+(kframe+1)/2)/fs,blag*1000/fs,'-b')\n xlabel('Time (s)');\n ylabel('Period (ms)');\n title('Lag Candidates');\n linkaxes(ax,'x');\nend\nif ~any(mode=='u')\ntt(isnan(fx),:)=[]; % remove NaN spurts\nfx(isnan(fx),:)=[];\nend\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction v=normxcor(x,y,d)\n% Calculate the normalized cross correlation of column vectors x and y\n% we can calculate this in two ways but fft is much faster even for nx small\n% We must have nx<=ny and the output length is ny-nx+1\n% note that this routine does not do mean subtraction even though this is normally a good idea\n% if y is a matrix, we correlate with each column\n% d is a constant added onto the normalization factor\n% v(j)=x'*yj/sqrt(d + x'*x * yj'*yj) where yj=y(j:j+nx-1) for j=1:ny-nx+1\n\nif nargin<3\n d=0;\nend\nnx=length(x);\n[ny,my]=size(y);\nnv=1+ny-nx;\nif nx>ny\n error('second argument is shorter than the first');\nend\n\nnf=pow2(nextpow2(ny));\nw=irfft(repmat(conj(rfft(x,nf,1)),1,my).*rfft(y,nf,1));\ns=zeros(ny+1,my);\ns(2:end,:)=cumsum(y.^2,1);\nv=w(1:nv,:)./sqrt(d+(x'*x).*(s(nx+1:end,:)-s(1:end-nx,:)));", "meta": {"author": "covarep", "repo": "covarep", "sha": "5a2be5d6b776f14a0b275c69fde90eb13849e60d", "save_path": "github-repos/MATLAB/covarep-covarep", "path": "github-repos/MATLAB/covarep-covarep/covarep-5a2be5d6b776f14a0b275c69fde90eb13849e60d/external/voicebox/fxrapt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6548947425132314, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.317217970571113}} {"text": "function [ly] = ft2ly(ft)\n% Convert length from feet to light years.\n% Chad A. Greene 2012\nly = ft*3.221738542107e-17;", "meta": {"author": "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/ft2ly.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7371581510799253, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.31708662417547206}} {"text": "function [Eft, Covft, ljpyt, Eyt, Covyt] = gpia_jpred(gp_array, x, y, varargin)\n%GPIA_JPRED Prediction with Gaussian Process GP_IA solution.\n%\n% Description\n% [EFT, COVFT] = GPIA_JPRED(GP_ARRAY, X, Y, XT, OPTIONS) \n% takes a cell array of GP structures together with matrix X of\n% training inputs and vector Y of training targets, and\n% evaluates the predictive distribution at test inputs XT with\n% parameters marginalized out with IA. Returns a posterior mean\n% EFT and covariance COVFT of latent variables.\n%\n% [EFT, COVFT, JPYT, EYT, COVYT] = GPIA_JPRED(GP, X, Y, XT, 'yt', YT, ...)\n% returns also logarithm of the predictive joint density PYT of\n% the observations YT at test input locations XT with parameters\n% marginalized out with IA. This can be used for example in the\n% cross-validation. Here Y has to be vector. Returns also\n% posterior predictive mean EYT and covariance COVYT.\n%\n% [EF, COVF, LJPY, EY, COVY] = GPIA_JPRED(GP, X, Y, OPTIONS)\n% evaluates the predictive distribution at training inputs X\n% and logarithm of the joint predictive density JPY of the training\n% observations Y.\n% \n% OPTIONS is optional parameter-value pair\n% predcf - index vector telling which covariance functions are \n% used for prediction. Default is all (1:gpcfn). See\n% additional information below.\n% tstind - a vector/cell array defining, which rows of X belong \n% to which training block in *IC type sparse models. \n% Deafult is []. In case of PIC, a cell array\n% containing index vectors specifying the blocking\n% structure for test data. IN FIC and CS+FIC a vector\n% of length n that points out the test inputs that\n% are also in the training set (if none, set TSTIND=[])\n% yt - optional observed yt in test points (see below)\n% z - optional observed quantity in triplet (x_i,y_i,z_i)\n% Some likelihoods may use this. For example, in case\n% of Poisson likelihood we have z_i=E_i, that is,\n% expected value for ith case.\n% zt - optional observed quantity in triplet (xt_i,yt_i,zt_i)\n% Some likelihoods may use this. For example, in case\n% of Poisson likelihood we have z_i=E_i, that is, the\n% expected value for the ith case.\n% \n% NOTE! In case of FIC and PIC sparse approximation the\n% prediction for only some PREDCF covariance functions is just\n% an approximation since the covariance functions are coupled in\n% the approximation and are not strictly speaking additive\n% anymore.\n%\n% For example, if you use covariance such as K = K1 + K2 your\n% predictions Eft1 = gpia_pred(gp_array, X, Y, X, 'predcf', 1) and\n% Eft2 = gpia_pred(gp_array, x, y, x, 'predcf', 2) should sum up to\n% Eft = gpia_pred(gp_array, x, y, x). That is Eft = Eft1 + Eft2. With\n% FULL model this is true but with FIC and PIC this is true only\n% approximately. That is Eft \\approx Eft1 + Eft2.\n%\n% With CS+FIC the predictions are exact if the PREDCF covariance\n% functions are all in the FIC part or if they are CS\n% covariances.\n%\n% NOTE! When making predictions with a subset of covariance\n% functions with FIC approximation the predictive variance can\n% in some cases be ill-behaved i.e. negative or unrealistically\n% small. This may happen because of the approximative nature of\n% the prediction.\n%\n% See also\n% GP_PRED, GP_SET, GP_IA\n%\n% Copyright (c) 2009 Ville Pietil�inen\n% Copyright (c) 2009-2010 Jarno Vanhatalo \n% Copyright (c) 2011-2012 Ville Tolvanen\n% Copyright (c) 2012 Aki Vehtari\n\n% This software is distributed under the GNU General Public \n% Licence (version 3 or later); please refer to the file \n% Licence.txt, included with the software, for details. \n\n \n ip=inputParser;\n ip.FunctionName = 'GPIA_JPRED';\n ip.addRequired('gp_array', @iscell);\n ip.addRequired('x', @(x) ~isempty(x) && isreal(x) && all(isfinite(x(:))))\n ip.addRequired('y', @(x) ~isempty(x) && isreal(x) && all(isfinite(x(:))))\n ip.addOptional('xt', [], @(x) isempty(x) || (isreal(x) && all(isfinite(x(:)))))\n ip.addParamValue('yt', [], @(x) isreal(x) && all(isfinite(x(:))))\n ip.addParamValue('z', [], @(x) isreal(x) && all(isfinite(x(:))))\n ip.addParamValue('zt', [], @(x) isreal(x) && all(isfinite(x(:))))\n ip.addParamValue('predcf', [], @(x) isempty(x) || ...\n isvector(x) && isreal(x) && all(isfinite(x)&x>0))\n ip.addParamValue('tstind', [], @(x) isempty(x) || iscell(x) ||...\n (isvector(x) && isreal(x) && all(isfinite(x)&x>0)))\n if numel(varargin)==0 || isnumeric(varargin{1})\n % inputParser should handle this, but it doesn't\n ip.parse(gp_array, x, y, varargin{:});\n else\n ip.parse(gp_array, x, y, [], varargin{:});\n end\n xt=ip.Results.xt;\n yt=ip.Results.yt;\n z=ip.Results.z;\n zt=ip.Results.zt;\n predcf=ip.Results.predcf;\n tstind=ip.Results.tstind;\n if isempty(xt)\n xt=x;\n if isempty(tstind)\n if iscell(gp_array)\n gptype=gp_array{1}.type;\n else\n gptype=gp_array.type;\n end\n switch gptype\n case {'FULL' 'VAR' 'DTC' 'SOR'}\n tstind = [];\n case {'FIC' 'CS+FIC'}\n tstind = 1:size(x,1);\n case 'PIC'\n if iscell(gp)\n tstind = gp_array{1}.tr_index;\n else\n tstind = gp_array.tr_index;\n end\n end\n end\n if isempty(yt)\n yt=y;\n end\n if isempty(zt)\n zt=z;\n end\n end\n \n % pass these forward\n options=struct();\n if ~isempty(yt);options.yt=yt;end\n if ~isempty(z);options.z=z;end\n if ~isempty(zt);options.zt=zt;end\n if ~isempty(predcf);options.predcf=predcf;end\n if ~isempty(tstind);options.tstind=tstind;end\n \n if nargout > 2 && isempty(yt)\n pyt = NaN;\n end\n \n nGP = numel(gp_array);\n\n % Make predictions with different models in gp_array\n for i1=1:nGP\n P_TH(:,i1) = gp_array{i1}.ia_weight;\n if nargout <= 2\n [Efts(:,i1), Covfts(:,:,i1)]=gp_jpred(gp_array{i1},x,y,xt,options); \n else\n [Efts(:,i1), Covfts(:,:,i1), ljpyts(i1), Eyts(:,i1), Covyts(:,:,i1)]=gp_jpred(gp_array{i1},x,y,xt, options);\n end\n end\n\n % Calculate mean and variance of the distributions\n Eft = sum(bsxfun(@times,Efts,P_TH), 2);\n % Calculate covariances of means\n Efts = bsxfun(@minus,Efts,Eft);\n for i1=1:nGP\n CovEfts(:,:,i1)=Efts(:,i1)'*Efts(:,2);\n end\n % Covariance is E(Cov)+Cov(E)\n Covft = squeeze(sum(bsxfun(@times, Covfts, permute(P_TH,[1 3 2])), 3)) ...\n + sum(bsxfun(@times, CovEfts, permute(P_TH,[1 3 2])), 3);\n \n % Calculate jpyt with weight given in P_TH.\n if nargout > 2\n if isempty(yt)\n ljpyt = [];\n else\n ljpyt = log(sum(exp(ljpyts)'.*P_TH));\n end\n end\n \n if nargout > 3\n Eyt = sum(bsxfun(@times,Eyts,P_TH),2);\n Covyt = squeeze(sum(bsxfun(@times, Covyts, permute(P_TH,[1 3 2])), 3)) ...\n + diag(sum(bsxfun(@times,bsxfun(@minus,Eyts,Eyt).^2, P_TH),2));\n end\n", "meta": {"author": "gpstuff-dev", "repo": "gpstuff", "sha": "114937ec0a201306489a66cbba38283e722fb998", "save_path": "github-repos/MATLAB/gpstuff-dev-gpstuff", "path": "github-repos/MATLAB/gpstuff-dev-gpstuff/gpstuff-114937ec0a201306489a66cbba38283e722fb998/gp/gpia_jpred.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6442251201477016, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.3170799608700028}} {"text": "function [MCI] = spm_mci_mfx_dynamic (MCI)\n% Mixed Effects Inference for Dynamical Systems\n% FORMAT [MCI] = spm_mci_mfx_dynamic (MCI)\n%\n% MCI Data structure containing fields:\n%\n% .M{n} Model for nth of N replications (e.g. subjects)\n% .U{n} Inputs for nth replication\n% .Y{n} Data for nth replication\n% .fixed Gaussian prior (.pE and .pC) over FFX\n% .S Second level model describing population mean, m, and \n% precision, Lambda. The parameters in S.prior\n% define the sufficient statistics of p(Lambda) (.a and .B)\n% and p(m|Lambda) (.beta and.m)\n% .total_its Total number of samples per subject\n% .rinit Proportion of samples to collect prior to use of\n% Empirical (group) prior\n% .verbose Show progress of optimisation\n%\n% KNOWN, FIXED or RANDOM EFFECTS:\n% The initial states, flow and output \n% parameters can be fixed or random effects or take on known values:\n%\n% .assign.init_par 'fixed', 'random' or 'known'\n% .assign.flow_par 'fixed', 'random' or 'known'\n% .assign.out_par 'fixed', 'random' or 'known'\n%\n% .pinit0 Initial values of initial state parameters\n% [Ninit x 1] for fixed, [Ninit x N] for random\n% .pflow0 Initial values of flow parameters\n% [Nflow x 1] for fixed, [Nflow x N] for random\n% .pout0 Initial values of output parameters\n% [Nout x 1] for fixed, [Nout x N] for random\n%\n% .update_obs_noise Update observation noise, Gamma ? [yes/no] (1/0), default=1\n% .verbose Show progress of optimisation \n%\n% The output fields are: \n%\n% POSTERIOR SAMPLES:\n% .sv [Nv x Nsamples] group fixed effects samples, v\n% .sm [Nw x Nsamples] group random effect means, m\n% .sw [Nw x N x Nsamples] subject random effects, w\n% .Ce [Ny x Ny x Nsamples] Obs noise covariance samples\n% .postind Indices for posterior (ie. excluding burn-in)\n%\n% POSTERIOR MEANS:\n% .sv_mean [Nv x 1] posterior mean over v\n% .sm_mean [Nw x 1] posterior mean over m\n% .sw_mean [Nw x N] posterior mean over w\n%\n% For Dynamical Systems models:\n% .pinit Estimated initial states\n% .pflow Estimated flow\n% .pout Estimated output params\n%\n% SUFFICIENT STATISTICS:\n% .noise Parameters of p(Gamma|Y,w,v): .c0,.D0,.cN,.DN\n% .S.post Parameters of p(Lambda|w) (.a and.B) \n% and p(m|Lambda,w) (.beta and .m)\n%\n% W.Penny, M Klein-Flugge and B Sengupta (2015) Mixed Effects Langevin\n% Monte Carlo, Submitted, 2015.\n%__________________________________________________________________________\n% Copyright (C) 2015 Wellcome Trust Centre for Neuroimaging\n\n% Will Penny \n% $Id: spm_mci_mfx_dynamic.m 6697 2016-01-27 14:57:28Z spm $\n\ntry, verbose=MCI.verbose; catch, verbose=0; end\n\n% Update observation noise ?\ntry, update_obs_noise=MCI.update_obs_noise; catch, update_obs_noise=1; end\n\n% Numbers of iterations, with and without group model\ntry, total_its=MCI.total_its; catch, total_its=1024; end\ntry, rinit=MCI.rinit; catch, rinit=0.25; end\nrfx_its=2;\nmfx_its=(1-rinit)*total_its/rfx_its;\nrfx1_its=rinit*total_its;\n\ntry, ffx_its=MCI.ffx_its; catch, ffx_its=4; end\ntry, ffx1_its=MCI.ffx1_its; catch, ffx1_its=64; end\n\nM=MCI.M;U=MCI.U;Y=MCI.Y;\nNp=length(spm_vec(M{1}.pE));\nif isfield(M{1},'x0')\n % For dynamical systems\n d=size(M{1}.x0,1);\nend\n\n% Observation noise\nNy=size(Y{1}.y,2);\nnoise.c0=Ny;\nnoise.D0=eye(Ny);\n \n% Prior over fixed effects\ntry\n fixed=MCI.fixed;\n fixed.vpE=spm_vec(fixed.pE); % m_v (vector)\ncatch\n fixed=[];\nend\n \n% Prior over random effects (second level model)\ntry\n S=MCI.S;\n Nrand=S.prior.a;\ncatch\n if strcmp(MCI.assign.init_par,'random')\n Nrand=d;\n else\n Nrand=0;\n end\n if strcmp(MCI.assign.flow_par,'random')\n Nrand=Nrand+M{1}.Npflow;\n end\n if strcmp(MCI.assign.out_par,'random')\n Nrand=Nrand+M{1}.Npout;\n end\n S.prior.P=Nrand;\n S.prior.a=Nrand/2;\n S.prior.B=eye(Nrand);\n S.prior.beta=1;\n S.prior.m=zeros(Nrand,1);\n S.N=length(M);\nend\n% Prior mean and cov of random effects from second level model\nm=S.prior.m;\nC=S.prior.B/S.prior.a;\nrfx_prior.pE=m;\nrfx_prior.pC=C;\nMCI.S=S;\n\n% Initialise fixed and random effects\n[w_init,v_init,assign,update_ffx,update_rfx] = spm_mci_vw_init (MCI);\n\n% Sampling params\nfixed_mcmc.assign=assign;\nsubj_mcmc.assign=assign;\nsubj_mcmc.verbose=0;\n\n% Set up sample matrix\nNfixed = length(v_init);\nif Nfixed > 0\n %v = zeros(mfx_its,Nfixed);\n for j=1:rfx1_its,\n v(j,:) = v_init';\n end\nend\nw = w_init;\n\n% Initialisation of each model\nsubj_mcmc.verbose=verbose;\nsubj_mcmc.maxits=rfx1_its;\nfor n=1:S.N,\n subj_mcmc.init=w(:,n);\n if rfx1_its > 0\n Psamp = spm_mci_random (subj_mcmc,rfx_prior,v_init,M{n},U{n},Y{n});\n sw(n,:,:) = Psamp;\n w(:,n) = Psamp(:,end);\n else\n sw(n,:,1) = w(:,n);\n end\nend\nsw=permute(sw,[2 1 3]);\nsm=squeeze(mean(sw,2));\nfor j=1:rfx1_its,\n Ce(:,:,j)=M{1}.Ce;\nend\nsubj_mcmc.maxits=rfx_its;\nsubj_mcmc.verbose=0;\n\n% Main Loop\nfor it=1:mfx_its\n \n if verbose\n disp(sprintf('MCI iteration %d',it));\n end\n \n if it>1 && Nrand > 0 \n % Update second level params\n S = spm_nwpost (S,w);\n [m,Lambda,C] = spm_nwrnd (S.post,1);\n end\n \n \n if update_ffx\n if verbose, disp('Updating fixed effects'); end\n % 2. Update estimate of group fixed effects\n \n % Start sampling where left off\n fixed_mcmc.init=v(it,:)';\n fixed_mcmc.update_obs_noise=update_obs_noise;\n \n if it==1\n fixed_mcmc.verbose=1;\n fixed_mcmc.maxits=ffx1_its;\n else\n fixed_mcmc.maxits=ffx_its;\n fixed_mcmc.verbose=0;\n end\n [Psamp,noise,M] = spm_mci_fixed (fixed_mcmc,w,fixed,noise,M,U,Y);\n P = Psamp(end,:);\n v(rfx1_its+it,:) = P;\n vit=P';\n else\n vit=[];\n end\n \n if update_rfx\n % Updated prior on random effects\n rfx_prior.pE=m;\n rfx_prior.pC=C;\n \n % 1. Update estimates of subject random effects \n if verbose, disp('Updating random effects'); end\n \n for n=1:S.N,\n if verbose\n disp(sprintf('Subject %d out of %d',n,S.N));\n end\n % Start sampling where left off\n subj_mcmc.init=w(:,n);\n Psamp = spm_mci_random (subj_mcmc,rfx_prior,vit,M{n},U{n},Y{n});\n w(:,n) = Psamp(:,end);\n end\n \n end\n \n % Update observation noise precision\n if update_obs_noise\n if verbose, disp('Updating observation noise precision'); end\n [noise,M] = spm_mci_obsnoise (w,vit,assign,noise,M,U,Y);\n end\n Ce(:,:,rfx1_its+it)=M{1}.Ce;\n \n % Store samples\n sm(:,rfx1_its+it)=m;\n sw(:,:,rfx1_its+it)=w;\n \nend\n\n% Define post burn-in\ntotal_its=size(sm,2); \nburn_in=round(0.3*total_its);\npost_ind=[burn_in+1:total_its];\n\n% Return samples\nMCI.sm=sm;\nMCI.sw=sw;\ntry, MCI.sv=v'; catch, MCI.sv=[]; end\n\n% Return posterior means\nif update_rfx\n MCI.sm_mean=mean(sm(:,post_ind),2);\n MCI.sw_mean=mean(sw(:,:,post_ind),3);\nend\ntry, MCI.sv_mean=mean(v(post_ind,:)); catch, MCI.sv_mean=[]; end\nMCI.post_ind=post_ind;\n\n% Extract posterior means for pinit, pflow, pout\nswitch assign.init_par,\n case 'fixed',\n MCI.pinit=MCI.sv_mean(:,assign.v_init)';\n case 'random',\n MCI.pinit_sub=MCI.sw_mean(assign.w_init,:);\n MCI.pinit=MCI.sm_mean(assign.w_init,:);\n otherwise\n try, MCI.pinit=MCI.pinit0; catch, MCI.pinit=[]; end\nend\nswitch assign.flow_par,\n case 'fixed',\n MCI.pflow=MCI.sv_mean(:,assign.v_flow)';\n case 'random',\n MCI.pflow_sub=MCI.sw_mean(assign.w_flow,:);\n MCI.pflow=MCI.sm_mean(assign.w_flow,:);\n otherwise\n try, MCI.pflow=MCI.flow0; catch, MCI.pflow=[]; end\nend\nswitch assign.out_par,\n case 'fixed',\n MCI.pout=MCI.sv_mean(:,assign.v_out)';\n case 'random',\n MCI.pout_sub=MCI.sw_mean(assign.w_out,:);\n MCI.pout=MCI.sm_mean(assign.w_out,:);\n otherwise\n try, MCI.pout=MCI.out0; catch, MCI.pout=[]; end\nend\n\nMCI.M=M;\nMCI.S=S;\nMCI.noise=noise;\nMCI.assign=assign;\nMCI.Ce=Ce;\n\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/toolbox/mci/inference/spm_mci_mfx_dynamic.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.3166320821070983}} {"text": "function [s, cfg] = ft_statfun_indepsamplesF(cfg, dat, design)\n\n% FT_STATFUN_INDEPSAMPLESF calculates the independent samples F-statistic on the\n% biological data in dat (the dependent variable), using the information on the\n% independent variable (ivar) in design.\n%\n% Use this function by calling one of the high-level statistics functions as\n% [stat] = ft_timelockstatistics(cfg, timelock1, timelock2, ...)\n% [stat] = ft_freqstatistics(cfg, freq1, freq2, ...)\n% [stat] = ft_sourcestatistics(cfg, source1, source2, ...)\n% with the following configuration option\n% cfg.statistic = 'ft_statfun_indepsamplesF'\n%\n% Configuration options\n% cfg.computestat = 'yes' or 'no', calculate the statistic (default='yes')\n% cfg.computecritval = 'yes' or 'no', calculate the critical values of the test statistics (default='no')\n% cfg.computeprob = 'yes' or 'no', calculate the p-values (default='no')\n%\n% The following options are relevant if cfg.computecritval='yes' and/or\n% cfg.computeprob='yes'.\n% cfg.alpha = critical alpha-level of the statistical test (default=0.05)\n% cfg.tail = -1, 0, or 1, left, two-sided, or right (default=1)\n% cfg.tail in combination with cfg.computecritval='yes'\n% determines whether the critical value is computed at\n% quantile cfg.alpha (with cfg.tail=-1), at quantiles\n% cfg.alpha/2 and (1-cfg.alpha/2) (with cfg.tail=0), or at\n% quantile (1-cfg.alpha) (with cfg.tail=1).\n%\n% Design specification\n% cfg.ivar = row number of the design that contains the labels of the conditions that must be \n% compared (default=1). The labels range from 1 to the number of conditions.\n%\n% See also FT_TIMELOCKSTATISTICS, FT_FREQSTATISTICS or FT_SOURCESTATISTICS\n\n% Copyright (C) 2006, Eric Maris\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% set the defaults\nif ~isfield(cfg, 'computestat'), cfg.computestat='yes'; end\nif ~isfield(cfg, 'computecritval'), cfg.computecritval='no'; end\nif ~isfield(cfg, 'computeprob'), cfg.computeprob='no'; end\nif ~isfield(cfg, 'alpha'), cfg.alpha=0.05; end\nif ~isfield(cfg, 'tail'), cfg.tail=1; end\n\n% perform some checks on the configuration\nif strcmp(cfg.computeprob,'yes') && strcmp(cfg.computestat,'no')\n ft_error('P-values can only be calculated if the test statistics are calculated.');\nend\nif isfield(cfg,'uvar') && ~isempty(cfg.uvar)\n ft_error('cfg.uvar should not exist for an independent samples statistic');\nend\n \nncond=length(unique(design(cfg.ivar,:)));\nnrepl=0;\nfor condindx=1:ncond\n nrepl=nrepl+length(find(design(cfg.ivar,:)==condindx));\nend\nif nrepl 8)\n corrector = 1; \n else\n corrector = 0; \n hRd = zeros(m,1);\n end \n hEinvRc = zeros(m,1); \n EinvRc = cell(size(blk,1),1); \n rhsfree = []; \n%%\n for p = 1:size(blk,1)\n pblk = blk(p,:); \n n = sum(pblk{2}); \n if strcmp(pblk{1},'l')\n\t if iscell(sigmu)\n EinvRc{p} = sigmu{p}./Z{p} -X{p};\n\t else\n EinvRc{p} = sigmu./Z{p} -X{p};\n end\n Rq = sparse(n,1); \n if (corrector) & (norm(par.parbarrier{p})==0)\n Rq = dX{p}.*dZ{p}./Z{p};\n else\n tmp = par.dd{p}.*Rd{p};\n tmp2 = mexMatvec(At{p},tmp,1);\n hRd = hRd + tmp2;\n end\n\t EinvRc{p} = EinvRc{p} - Rq; \n tmp2 = mexMatvec(At{p,1},EinvRc{p},1); \n hEinvRc = hEinvRc + tmp2;\n elseif strcmp(pblk{1},'q') \n\t if iscell(sigmu)\n EinvRc{p} = qops(pblk,sigmu{p},par.Zinv{p},3) -X{p};\n\t else\n EinvRc{p} = sigmu*par.Zinv{p} -X{p};\n end\n Rq = sparse(n,1); \n if (corrector) & (norm(par.parbarrier{p})==0)\n \t ff{p} = qops(pblk,1./par.gamz{p},Z{p},3);\n hdx = qops(pblk,par.gamz{p},ff{p},5,dX{p}); \n hdz = qops(pblk,par.gamz{p},ff{p},6,dZ{p}); \n hdxdz = Arrow(pblk,hdx,hdz);\n Rq = qops(pblk,par.gamz{p},ff{p},6,hdxdz); \n else\n tmp = par.dd{p}.*Rd{p} ...\n + qops(pblk,qops(pblk,Rd{p},par.Zinv{p},1),X{p},3) ...\n + qops(pblk,qops(pblk,Rd{p},X{p},1),par.Zinv{p},3); \n tmp2 = mexMatvec(At{p,1},tmp,1);\n hRd = hRd + tmp2;\n end\n\t EinvRc{p} = EinvRc{p} - Rq; \n tmp2 = mexMatvec(At{p,1},EinvRc{p},1); \n hEinvRc = hEinvRc + tmp2;\n elseif strcmp(pblk{1},'s') \n\t if iscell(sigmu)\t \n %%ss = [0,cumsum(pblk{2})]; \n %%sigmuvec = zeros(n,1); \n %%for k = 1:length(pblk{2}); \n %% sigmuvec(ss(k)+1:ss(k+1)) = sigmu{p}(k)*ones(pblk{2}(k),1); \n %%end\n sigmuvec = mexexpand(pblk{2},sigmu{p}); \n EinvRc{p} = par.Zinv{p}*spdiags(sigmuvec,0,n,n) -X{p};\n else\n EinvRc{p} = sigmu*par.Zinv{p} -X{p};\n end\n Rq = sparse(n,n);\n if (corrector) & (norm(par.parbarrier{p})==0)\n Rq = Prod3(pblk,dX{p},dZ{p},par.Zinv{p},0); \n\t Rq = 0.5*(Rq+Rq');\n else\n tmp = Prod3(pblk,X{p},Rd{p},par.Zinv{p},0,par.nzlistAy{p}); \n tmp = 0.5*(tmp+tmp'); \n tmp2 = AXfun(pblk,At(p,:),par.permA(p,:),{tmp}); \n hRd = hRd + tmp2;\n end \n\t EinvRc{p} = EinvRc{p} - Rq; \n tmp2 = AXfun(pblk,At(p,:),par.permA(p,:),EinvRc(p)); \n hEinvRc = hEinvRc + tmp2;\n elseif strcmp(pblk{1},'u') \n rhsfree = [rhsfree; Rd{p}]; \n end\n end\n%%\n rhs = rp + hRd - hEinvRc; \n rhs = full([rhs; rhsfree]); \n%%*******************************************************************\n", "meta": {"author": "yu-jiang", "repo": "radpbook", "sha": "88b9fa7d0a541099cdd1ac29383c89e087d1d895", "save_path": "github-repos/MATLAB/yu-jiang-radpbook", "path": "github-repos/MATLAB/yu-jiang-radpbook/radpbook-88b9fa7d0a541099cdd1ac29383c89e087d1d895/tools/SDPT3-4.0/SDPT3-4.0/Solver/HKMrhsfun.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.31598346654228304}} {"text": "function [elc, lab] = elec1020_locate(pnt, dhk, nas, ini, lpa, rpa, feedback)\n\n% ELEC1020_LOCATE determines 10-20 (20%, 10% and 5%) electrode positions\n% on a scalp surface that is described by its surface triangulation\n\n% Copyright (C) 2003, Robert Oostenveld\n%\n% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org\n% for the documentation and details.\n%\n% FieldTrip is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% FieldTrip is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with FieldTrip. If not, see .\n\nif nargin<7\n feedback = false;\nend\n\n\n% determine the approximate location of the vertex\nori = (lpa+rpa+nas+ini)/4; % center of head\nver = cross(rpa-lpa, nas-ini); % orientation\nver = ver /sqrt(norm(ver)); % make correct length\nver = ori + 0.7*ver; % location from center of head\n\nif feedback\n figure\n ft_plot_mesh(struct('pos', pnt, 'tri', dhk), 'edgecolor', 'none', 'facecolor', 'skin')\n lighting gouraud\n material dull\n lightangle(0, 90);\n alpha 0.9\n ft_plot_mesh(nas, 'vertexsize', 30)\n ft_plot_mesh(lpa, 'vertexsize', 30)\n ft_plot_mesh(ini, 'vertexsize', 30)\n ft_plot_mesh(rpa, 'vertexsize', 30)\n ft_plot_mesh(ver, 'vertexsize', 30)\n grid on\n hold on\n view([1 1 0.5])\nend\n\n\n% point near LPA that is at 50% of left lower contour\n[cnt1, cnt2] = elec1020_follow(pnt, dhk, nas, lpa, ini, feedback);\nmle = elec1020_fraction(cnt1, cnt2, 0.5);\n\n% point near RPA that is at 50% of right lower contour\n[cnt1, cnt2] = elec1020_follow(pnt, dhk, nas, rpa, ini, feedback);\nmre = elec1020_fraction(cnt1, cnt2, 0.5);\n\n% determine two points that approximate the vertex\n[cnt1, cnt2] = elec1020_follow(pnt, dhk, nas, ver, ini, feedback);\nver1 = elec1020_fraction(cnt1, cnt2, 0.5);\n[cnt1, cnt2] = elec1020_follow(pnt, dhk, mle, ver, mre, feedback);\nver2 = elec1020_fraction(cnt1, cnt2, 0.5);\n\n% refined estimate is the average of these two\nver = (ver1+ver2)/2;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% start contouring\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% ant-post contour through vertex\nfprintf('constructing vertical ant-post contour\\n');\n[cnt1, cnt2] = elec1020_follow(pnt, dhk, nas, ver, ini, feedback);\nNz = elec1020_fraction(cnt1, cnt2, 0/20);\nNFpz = elec1020_fraction(cnt1, cnt2, 1/20);\nFpz = elec1020_fraction(cnt1, cnt2, 2/20);\nAFpz = elec1020_fraction(cnt1, cnt2, 3/20);\nAFz = elec1020_fraction(cnt1, cnt2, 4/20);\nAFFz = elec1020_fraction(cnt1, cnt2, 5/20);\nFz = elec1020_fraction(cnt1, cnt2, 6/20);\nFFCz = elec1020_fraction(cnt1, cnt2, 7/20);\nFCz = elec1020_fraction(cnt1, cnt2, 8/20);\nFCCz = elec1020_fraction(cnt1, cnt2, 9/20);\nCz = elec1020_fraction(cnt1, cnt2, 10/20);\nCCPz = elec1020_fraction(cnt1, cnt2, 11/20);\nCPz = elec1020_fraction(cnt1, cnt2, 12/20);\nCPPz = elec1020_fraction(cnt1, cnt2, 13/20);\nPz = elec1020_fraction(cnt1, cnt2, 14/20);\nPPOz = elec1020_fraction(cnt1, cnt2, 15/20);\nPOz = elec1020_fraction(cnt1, cnt2, 16/20);\nPOOz = elec1020_fraction(cnt1, cnt2, 17/20);\nOz = elec1020_fraction(cnt1, cnt2, 18/20);\nOIz = elec1020_fraction(cnt1, cnt2, 19/20);\nIz = elec1020_fraction(cnt1, cnt2, 20/20);\n\n% left-right through vertex\nfprintf('constructing C contour\\n');\n[cnt1, cnt2] = elec1020_follow(pnt, dhk, mle, ver, mre, feedback);\nT9 = elec1020_fraction(cnt1, cnt2, 0/20);\nT9h = elec1020_fraction(cnt1, cnt2, 1/20);\nT7 = elec1020_fraction(cnt1, cnt2, 2/20);\nT7h = elec1020_fraction(cnt1, cnt2, 3/20);\nC5 = elec1020_fraction(cnt1, cnt2, 4/20);\nC5h = elec1020_fraction(cnt1, cnt2, 5/20);\nC3 = elec1020_fraction(cnt1, cnt2, 6/20);\nC3h = elec1020_fraction(cnt1, cnt2, 7/20);\nC1 = elec1020_fraction(cnt1, cnt2, 8/20);\nC1h = elec1020_fraction(cnt1, cnt2, 9/20);\nCz = elec1020_fraction(cnt1, cnt2, 10/20);\nC2h = elec1020_fraction(cnt1, cnt2, 11/20);\nC2 = elec1020_fraction(cnt1, cnt2, 12/20);\nC4h = elec1020_fraction(cnt1, cnt2, 13/20);\nC4 = elec1020_fraction(cnt1, cnt2, 14/20);\nC6h = elec1020_fraction(cnt1, cnt2, 15/20);\nC6 = elec1020_fraction(cnt1, cnt2, 16/20);\nT8h = elec1020_fraction(cnt1, cnt2, 17/20);\nT8 = elec1020_fraction(cnt1, cnt2, 18/20);\nT10h = elec1020_fraction(cnt1, cnt2, 19/20);\nT10 = elec1020_fraction(cnt1, cnt2, 20/20);\n\n% horizontal ant-post through T7\nfprintf('constructing horizontal left contour\\n');\n[cnt1, cnt2] = elec1020_follow(pnt, dhk, Fpz, T7, Oz, feedback);\nFp1h = elec1020_fraction(cnt1, cnt2, 1/20);\nFp1 = elec1020_fraction(cnt1, cnt2, 2/20);\nAFp7 = elec1020_fraction(cnt1, cnt2, 3/20);\nAF7 = elec1020_fraction(cnt1, cnt2, 4/20);\nAFF7 = elec1020_fraction(cnt1, cnt2, 5/20);\nF7 = elec1020_fraction(cnt1, cnt2, 6/20);\nFFT7 = elec1020_fraction(cnt1, cnt2, 7/20);\nFT7 = elec1020_fraction(cnt1, cnt2, 8/20);\nFTT7 = elec1020_fraction(cnt1, cnt2, 9/20);\nT7 = elec1020_fraction(cnt1, cnt2, 10/20);\nTTP7 = elec1020_fraction(cnt1, cnt2, 11/20);\nTP7 = elec1020_fraction(cnt1, cnt2, 12/20);\nTPP7 = elec1020_fraction(cnt1, cnt2, 13/20);\nP7 = elec1020_fraction(cnt1, cnt2, 14/20);\nPPO7 = elec1020_fraction(cnt1, cnt2, 15/20);\nPO7 = elec1020_fraction(cnt1, cnt2, 16/20);\nPOO7 = elec1020_fraction(cnt1, cnt2, 17/20);\nO1 = elec1020_fraction(cnt1, cnt2, 18/20);\nO1h = elec1020_fraction(cnt1, cnt2, 19/20);\n\n% horizontal ant-post through T8\nfprintf('constructing horizontal right contour\\n');\n[cnt1, cnt2] = elec1020_follow(pnt, dhk, Fpz, T8, Oz, feedback);\nFp2h = elec1020_fraction(cnt1, cnt2, 1/20);\nFp2 = elec1020_fraction(cnt1, cnt2, 2/20);\nAFp8 = elec1020_fraction(cnt1, cnt2, 3/20);\nAF8 = elec1020_fraction(cnt1, cnt2, 4/20);\nAFF8 = elec1020_fraction(cnt1, cnt2, 5/20);\nF8 = elec1020_fraction(cnt1, cnt2, 6/20);\nFFT8 = elec1020_fraction(cnt1, cnt2, 7/20);\nFT8 = elec1020_fraction(cnt1, cnt2, 8/20);\nFTT8 = elec1020_fraction(cnt1, cnt2, 9/20);\nT8 = elec1020_fraction(cnt1, cnt2, 10/20);\nTTP8 = elec1020_fraction(cnt1, cnt2, 11/20);\nTP8 = elec1020_fraction(cnt1, cnt2, 12/20);\nTPP8 = elec1020_fraction(cnt1, cnt2, 13/20);\nP8 = elec1020_fraction(cnt1, cnt2, 14/20);\nPPO8 = elec1020_fraction(cnt1, cnt2, 15/20);\nPO8 = elec1020_fraction(cnt1, cnt2, 16/20);\nPOO8 = elec1020_fraction(cnt1, cnt2, 17/20);\nO2 = elec1020_fraction(cnt1, cnt2, 18/20);\nO2h = elec1020_fraction(cnt1, cnt2, 19/20);\n\nfprintf('constructing AFp contour\\n');\n[cnt1, cnt2] = elec1020_follow(pnt, dhk, AFp7, AFpz, AFp8, feedback);\nAFp7h = elec1020_fraction(cnt1, cnt2, 1/16);\nAFp5 = elec1020_fraction(cnt1, cnt2, 2/16);\nAFp5h = elec1020_fraction(cnt1, cnt2, 3/16);\nAFp3 = elec1020_fraction(cnt1, cnt2, 4/16);\nAFp3h = elec1020_fraction(cnt1, cnt2, 5/16);\nAFp1 = elec1020_fraction(cnt1, cnt2, 6/16);\nAFp1h = elec1020_fraction(cnt1, cnt2, 7/16);\nAFp2h = elec1020_fraction(cnt1, cnt2, 9/16);\nAFp2 = elec1020_fraction(cnt1, cnt2, 10/16);\nAFp4h = elec1020_fraction(cnt1, cnt2, 11/16);\nAFp4 = elec1020_fraction(cnt1, cnt2, 12/16);\nAFp6h = elec1020_fraction(cnt1, cnt2, 13/16);\nAFp6 = elec1020_fraction(cnt1, cnt2, 14/16);\nAFp8h = elec1020_fraction(cnt1, cnt2, 15/16);\n\nfprintf('constructing AF contour\\n');\n[cnt1, cnt2] = elec1020_follow(pnt, dhk, AF7, AFz, AF8, feedback);\nAF7h = elec1020_fraction(cnt1, cnt2, 1/16);\nAF5 = elec1020_fraction(cnt1, cnt2, 2/16);\nAF5h = elec1020_fraction(cnt1, cnt2, 3/16);\nAF3 = elec1020_fraction(cnt1, cnt2, 4/16);\nAF3h = elec1020_fraction(cnt1, cnt2, 5/16);\nAF1 = elec1020_fraction(cnt1, cnt2, 6/16);\nAF1h = elec1020_fraction(cnt1, cnt2, 7/16);\nAF2h = elec1020_fraction(cnt1, cnt2, 9/16);\nAF2 = elec1020_fraction(cnt1, cnt2, 10/16);\nAF4h = elec1020_fraction(cnt1, cnt2, 11/16);\nAF4 = elec1020_fraction(cnt1, cnt2, 12/16);\nAF6h = elec1020_fraction(cnt1, cnt2, 13/16);\nAF6 = elec1020_fraction(cnt1, cnt2, 14/16);\nAF8h = elec1020_fraction(cnt1, cnt2, 15/16);\n\nfprintf('constructing AFF contour\\n');\n[cnt1, cnt2] = elec1020_follow(pnt, dhk, AFF7, AFFz, AFF8, feedback);\nAFF7h = elec1020_fraction(cnt1, cnt2, 1/16);\nAFF5 = elec1020_fraction(cnt1, cnt2, 2/16);\nAFF5h = elec1020_fraction(cnt1, cnt2, 3/16);\nAFF3 = elec1020_fraction(cnt1, cnt2, 4/16);\nAFF3h = elec1020_fraction(cnt1, cnt2, 5/16);\nAFF1 = elec1020_fraction(cnt1, cnt2, 6/16);\nAFF1h = elec1020_fraction(cnt1, cnt2, 7/16);\nAFF2h = elec1020_fraction(cnt1, cnt2, 9/16);\nAFF2 = elec1020_fraction(cnt1, cnt2, 10/16);\nAFF4h = elec1020_fraction(cnt1, cnt2, 11/16);\nAFF4 = elec1020_fraction(cnt1, cnt2, 12/16);\nAFF6h = elec1020_fraction(cnt1, cnt2, 13/16);\nAFF6 = elec1020_fraction(cnt1, cnt2, 14/16);\nAFF8h = elec1020_fraction(cnt1, cnt2, 15/16);\n\nfprintf('constructing F contour\\n');\n[cnt1, cnt2] = elec1020_follow(pnt, dhk, F7, Fz, F8, feedback);\nF7h = elec1020_fraction(cnt1, cnt2, 1/16);\nF5 = elec1020_fraction(cnt1, cnt2, 2/16);\nF5h = elec1020_fraction(cnt1, cnt2, 3/16);\nF3 = elec1020_fraction(cnt1, cnt2, 4/16);\nF3h = elec1020_fraction(cnt1, cnt2, 5/16);\nF1 = elec1020_fraction(cnt1, cnt2, 6/16);\nF1h = elec1020_fraction(cnt1, cnt2, 7/16);\nF2h = elec1020_fraction(cnt1, cnt2, 9/16);\nF2 = elec1020_fraction(cnt1, cnt2, 10/16);\nF4h = elec1020_fraction(cnt1, cnt2, 11/16);\nF4 = elec1020_fraction(cnt1, cnt2, 12/16);\nF6h = elec1020_fraction(cnt1, cnt2, 13/16);\nF6 = elec1020_fraction(cnt1, cnt2, 14/16);\nF8h = elec1020_fraction(cnt1, cnt2, 15/16);\n\nfprintf('constructing FFC contour\\n');\n[cnt1, cnt2] = elec1020_follow(pnt, dhk, FFT7, FFCz, FFT8, feedback);\nFFT7h = elec1020_fraction(cnt1, cnt2, 1/16);\nFFC5 = elec1020_fraction(cnt1, cnt2, 2/16);\nFFC5h = elec1020_fraction(cnt1, cnt2, 3/16);\nFFC3 = elec1020_fraction(cnt1, cnt2, 4/16);\nFFC3h = elec1020_fraction(cnt1, cnt2, 5/16);\nFFC1 = elec1020_fraction(cnt1, cnt2, 6/16);\nFFC1h = elec1020_fraction(cnt1, cnt2, 7/16);\nFFC2h = elec1020_fraction(cnt1, cnt2, 9/16);\nFFC2 = elec1020_fraction(cnt1, cnt2, 10/16);\nFFC4h = elec1020_fraction(cnt1, cnt2, 11/16);\nFFC4 = elec1020_fraction(cnt1, cnt2, 12/16);\nFFC6h = elec1020_fraction(cnt1, cnt2, 13/16);\nFFC6 = elec1020_fraction(cnt1, cnt2, 14/16);\nFFT8h = elec1020_fraction(cnt1, cnt2, 15/16);\n\nfprintf('constructing FC contour\\n');\n[cnt1, cnt2] = elec1020_follow(pnt, dhk, FT7, FCz, FT8, feedback);\nFT7h = elec1020_fraction(cnt1, cnt2, 1/16);\nFC5 = elec1020_fraction(cnt1, cnt2, 2/16);\nFC5h = elec1020_fraction(cnt1, cnt2, 3/16);\nFC3 = elec1020_fraction(cnt1, cnt2, 4/16);\nFC3h = elec1020_fraction(cnt1, cnt2, 5/16);\nFC1 = elec1020_fraction(cnt1, cnt2, 6/16);\nFC1h = elec1020_fraction(cnt1, cnt2, 7/16);\nFC2h = elec1020_fraction(cnt1, cnt2, 9/16);\nFC2 = elec1020_fraction(cnt1, cnt2, 10/16);\nFC4h = elec1020_fraction(cnt1, cnt2, 11/16);\nFC4 = elec1020_fraction(cnt1, cnt2, 12/16);\nFC6h = elec1020_fraction(cnt1, cnt2, 13/16);\nFC6 = elec1020_fraction(cnt1, cnt2, 14/16);\nFT8h = elec1020_fraction(cnt1, cnt2, 15/16);\n\nfprintf('constructing FCC contour\\n');\n[cnt1, cnt2] = elec1020_follow(pnt, dhk, FTT7, FCCz, FTT8, feedback);\nFTT7h = elec1020_fraction(cnt1, cnt2, 1/16);\nFCC5 = elec1020_fraction(cnt1, cnt2, 2/16);\nFCC5h = elec1020_fraction(cnt1, cnt2, 3/16);\nFCC3 = elec1020_fraction(cnt1, cnt2, 4/16);\nFCC3h = elec1020_fraction(cnt1, cnt2, 5/16);\nFCC1 = elec1020_fraction(cnt1, cnt2, 6/16);\nFCC1h = elec1020_fraction(cnt1, cnt2, 7/16);\nFCC2h = elec1020_fraction(cnt1, cnt2, 9/16);\nFCC2 = elec1020_fraction(cnt1, cnt2, 10/16);\nFCC4h = elec1020_fraction(cnt1, cnt2, 11/16);\nFCC4 = elec1020_fraction(cnt1, cnt2, 12/16);\nFCC6h = elec1020_fraction(cnt1, cnt2, 13/16);\nFCC6 = elec1020_fraction(cnt1, cnt2, 14/16);\nFTT8h = elec1020_fraction(cnt1, cnt2, 15/16);\n\nfprintf('constructing CCP contour\\n');\n[cnt1, cnt2] = elec1020_follow(pnt, dhk, TTP7, CCPz, TTP8, feedback);\nTTP7h = elec1020_fraction(cnt1, cnt2, 1/16);\nCCP5 = elec1020_fraction(cnt1, cnt2, 2/16);\nCCP5h = elec1020_fraction(cnt1, cnt2, 3/16);\nCCP3 = elec1020_fraction(cnt1, cnt2, 4/16);\nCCP3h = elec1020_fraction(cnt1, cnt2, 5/16);\nCCP1 = elec1020_fraction(cnt1, cnt2, 6/16);\nCCP1h = elec1020_fraction(cnt1, cnt2, 7/16);\nCCP2h = elec1020_fraction(cnt1, cnt2, 9/16);\nCCP2 = elec1020_fraction(cnt1, cnt2, 10/16);\nCCP4h = elec1020_fraction(cnt1, cnt2, 11/16);\nCCP4 = elec1020_fraction(cnt1, cnt2, 12/16);\nCCP6h = elec1020_fraction(cnt1, cnt2, 13/16);\nCCP6 = elec1020_fraction(cnt1, cnt2, 14/16);\nTTP8h = elec1020_fraction(cnt1, cnt2, 15/16);\n\nfprintf('constructing CP contour\\n');\n[cnt1, cnt2] = elec1020_follow(pnt, dhk, TP7, CPz, TP8, feedback);\nTP7h = elec1020_fraction(cnt1, cnt2, 1/16);\nCP5 = elec1020_fraction(cnt1, cnt2, 2/16);\nCP5h = elec1020_fraction(cnt1, cnt2, 3/16);\nCP3 = elec1020_fraction(cnt1, cnt2, 4/16);\nCP3h = elec1020_fraction(cnt1, cnt2, 5/16);\nCP1 = elec1020_fraction(cnt1, cnt2, 6/16);\nCP1h = elec1020_fraction(cnt1, cnt2, 7/16);\nCP2h = elec1020_fraction(cnt1, cnt2, 9/16);\nCP2 = elec1020_fraction(cnt1, cnt2, 10/16);\nCP4h = elec1020_fraction(cnt1, cnt2, 11/16);\nCP4 = elec1020_fraction(cnt1, cnt2, 12/16);\nCP6h = elec1020_fraction(cnt1, cnt2, 13/16);\nCP6 = elec1020_fraction(cnt1, cnt2, 14/16);\nTP8h = elec1020_fraction(cnt1, cnt2, 15/16);\n\nfprintf('constructing CPP contour\\n');\n[cnt1, cnt2] = elec1020_follow(pnt, dhk, TPP7, CPPz, TPP8, feedback);\nTPP7h = elec1020_fraction(cnt1, cnt2, 1/16);\nCPP5 = elec1020_fraction(cnt1, cnt2, 2/16);\nCPP5h = elec1020_fraction(cnt1, cnt2, 3/16);\nCPP3 = elec1020_fraction(cnt1, cnt2, 4/16);\nCPP3h = elec1020_fraction(cnt1, cnt2, 5/16);\nCPP1 = elec1020_fraction(cnt1, cnt2, 6/16);\nCPP1h = elec1020_fraction(cnt1, cnt2, 7/16);\nCPP2h = elec1020_fraction(cnt1, cnt2, 9/16);\nCPP2 = elec1020_fraction(cnt1, cnt2, 10/16);\nCPP4h = elec1020_fraction(cnt1, cnt2, 11/16);\nCPP4 = elec1020_fraction(cnt1, cnt2, 12/16);\nCPP6h = elec1020_fraction(cnt1, cnt2, 13/16);\nCPP6 = elec1020_fraction(cnt1, cnt2, 14/16);\nTPP8h = elec1020_fraction(cnt1, cnt2, 15/16);\n\nfprintf('constructing P contour\\n');\n[cnt1, cnt2] = elec1020_follow(pnt, dhk, P7, Pz, P8, feedback);\nP7h = elec1020_fraction(cnt1, cnt2, 1/16);\nP5 = elec1020_fraction(cnt1, cnt2, 2/16);\nP5h = elec1020_fraction(cnt1, cnt2, 3/16);\nP3 = elec1020_fraction(cnt1, cnt2, 4/16);\nP3h = elec1020_fraction(cnt1, cnt2, 5/16);\nP1 = elec1020_fraction(cnt1, cnt2, 6/16);\nP1h = elec1020_fraction(cnt1, cnt2, 7/16);\nP2h = elec1020_fraction(cnt1, cnt2, 9/16);\nP2 = elec1020_fraction(cnt1, cnt2, 10/16);\nP4h = elec1020_fraction(cnt1, cnt2, 11/16);\nP4 = elec1020_fraction(cnt1, cnt2, 12/16);\nP6h = elec1020_fraction(cnt1, cnt2, 13/16);\nP6 = elec1020_fraction(cnt1, cnt2, 14/16);\nP8h = elec1020_fraction(cnt1, cnt2, 15/16);\n\nfprintf('constructing PPO contour\\n');\n[cnt1, cnt2] = elec1020_follow(pnt, dhk, PPO7, PPOz, PPO8, feedback);\nPPO7h = elec1020_fraction(cnt1, cnt2, 1/16);\nPPO5 = elec1020_fraction(cnt1, cnt2, 2/16);\nPPO5h = elec1020_fraction(cnt1, cnt2, 3/16);\nPPO3 = elec1020_fraction(cnt1, cnt2, 4/16);\nPPO3h = elec1020_fraction(cnt1, cnt2, 5/16);\nPPO1 = elec1020_fraction(cnt1, cnt2, 6/16);\nPPO1h = elec1020_fraction(cnt1, cnt2, 7/16);\nPPO2h = elec1020_fraction(cnt1, cnt2, 9/16);\nPPO2 = elec1020_fraction(cnt1, cnt2, 10/16);\nPPO4h = elec1020_fraction(cnt1, cnt2, 11/16);\nPPO4 = elec1020_fraction(cnt1, cnt2, 12/16);\nPPO6h = elec1020_fraction(cnt1, cnt2, 13/16);\nPPO6 = elec1020_fraction(cnt1, cnt2, 14/16);\nPPO8h = elec1020_fraction(cnt1, cnt2, 15/16);\n\nfprintf('constructing PO contour\\n');\n[cnt1, cnt2] = elec1020_follow(pnt, dhk, PO7, POz, PO8, feedback);\nPO7h = elec1020_fraction(cnt1, cnt2, 1/16);\nPO5 = elec1020_fraction(cnt1, cnt2, 2/16);\nPO5h = elec1020_fraction(cnt1, cnt2, 3/16);\nPO3 = elec1020_fraction(cnt1, cnt2, 4/16);\nPO3h = elec1020_fraction(cnt1, cnt2, 5/16);\nPO1 = elec1020_fraction(cnt1, cnt2, 6/16);\nPO1h = elec1020_fraction(cnt1, cnt2, 7/16);\nPO2h = elec1020_fraction(cnt1, cnt2, 9/16);\nPO2 = elec1020_fraction(cnt1, cnt2, 10/16);\nPO4h = elec1020_fraction(cnt1, cnt2, 11/16);\nPO4 = elec1020_fraction(cnt1, cnt2, 12/16);\nPO6h = elec1020_fraction(cnt1, cnt2, 13/16);\nPO6 = elec1020_fraction(cnt1, cnt2, 14/16);\nPO8h = elec1020_fraction(cnt1, cnt2, 15/16);\n\nfprintf('constructing POO contour\\n');\n[cnt1, cnt2] = elec1020_follow(pnt, dhk, POO7, POOz, POO8, feedback);\nPOO7h = elec1020_fraction(cnt1, cnt2, 1/16);\nPOO5 = elec1020_fraction(cnt1, cnt2, 2/16);\nPOO5h = elec1020_fraction(cnt1, cnt2, 3/16);\nPOO3 = elec1020_fraction(cnt1, cnt2, 4/16);\nPOO3h = elec1020_fraction(cnt1, cnt2, 5/16);\nPOO1 = elec1020_fraction(cnt1, cnt2, 6/16);\nPOO1h = elec1020_fraction(cnt1, cnt2, 7/16);\nPOO2h = elec1020_fraction(cnt1, cnt2, 9/16);\nPOO2 = elec1020_fraction(cnt1, cnt2, 10/16);\nPOO4h = elec1020_fraction(cnt1, cnt2, 11/16);\nPOO4 = elec1020_fraction(cnt1, cnt2, 12/16);\nPOO6h = elec1020_fraction(cnt1, cnt2, 13/16);\nPOO6 = elec1020_fraction(cnt1, cnt2, 14/16);\nPOO8h = elec1020_fraction(cnt1, cnt2, 15/16);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% start contouring the low electrode locations\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% low horizontal ant-post through T9\nfprintf('constructing low horizontal left contour\\n');\n[cnt1, cnt2] = elec1020_follow(pnt, dhk, Nz, T9, Iz, feedback);\nAFp9 = elec1020_fraction(cnt1, cnt2, 3/20);\nAF9 = elec1020_fraction(cnt1, cnt2, 4/20);\nAFF9 = elec1020_fraction(cnt1, cnt2, 5/20);\nF9 = elec1020_fraction(cnt1, cnt2, 6/20);\nFFT9 = elec1020_fraction(cnt1, cnt2, 7/20);\nFT9 = elec1020_fraction(cnt1, cnt2, 8/20);\nFTT9 = elec1020_fraction(cnt1, cnt2, 9/20);\nT9 = elec1020_fraction(cnt1, cnt2, 10/20);\nTTP9 = elec1020_fraction(cnt1, cnt2, 11/20);\nTP9 = elec1020_fraction(cnt1, cnt2, 12/20);\nTPP9 = elec1020_fraction(cnt1, cnt2, 13/20);\nP9 = elec1020_fraction(cnt1, cnt2, 14/20);\nPPO9 = elec1020_fraction(cnt1, cnt2, 15/20);\nPO9 = elec1020_fraction(cnt1, cnt2, 16/20);\nPOO9 = elec1020_fraction(cnt1, cnt2, 17/20);\nI1 = elec1020_fraction(cnt1, cnt2, 18/20);\nI1h = elec1020_fraction(cnt1, cnt2, 19/20);\n\n[cnt1, cnt2] = elec1020_follow(pnt, dhk, NFpz, T9h, OIz, feedback);\nAFp9h = elec1020_fraction(cnt1, cnt2, 3/20);\nAF9h = elec1020_fraction(cnt1, cnt2, 4/20);\nAFF9h = elec1020_fraction(cnt1, cnt2, 5/20);\nF9h = elec1020_fraction(cnt1, cnt2, 6/20);\nFFT9h = elec1020_fraction(cnt1, cnt2, 7/20);\nFT9h = elec1020_fraction(cnt1, cnt2, 8/20);\nFTT9h = elec1020_fraction(cnt1, cnt2, 9/20);\nT9h = elec1020_fraction(cnt1, cnt2, 10/20);\nTTP9h = elec1020_fraction(cnt1, cnt2, 11/20);\nTP9h = elec1020_fraction(cnt1, cnt2, 12/20);\nTPP9h = elec1020_fraction(cnt1, cnt2, 13/20);\nP9h = elec1020_fraction(cnt1, cnt2, 14/20);\nPPO9h = elec1020_fraction(cnt1, cnt2, 15/20);\nPO9h = elec1020_fraction(cnt1, cnt2, 16/20);\nPOO9h = elec1020_fraction(cnt1, cnt2, 17/20);\nOI1 = elec1020_fraction(cnt1, cnt2, 18/20);\nOI1h = elec1020_fraction(cnt1, cnt2, 19/20);\n\n% low horizontal ant-post through T10\nfprintf('constructing low horizontal right contour\\n');\n[cnt1, cnt2] = elec1020_follow(pnt, dhk, Nz, T10, Iz, feedback);\nAFp10 = elec1020_fraction(cnt1, cnt2, 3/20);\nAF10 = elec1020_fraction(cnt1, cnt2, 4/20);\nAFF10 = elec1020_fraction(cnt1, cnt2, 5/20);\nF10 = elec1020_fraction(cnt1, cnt2, 6/20);\nFFT10 = elec1020_fraction(cnt1, cnt2, 7/20);\nFT10 = elec1020_fraction(cnt1, cnt2, 8/20);\nFTT10 = elec1020_fraction(cnt1, cnt2, 9/20);\nT10 = elec1020_fraction(cnt1, cnt2, 10/20);\nTTP10 = elec1020_fraction(cnt1, cnt2, 11/20);\nTP10 = elec1020_fraction(cnt1, cnt2, 12/20);\nTPP10 = elec1020_fraction(cnt1, cnt2, 13/20);\nP10 = elec1020_fraction(cnt1, cnt2, 14/20);\nPPO10 = elec1020_fraction(cnt1, cnt2, 15/20);\nPO10 = elec1020_fraction(cnt1, cnt2, 16/20);\nPOO10 = elec1020_fraction(cnt1, cnt2, 17/20);\nI2 = elec1020_fraction(cnt1, cnt2, 18/20);\nI2h = elec1020_fraction(cnt1, cnt2, 19/20);\n\n[cnt1, cnt2] = elec1020_follow(pnt, dhk, NFpz, T10h, OIz, feedback);\nAFp10h = elec1020_fraction(cnt1, cnt2, 3/20);\nAF10h = elec1020_fraction(cnt1, cnt2, 4/20);\nAFF10h = elec1020_fraction(cnt1, cnt2, 5/20);\nF10h = elec1020_fraction(cnt1, cnt2, 6/20);\nFFT10h = elec1020_fraction(cnt1, cnt2, 7/20);\nFT10h = elec1020_fraction(cnt1, cnt2, 8/20);\nFTT10h = elec1020_fraction(cnt1, cnt2, 9/20);\nT10h = elec1020_fraction(cnt1, cnt2, 10/20);\nTTP10h = elec1020_fraction(cnt1, cnt2, 11/20);\nTP10h = elec1020_fraction(cnt1, cnt2, 12/20);\nTPP10h = elec1020_fraction(cnt1, cnt2, 13/20);\nP10h = elec1020_fraction(cnt1, cnt2, 14/20);\nPPO10h = elec1020_fraction(cnt1, cnt2, 15/20);\nPO10h = elec1020_fraction(cnt1, cnt2, 16/20);\nPOO10h = elec1020_fraction(cnt1, cnt2, 17/20);\nOI2 = elec1020_fraction(cnt1, cnt2, 18/20);\nOI2h = elec1020_fraction(cnt1, cnt2, 19/20);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% collect all the computed electrode locations\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nlab = {\n 'LPA'\n 'RPA'\n 'NAS'\n 'INI'\n 'Nz'\n 'Fp1'\n 'Fpz'\n 'Fp2'\n 'AF9'\n 'AF7'\n 'AF5'\n 'AF3'\n 'AF1'\n 'AFz'\n 'AF2'\n 'AF4'\n 'AF6'\n 'AF8'\n 'AF10'\n 'F9'\n 'F7'\n 'F5'\n 'F3'\n 'F1'\n 'Fz'\n 'F2'\n 'F4'\n 'F6'\n 'F8'\n 'F10'\n 'FT9'\n 'FT7'\n 'FC5'\n 'FC3'\n 'FC1'\n 'FCz'\n 'FC2'\n 'FC4'\n 'FC6'\n 'FT8'\n 'FT10'\n 'T9'\n 'T7'\n 'C5'\n 'C3'\n 'C1'\n 'Cz'\n 'C2'\n 'C4'\n 'C6'\n 'T8'\n 'T10'\n 'TP9'\n 'TP7'\n 'CP5'\n 'CP3'\n 'CP1'\n 'CPz'\n 'CP2'\n 'CP4'\n 'CP6'\n 'TP8'\n 'TP10'\n 'P9'\n 'P7'\n 'P5'\n 'P3'\n 'P1'\n 'Pz'\n 'P2'\n 'P4'\n 'P6'\n 'P8'\n 'P10'\n 'PO9'\n 'PO7'\n 'PO5'\n 'PO3'\n 'PO1'\n 'POz'\n 'PO2'\n 'PO4'\n 'PO6'\n 'PO8'\n 'PO10'\n 'O1'\n 'Oz'\n 'O2'\n 'I1'\n 'Iz'\n 'I2'\n 'AFp9h'\n 'AFp7h'\n 'AFp5h'\n 'AFp3h'\n 'AFp1h'\n 'AFp2h'\n 'AFp4h'\n 'AFp6h'\n 'AFp8h'\n 'AFp10h'\n 'AFF9h'\n 'AFF7h'\n 'AFF5h'\n 'AFF3h'\n 'AFF1h'\n 'AFF2h'\n 'AFF4h'\n 'AFF6h'\n 'AFF8h'\n 'AFF10h'\n 'FFT9h'\n 'FFT7h'\n 'FFC5h'\n 'FFC3h'\n 'FFC1h'\n 'FFC2h'\n 'FFC4h'\n 'FFC6h'\n 'FFT8h'\n 'FFT10h'\n 'FTT9h'\n 'FTT7h'\n 'FCC5h'\n 'FCC3h'\n 'FCC1h'\n 'FCC2h'\n 'FCC4h'\n 'FCC6h'\n 'FTT8h'\n 'FTT10h'\n 'TTP9h'\n 'TTP7h'\n 'CCP5h'\n 'CCP3h'\n 'CCP1h'\n 'CCP2h'\n 'CCP4h'\n 'CCP6h'\n 'TTP8h'\n 'TTP10h'\n 'TPP9h'\n 'TPP7h'\n 'CPP5h'\n 'CPP3h'\n 'CPP1h'\n 'CPP2h'\n 'CPP4h'\n 'CPP6h'\n 'TPP8h'\n 'TPP10h'\n 'PPO9h'\n 'PPO7h'\n 'PPO5h'\n 'PPO3h'\n 'PPO1h'\n 'PPO2h'\n 'PPO4h'\n 'PPO6h'\n 'PPO8h'\n 'PPO10h'\n 'POO9h'\n 'POO7h'\n 'POO5h'\n 'POO3h'\n 'POO1h'\n 'POO2h'\n 'POO4h'\n 'POO6h'\n 'POO8h'\n 'POO10h'\n 'OI1h'\n 'OI2h'\n 'Fp1h'\n 'Fp2h'\n 'AF9h'\n 'AF7h'\n 'AF5h'\n 'AF3h'\n 'AF1h'\n 'AF2h'\n 'AF4h'\n 'AF6h'\n 'AF8h'\n 'AF10h'\n 'F9h'\n 'F7h'\n 'F5h'\n 'F3h'\n 'F1h'\n 'F2h'\n 'F4h'\n 'F6h'\n 'F8h'\n 'F10h'\n 'FT9h'\n 'FT7h'\n 'FC5h'\n 'FC3h'\n 'FC1h'\n 'FC2h'\n 'FC4h'\n 'FC6h'\n 'FT8h'\n 'FT10h'\n 'T9h'\n 'T7h'\n 'C5h'\n 'C3h'\n 'C1h'\n 'C2h'\n 'C4h'\n 'C6h'\n 'T8h'\n 'T10h'\n 'TP9h'\n 'TP7h'\n 'CP5h'\n 'CP3h'\n 'CP1h'\n 'CP2h'\n 'CP4h'\n 'CP6h'\n 'TP8h'\n 'TP10h'\n 'P9h'\n 'P7h'\n 'P5h'\n 'P3h'\n 'P1h'\n 'P2h'\n 'P4h'\n 'P6h'\n 'P8h'\n 'P10h'\n 'PO9h'\n 'PO7h'\n 'PO5h'\n 'PO3h'\n 'PO1h'\n 'PO2h'\n 'PO4h'\n 'PO6h'\n 'PO8h'\n 'PO10h'\n 'O1h'\n 'O2h'\n 'I1h'\n 'I2h'\n 'AFp9'\n 'AFp7'\n 'AFp5'\n 'AFp3'\n 'AFp1'\n 'AFpz'\n 'AFp2'\n 'AFp4'\n 'AFp6'\n 'AFp8'\n 'AFp10'\n 'AFF9'\n 'AFF7'\n 'AFF5'\n 'AFF3'\n 'AFF1'\n 'AFFz'\n 'AFF2'\n 'AFF4'\n 'AFF6'\n 'AFF8'\n 'AFF10'\n 'FFT9'\n 'FFT7'\n 'FFC5'\n 'FFC3'\n 'FFC1'\n 'FFCz'\n 'FFC2'\n 'FFC4'\n 'FFC6'\n 'FFT8'\n 'FFT10'\n 'FTT9'\n 'FTT7'\n 'FCC5'\n 'FCC3'\n 'FCC1'\n 'FCCz'\n 'FCC2'\n 'FCC4'\n 'FCC6'\n 'FTT8'\n 'FTT10'\n 'TTP9'\n 'TTP7'\n 'CCP5'\n 'CCP3'\n 'CCP1'\n 'CCPz'\n 'CCP2'\n 'CCP4'\n 'CCP6'\n 'TTP8'\n 'TTP10'\n 'TPP9'\n 'TPP7'\n 'CPP5'\n 'CPP3'\n 'CPP1'\n 'CPPz'\n 'CPP2'\n 'CPP4'\n 'CPP6'\n 'TPP8'\n 'TPP10'\n 'PPO9'\n 'PPO7'\n 'PPO5'\n 'PPO3'\n 'PPO1'\n 'PPOz'\n 'PPO2'\n 'PPO4'\n 'PPO6'\n 'PPO8'\n 'PPO10'\n 'POO9'\n 'POO7'\n 'POO5'\n 'POO3'\n 'POO1'\n 'POOz'\n 'POO2'\n 'POO4'\n 'POO6'\n 'POO8'\n 'POO10'\n 'OI1'\n 'OIz'\n 'OI2'\n 'T3' % this is now called T7\n 'T4' % this is now called T8\n 'T5' % this is now called P7\n 'T6' % this is now called P8\n 'M1' % left mastoid\n 'M2' % right mastoid\n 'A1' % left ear lobe\n 'A2' % right ear lobe\n };\n\n% allow for upper case electrode position labels\nNAS = nas;\nINI = ini;\nLPA = lpa;\nRPA = rpa;\n\n% it would be possible to assign locations to these old locations\n% but there are no locations determined for M1/2 and A1/2\nif false\n T3 = T7;\n T4 = T8;\n T5 = P7;\n T6 = P8;\nend\n\n% assign the known local electrode positions to the output matrix\nnlab = numel(lab);\nelc = ones(nlab,3) * nan;\nfor i=1:nlab\n if exist(lab{i}, 'var')\n eval(sprintf('elc(%d,:) = %s;', i, lab{i}));\n else\n fprintf('not placing electrode %s\\n', lab{i});\n end\nend\n\n% remove unknown electrode positions\nsel = ~isnan(elc(:,1));\nelc = elc(sel, :);\nlab = lab(sel);\n\nif feedback\n elec = [];\n elec.elecpos = elc;\n elec.label = lab;\n ft_plot_sens(elec)\nend\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/private/elec1020_locate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548511303338, "lm_q2_score": 0.4843800842769843, "lm_q1q2_score": 0.3155033176847336}} {"text": "function [delta,h,alpha] = iswnbr(w,thetaSQR)\n% [delta,h,alpha] = iswnbr(vSQR,thetaSQR)\n%\n% ISWNBR Checks feasibility w.r.t. wide region/neighborhood of Sturm-Zhang.\n% vTAR:= (1-alpha)*max(h,v) projection v onto theta-central region\n% delta = (sqrt(n)/theta) * norm(vTAR - v) / norm(v)\n%\n% ********** INTERNAL FUNCTION OF SEDUMI **********\n%\n% See also sedumi\n\n% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko\n% Copyright (C) 2005 McMaster University, Hamilton, CANADA (since 1.1)\n%\n% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)\n% Dept. Econometrics & O.R., Tilburg University, the Netherlands.\n% Supported by the Netherlands Organization for Scientific Research (NWO).\n%\n% Affiliation SeDuMi 1.03 and 1.04Beta (2000):\n% Dept. Quantitative Economics, Maastricht University, the Netherlands.\n%\n% Affiliations up to SeDuMi 1.02 (AUG1998):\n% CRL, McMaster University, Canada.\n% Supported by the Netherlands Organization for Scientific Research (NWO).\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA\n% 02110-1301, USA\n%\n\n%Indicate to the user Matlab cannot find the SeDuMi binaries\nsedumi_binary_error();\n\n% ----------------------------------------\n% r = n/thetaSQR\n% hSQR = sumwNT/(r-|T|), hubSQR = sumwNT/(r-|T| - |Q|)\n% sumdifv = h*|T| - sumvT (sumvT = sum(v_T), growing )\n% sumdifw = hSQR*|T| - sumwT\n% alpha = sumdifv / (r*h)\n% deltaSQR = r * ( 2*alpha-alpha^2 - (1-alpha)^2 * sumdifw/gap )\n% WE UPDATE sumdifv AND sumdifw IN A STABLE WAY\n% ----------------------------------------\nn = length(w); gap = sum(w);\nsumwNT = gap;\nr = n / thetaSQR;\ncardT = 0; wQ = []; sumdifv = 0; sumdifw = 0;\ncardQ = n;\nhSQR = sumwNT / (r - cardT); hubSQR = sumwNT / (r-(n-1));\nfor j = 1:n\n wj = w(j);\n if wj >= hubSQR % wj >= hubSQR ==> not in T\n cardQ = cardQ - 1;\n hubSQR = sumwNT / (r-cardT-cardQ);\n elseif wj < hSQR % wj < hSQR ==> in T\n cardT = cardT + 1;\n cardQ = cardQ - 1;\n hubSQR = (1-wj/sumwNT) * hubSQR;\n sumwNT = sumwNT - wj;\n oldhSQR = hSQR;\n hSQR = sumwNT / (r - cardT);\n sumdifw = sumdifw + (oldhSQR-wj) + cardT * (hSQR-oldhSQR);\n sumdifv = sumdifv + (sqrt(oldhSQR)-sqrt(wj)) + ...\n cardT * (sqrt(hSQR)-sqrt(oldhSQR));\n else % Inconclusive: j in Q\n wQ = [wQ;wj]; %#ok\n end % if\nend % for\n% ----------------------------------------\n% The same treatment for the Q set, but we\n% sort the (presumably short) wQ first.\n% ----------------------------------------\nif ~isempty(wQ)\n sort(wQ);\n STOP = 0; j = 1;\n while ~STOP\n wj = wQ(j);\n if wj >= hSQR\n STOP = 1;\n else\n cardT = cardT + 1;\n sumwNT = sumwNT - wj;\n oldhSQR = hSQR;\n hSQR = sumwNT / (r - cardT);\n sumdifw = sumdifw + (oldhSQR-wj) + cardT * (hSQR-oldhSQR);\n sumdifv = sumdifv + (sqrt(oldhSQR)-sqrt(wj)) + ...\n cardT * (sqrt(hSQR)-sqrt(oldhSQR));\n j = j+1;\n if j > length(wQ)\n STOP = 1;\n end\n end\n end\nend % treatment Q\n% ----------------------------------------\n% alpha = sumdifv/(r*h)\n% deltaSQR = r * ( 2*alpha-alpha^2 - (1-alpha)^2 * sumdifw/gap )\n% (THE ABOVE DIFFERENCE SHOULD NOT BE NUMERICALLY DANGEROUS,\n% SINCE alpha IS *SIGNIF* BIGGER THAN sumdifw/gap )\n% ----------------------------------------\nh = sqrt(hSQR);\nalpha = sumdifv/ (r*h);\ndeltaSQR = alpha*(2-alpha) - (1-alpha)^2 * sumdifw/gap;\ndelta = sqrt(r*deltaSQR);", "meta": {"author": "zarathustr", "repo": "LibQPEP", "sha": "99e5c23e746ace0bac4a86742c31db6fcf7297ba", "save_path": "github-repos/MATLAB/zarathustr-LibQPEP", "path": "github-repos/MATLAB/zarathustr-LibQPEP/LibQPEP-99e5c23e746ace0bac4a86742c31db6fcf7297ba/MATLAB/sedumi/iswnbr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6893056167854461, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.3151069065480501}} {"text": "function [energyV,entropyV,sumAvgV,corrV,invDiffMomV,contrastV,...\n clustShadeV,clustProminV] = haralickTextureAllDir(scanArray3M, nL, offsetsM, flagv, hWait)\n% [energyV,entropyV,sumAvgV,corrV,invDiffMomV,contrastV,...\n% clustShadeV,clustProminV] = haralickTextureAllDir(scanArray3M, nL, offsetsM, flagv, hWait)\n%\n% Haralick texture with cooccurrence matrix combined from all directions.\n%\n% APA, 05/12/2016\n\n% Generate flags\nif ~exist('flagv','var')\n flagv = ones(1,8);\nelseif exist('flagv','var') && isempty(flagv)\n flagv = ones(1,8);\nend\n\n% % Flag to draw waitbar\n% waitbarFlag = 0;\n% if exist('hWait','var') && ishandle(hWait)\n% waitbarFlag = 1;\n% end\n\n\n% % Grid resolution\n% deltaX = deltaXYZv(1);\n% deltaY = deltaXYZv(2);\n% deltaZ = deltaXYZv(3);\n%\n% % Get Block size to process\n% slcWindow = floor(2*patchSizeV(3)/deltaZ);\n% rowWindow = floor(2*patchSizeV(1)/deltaY);\n% colWindow = floor(2*patchSizeV(2)/deltaX);\n%\n% % Make sure that the window is of odd size\n% if mod(slcWindow,2) == 0\n% slcWindow = slcWindow + 1;\n% end\n% if mod(rowWindow,2) == 0\n% rowWindow = rowWindow + 1;\n% end\n% if mod(colWindow,2) == 0\n% colWindow = colWindow + 1;\n% end\n\nslcWindow = size(scanArray3M,3);\nrowWindow = size(scanArray3M,1);\ncolWindow = size(scanArray3M,2);\n\n% Build distance matrices\nnumColsPad = 1;\nnumRowsPad = 1;\nnumSlcsPad = 1;\n\n% Get number of voxels per slice\n[numRows, numCols, numSlices] = size(scanArray3M);\nnumVoxels = numRows*numCols;\n\nminQ = min(scanArray3M(:));\nmaxQ = max(scanArray3M(:));\ndq = (maxQ-minQ)/nL/4;\nlevels = linspace(minQ,maxQ,nL);\nlevels = linspace(dq,maxQ-dq,nL);\nq1 = imquantize_cerr(scanArray3M,nL);\nq2 = imquantize(scanArray3M, levels);\n%levels = multithresh(scanArray3M, nL);\n%q3 = imquantize(scanArray3M, levels);\n\n% Pad doseArray2 so that sliding window works also for the edge voxels\n%scanArrayTmp3M = padarray(scanArray3M,[numRowsPad numColsPad\n%numSlcsPad],NaN,'both'); % aa commented\nif exist('padarray.m','file')\n q = padarray(q1,[numRowsPad numColsPad numSlcsPad],NaN,'both');\nelse\n q = padarray_oct(q1,[numRowsPad numColsPad numSlcsPad],NaN,'both');\nend\n\n% Quantize the image\n%nL = 16;\n% if any(isnan(q)) % aa commented\n% nL = nL-1; % aa commented\n% end % aa commented\n%q = imquantize_cerr(scanArrayTmp3M,nL); % aa commented\n%clear scanArrayTmp3M; % aa commented\nqmax = max(q(:));\nnanFlag = 0;\nif any(isnan(q(:)))\n nanFlag = 1;\n q(isnan(q))=qmax+1;\nend\nqs=sort(unique(q));\nlq=length(qs);\n\nfor k = 1:length(qs)\n q(q==qs(k)) = k;\nend\n\nq = uint16(q); % q is the quantized image\n%numSlcsWithPadding = size(q,3);\n\n% % Create indices for 2D blocks\n% [m,n,~] = size(q);\n% m = uint32(m);\n% n = uint32(n);\n% colWindow = uint32(colWindow);\n% rowWindow = uint32(rowWindow);\n% slcWindow = uint32(slcWindow);\n%\n% % Index calculation adapted from\n% % http://stackoverflow.com/questions/25449279/efficient-implementation-of-im2col-and-col2im\n%\n% %// Start indices for each block\n% start_ind = reshape(bsxfun(@plus,[1:m-rowWindow+1]',[0:n-colWindow]*m),[],1); %//'\n%\n% %// Row indices\n% lin_row = permute(bsxfun(@plus,start_ind,[0:rowWindow-1])',[1 3 2]); %//'\n%\n% %// Get linear indices based on row and col indices and get desired output\n% % imTmpM = A(reshape(bsxfun(@plus,lin_row,[0:ncols-1]*m),nrows*ncols,[]));\n% indM = reshape(bsxfun(@plus,lin_row,(0:colWindow-1)*m),rowWindow*colWindow,[]);\n\n% Create indices list\n%indCooccurM = reshape(1:nL*nL,nL,nL);\n\n% Number of offsets\nnumOffsets = size(offsetsM,1);\n\n% Indices of last level to filter out\nnanIndV = false([lq*lq,1]);\nnanIndV([lq:lq:lq*lq-lq, lq*lq-lq:lq*lq]) = true;\n\n% Build levels vector for mu, sig\nlevRowV = repmat(1:lq,[1 lq]);\nlevColV = repmat(1:lq,[lq 1]);\nlevColV = levColV(:)';\n\n% Build list of indices for px and contrast calculation\nfor n=0:lq-1\n % indices for p(x-y), contrast\n indCtrstV = false(lq*lq,1);\n indCtrst1V = 1:lq-n;\n indCtrst2V = 1+n:lq;\n indCtrstTmpV = indCtrst1V + (indCtrst2V-1)*lq;\n indCtrstTmpV = [indCtrstTmpV indCtrst2V + (indCtrst1V-1)*lq];\n indCtrstV(indCtrstTmpV) = 1;\n indCtrstV(nanIndV) = [];\n indCtrstC{n+1} = indCtrstV;\n \n % indices for p(x+y)\n indPxPlusYv = false(lq*lq,1);\n indPxPlusYv(levRowV + levColV == n+2) = 1;\n indPxPlusYv(nanIndV) = [];\n indPxPlusYc{n+1} = indPxPlusYv;\n \n % indices for px\n indPxV = false(lq*lq,1);\n indPxV(lq*n+1:lq*(n+1)) = true;\n indPxV(nanIndV) = [];\n indPxC{n+1} = indPxV;\nend\n\n% Filter NaN indices from row/col levels\nlevRowV(nanIndV) = [];\nlevColV(nanIndV) = [];\n\n% Build linear indices column/row-wise for Symmetry\nindRowV = zeros(1,lq*lq);\nfor i=1:lq\n indRowV((i-1)*lq+1:(i-1)*lq+lq) = i:lq:lq*lq;\nend\n\n% Initialize\nenergyV = [];\nentropyV = [];\nsumAvgV = [];\ncorrcorrV = [];\ninvDiffMomV = [];\ncontrastV = [];\nclustShadeV = [];\nclustProminV = [];\n\ntic\n% Initialize cooccurrence matrix (vectorized for speed)\ncooccurV = zeros(lq*lq,1,'single');\nfor off = 1:numOffsets\n \n offset = offsetsM(off,:);\n slc1M = q(numRowsPad+(1:numRows),numColsPad+(1:numCols),...\n numSlcsPad+(1:numSlices));\n slc2M = circshift(q,offset);\n slc2M = slc2M(numRowsPad+(1:numRows),numColsPad+(1:numCols),numSlcsPad+(1:numSlices))...\n + (slc1M-1)*lq;\n cooccurV = cooccurV + accumarray(slc2M(:),1, [lq*lq,1]); % patch-wise cooccurance\n\nend\n\ncooccurV = cooccurV + cooccurV(indRowV,:); % for symmetry\ncooccurV(nanIndV,:) = [];\ncooccurV = cooccurV./sum(cooccurV);\n\n% Calculate scalar texture for this offset\n% Angular Second Moment (Energy)\nif flagv(1)\n energyV = sum(cooccurV.^2);\nend\n% Entropy\nif flagv(2)\n entropyV = -sum(cooccurV.*log2(cooccurV+1e-10));\nend\n% Contrast, inverse Difference Moment\ncontrastV = 0;\ninvDiffMomV = 0;\nfor n=0:nL-1\n % px\n px(n+1) = sum(cooccurV(indPxC{n+1},:),1);\n % p(x+y)\n pXplusY = cooccurV(indCtrstC{n+1},:);\n % p(x-y)\n pXminusY = cooccurV(indCtrstC{n+1},:);\n % contrast\n if flagv(6)\n contrastV = contrastV + ...\n sum(n^2*cooccurV(indCtrstC{n+1},:));\n end\n % inv diff moment\n if flagv(5)\n invDiffMomV = invDiffMomV + ...\n sum((1/(1+n^2))*cooccurV(indCtrstC{n+1},:));\n end\nend\n% weighted pixel average (mu), weighted pixel variance (sig)\nmu = (1:nL) * px';\nsig = ((1:nL)-mu).^2 * px';\n%px = sum(cooccurV(indCooccurM),2);\nmuX = mean(px);\nsigX = std(px);\n% for colNum = 1:numCalcVoxs\nclstrV = (levRowV + levColV - 2*mu);\n% Cluster Shade\nif flagv(7)\n clustShadeV = clstrV.*clstrV.*clstrV * cooccurV(:,1);\nend\n% Cluster Prominence\n% clustProminTmpV(colNum) = (levRowV + levColV - 2*mu(colNum)).^4 ...\n% * cooccurPatchM(:,colNum);\nif flagv(8)\n clustProminV = clstrV.*clstrV.*clstrV.*clstrV ...\n * cooccurV(:,1);\nend\n% Sum Avg\nif flagv(3)\n sumAvgV = (levRowV + levColV) * cooccurV(:,1);\nend\n% Correlation\nif flagv(4)\n corrV = (levRowV .* levColV * cooccurV(:,1) - ...\n muX*muX) / sigX^2; %var(1); % check this\nend\n\n\n\n% % Average texture from all directions\n% energyV = energyV / numOffsets;\n% entropyV = entropyV / numOffsets;\n% contrastV = contrastV / numOffsets;\n% invDiffMomV = invDiffMomV / numOffsets;\n% clustShadeV = clustShadeV / numOffsets;\n% clustProminV = clustProminV / numOffsets;\n\n% if flagv(1)\n% energyV = energyV / numOffsets;\n% end\n% if flagv(2)\n% entropyV = entropyV / numOffsets;\n% end\n% if flagv(3)\n% sumAvgV = sumAvgV / numOffsets;\n% end\n% if flagv(4)\n% corrV = corrV / numOffsets;\n% end\n%\n% if flagv(6)\n% contrastV = contrastV / numOffsets;\n% end\n% if flagv(5)\n% invDiffMomV = invDiffMomV / numOffsets;\n% end\n% if flagv(7)\n% clustShadeV = clustShadeV / numOffsets;\n% end\n% if flagv(8)\n% clustProminV = clustProminV / numOffsets;\n% end\n\n% if waitbarFlag\n% set(hWait, 'Vertices', [[0 0 slcNum/numSlices slcNum/numSlices]' [0 1 1 0]']);\n% drawnow;\n% end\n\n% end\ntoc\n\n", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/CERR_core/PlanMetrics/heterogenity_metrics/haralickTextureAllDir.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.3145090531165991}} {"text": "function om = add_legacy_cost(om, name, idx, varargin)\n%ADD_LEGACY_COST Adds a set of user costs to the model.\n%\n% OM.ADD_LEGACY_COST(NAME, CP);\n% OM.ADD_LEGACY_COST(NAME, CP, VARSETS);\n% OM.ADD_LEGACY_COST(NAME, IDX_LIST, CP);\n% OM.ADD_LEGACY_COST(NAME, IDX_LIST, CP, VARSETS);\n%\n% Adds a named block of user-defined costs to the model. Each set is\n% defined by the CP struct described below. All user-defined sets of\n% costs are combined together into a single set of cost parameters in\n% a single CP struct by BULD_COST_PARAMS. This full aggregate set of\n% cost parameters can be retreived from the model by GET_COST_PARAMS.\n%\n% Examples:\n% cp1 = struct('N', N1, 'Cw', Cw1);\n% cp2 = struct('N', N2, 'Cw', Cw2, 'H', H, 'dd', dd, ...\n% 'rh', rh, 'kk', kk, 'mm', mm);\n% om.add_legacy_cost('usr1', cp1, {'Pg', 'Qg', 'z'});\n% om.add_legacy_cost('usr2', cp2, {'Vm', 'Pg', 'Qg', 'z'});\n%\n% om.init_indexed_name('c', {2, 3});\n% for i = 1:2\n% for j = 1:3\n% om.add_legacy_cost('c', {i, j}, cp(i,j), ...);\n% end\n% end\n%\n% Let x refer to the vector formed by combining the specified VARSETS,\n% and f_u(x, CP) be the cost at x corresponding to the cost parameters\n% contained in CP, where CP is a struct with the following fields:\n% N - nw x nx sparse matrix (optional, identity matrix by default)\n% Cw - nw x 1 vector\n% H - nw x nw sparse matrix (optional, all zeros by default)\n% dd, mm - nw x 1 vectors (optional, all ones by default)\n% rh, kk - nw x 1 vectors (optional, all zeros by default)\n%\n% These parameters are used as follows to compute f_u(x, CP)\n%\n% R = N*x - rh\n%\n% / kk(i), R(i) < -kk(i)\n% K(i) = < 0, -kk(i) <= R(i) <= kk(i)\n% \\ -kk(i), R(i) > kk(i)\n%\n% RR = R + K\n%\n% U(i) = / 0, -kk(i) <= R(i) <= kk(i)\n% \\ 1, otherwise\n%\n% DDL(i) = / 1, dd(i) = 1\n% \\ 0, otherwise\n%\n% DDQ(i) = / 1, dd(i) = 2\n% \\ 0, otherwise\n%\n% Dl = diag(mm) * diag(U) * diag(DDL)\n% Dq = diag(mm) * diag(U) * diag(DDQ)\n%\n% w = (Dl + Dq * diag(RR)) * RR\n%\n% f_u(x, CP) = 1/2 * w'*H*w + Cw'*w\n%\n% See also OPT_MODEL, PARAMS_LEGACY_COST, EVAL_LEGACY_COST.\n\n% MATPOWER\n% Copyright (c) 2008-2020, Power Systems Engineering Research Center (PSERC)\n% by Ray Zimmerman, PSERC Cornell\n%\n% This file is part of MATPOWER.\n% Covered by the 3-clause BSD License (see LICENSE file for details).\n% See https://matpower.org for more info.\n\nif iscell(idx)\n cp = varargin{1};\n args = varargin(2:end);\nelse %% simple named set\n cp = idx;\n args = varargin;\n idx = {};\nend\n\nif isempty(args)\n varsets = {};\nelse\n varsets = args{1};\nend\n\n%% convert varsets from cell to struct array if necessary\nvarsets = om.varsets_cell2struct(varsets);\nnv = om.varsets_len(varsets); %% number of variables\n\nif isfield(cp, 'N')\n [nw, nx] = size(cp.N);\nelse\n nw = length(cp.Cw);\n nx = nw;\n cp.N = speye(nw, nx);\nend\n\n%% check sizes\nif nx ~= nv\n if nw == 0\n cp.N = sparse(nw, nx);\n else\n error('@opt_model/add_legacy_cost: number of columns in N (%d x %d) does not match\\nnumber of variables (%d)\\n', nw, nx, nv);\n end\nend\nif size(cp.Cw, 1) ~= nw\n error('@opt_model/add_legacy_cost: number of rows of Cw (%d x %d) and N (%d x %d) must match\\n', size(cp.Cw), nw, nx);\nend\nif isfield(cp, 'H') && (size(cp.H, 1) ~= nw || size(cp.H, 2) ~= nw)\n error('@opt_model/add_legacy_cost: both dimensions of H (%d x %d) must match the number of rows in N (%d x %d)\\n', size(cp.H), nw, nx);\nend\nif isfield(cp, 'dd') && size(cp.dd, 1) ~= nw\n error('@opt_model/add_legacy_cost: number of rows of dd (%d x %d) and N (%d x %d) must match\\n', size(cp.dd), nw, nx);\nend\nif isfield(cp, 'rh') && size(cp.rh, 1) ~= nw\n error('@opt_model/add_legacy_cost: number of rows of rh (%d x %d) and N (%d x %d) must match\\n', size(cp.rh), nw, nx);\nend\nif isfield(cp, 'kk') && size(cp.kk, 1) ~= nw\n error('@opt_model/add_legacy_cost: number of rows of kk (%d x %d) and N (%d x %d) must match\\n', size(cp.kk), nw, nx);\nend\nif isfield(cp, 'mm') && size(cp.mm, 1) ~= nw\n error('@opt_model/add_legacy_cost: number of rows of mm (%d x %d) and N (%d x %d) must match\\n', size(cp.mm), nw, nx);\nend\n\n%% add the legacy cost set\nom.add_named_set('cost', name, idx, nw, cp, varsets);\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_model/add_legacy_cost.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.3142240456389592}} {"text": "function model = rmSearchFit_oneGaussianNonlinear(model, data, params, wProcess, t)\n% rmSearchFit_oneGaussianNonlinear - wrapper for 'fine' one Gaussian fit\n%\n% model = rmSearchFit_oneGaussianNonlinear(model, data, params, wProcess, t);\n%\n% 2008/01 SOD: split of from rmSearchFit.\n% 2010/02 SOD: cleanup.\n% 2015/02 JW: branched from rmSearchFit_oneGaussian, now includes\n% non-linear model (see Kay et al, 2013, on Compressive\n% Spatial Summation)\n \n% fminsearch options\nsearchOptions = params.analysis.fmins.options;\nexpandRange = params.analysis.fmins.expandRange;\n \n% convert to double just in case\nparams.analysis.X = double(params.analysis.X);\nparams.analysis.Y = double(params.analysis.Y);\n\nparams.analysis.allstimimages_unconvolved = double(params.analysis.allstimimages_unconvolved);\ndata = double(data);\n\n% get starting upper and lower range and reset TolFun \n% (raw rss computation (similar to norm) and TolFun adjustments)\nmodel.s = model.s_major;\n[range, TolFun] = rmSearchFit_range(params,model,data);\n\n% GLU 2021-10-14: not sute if best option, but I am going to restrict here\n% the exponent\n% If we are here we know that we are fitting the nonlinear css\nif params.analysis.fixcssexp ~= 0\n range.start(4,:) = params.analysis.fixcssexp * ones(size(range.start(4,:)));\n range.lower(4,:) = params.analysis.fixcssexp * ones(size(range.start(4,:)));;\n range.upper(4,:) = params.analysis.fixcssexp * ones(size(range.start(4,:)));;\nend\n\n% amount of negative fits\nnNegFit = 0;\nvethresh = params.analysis.fmins.vethresh;\ntrends = t.trends;\nt_id = t.dcid+1;\n\n%-----------------------------------\n% Go for each voxel\n%-----------------------------------\nprogress = 0;tic;\nfor ii = 1:numel(wProcess),\n % progress monitor (10 dots)\n if floor(ii./numel(wProcess)*10)>progress,\n % print out estimated time left\n if progress==0,\n esttime = toc.*10;\n if floor(esttime./3600)>0,\n fprintf(1,'[%s]:Estimated processing time: %d voxels: %d hours.\\n',...\n mfilename,numel(wProcess),ceil(esttime./3600));\n else\n fprintf(1,'[%s]:Estimated processing time: %d voxels: %d minutes.\\n',...\n mfilename,numel(wProcess),ceil(esttime./60));\n end;\n fprintf(1,'[%s]:Nonlinear optimization (x,y,sigma, exponent):',mfilename);\n end;\n fprintf(1,'.');drawnow;\n progress = progress + 1;\n end;\n\n % volume index\n vi = wProcess(ii);\n vData = data(:,ii);\n \n % reset tolFun: Precision of evaluation function. \n % We define RMS improvement relative to the initial raw 'no-fit' data\n % RMS. So, 1 means stop if there is less than 1% improvement on the fit:\n % searchOptions = optimset(searchOptions,'tolFun',optimget(params.analysis.fmins.options,'tolFun')./100.*rawrss);\n % optimset and optimget are a little slow so:\n searchOptions.TolFun = TolFun(ii);\n \n % actual fitting routine\n if searchOptions.MaxIter>0\n outParams = ...\n fmincon(@(x) rmModelSearchFit_oneGaussianNonlinear(x,vData,...\n params.analysis.X,...\n params.analysis.Y,...\n params.analysis.allstimimages_unconvolved,...\n params.analysis.Hrf,...\n params.analysis.scans,...\n trends),...\n range.start(:,vi),... % X0. Vector of 5 [x,y,sigma,exp,?]\n [],[], ... % A, B\n [],[], ... % Aeq, Beq\n range.lower(:,vi), ... % LB\n range.upper(:,vi),... % UB\n @(x) distanceCon(x,range.start(:,vi),range.step(:,vi).*expandRange),... % NONLCON\n searchOptions); % OPTIONS \n else\n outParams = range.start(:,vi);\n end\n\n %[ outParams range.lower(:,vi) range.start(:,vi) range.upper(:,vi)]\n\n % make RF, prediction and get rss,b\n Xv = params.analysis.X-outParams(1);\n Yv = params.analysis.Y-outParams(2);\n n = outParams(4);\n rf = exp( (Yv.*Yv + Xv.*Xv) ./ (-2.*(outParams(3).^2)) );\n pred = (params.analysis.allstimimages_unconvolved * rf).^ n;\n for scan = 1:numel(params.stim)\n inds = params.analysis.scans == scan;\n pred(inds) = filter(params.analysis.Hrf{scan}, 1, pred(inds));\n end\n \n X = [pred trends];\n b = pinv(X)*vData;\n rss = norm(vData-X*b).^2;\n\n % store results only if the first beta is positive, somehow fmincon\n % outputs negative fits. If the fit is negative keep old (grid) fit. We\n % do adjust the rss, so it won't be accidentally counted as a 'good'\n % fit. \n if b(1)>0,\n model.x0(vi) = outParams(1);\n model.y0(vi) = outParams(2);\n model.s(vi) = outParams(3);\n model.s_major(vi) = outParams(3);\n model.s_minor(vi) = outParams(3);\n model.s_theta(vi) = 0;\n model.exponent(vi) = outParams(4);\n model.rss(vi) = rss;\n model.b([1 t_id],vi) = b;\n else\n % change the percent variance explained to be just under the\n % current vethresh. So it counts as a 'coarse'-fit but can still be\n % included in later 'fine'-fits\n model.rss(vi) = (1-max((vethresh-0.01),0)).*model.rawrss(vi);\n nNegFit = nNegFit + 1;\n end\nend\n\n% end time monitor\net = toc;\nif floor(et/3600)>0,\n fprintf(1,'Done [%d hours].\\n',ceil(et/3600));\nelse\n fprintf(1,'Done [%d minutes].\\n',ceil(et/60));\nend;\nfprintf(1,'[%s]:Removed negative fits: %d (%.1f%%).\\n',...\n mfilename,nNegFit,nNegFit./numel(wProcess).*100);\nreturn;\n\n\n\n%-----------------------------------\n% make sure that the pRF can only be moved \"step\" away from original\n% position \"startParams\" - for the one Gaussian model\nfunction [C, Ceq]=distanceCon(x,startParams,step)\nCeq = [];\ndist = x([1 2])-startParams([1 2]);\nC = norm(dist) - step;\nreturn;\n%-----------------------------------\n\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrBOLD/Analysis/retinotopyModel/rmSearchFit_oneGaussianNonlinear.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.3141640248922661}} {"text": "%% Example: Proton Treatment Plan with Manipulated CT values\n%\n% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Copyright 2017 the matRad development team. \n% \n% This file is part of the matRad project. It is subject to the license \n% terms in the LICENSE file found in the top-level directory of this \n% distribution and at https://github.com/e0404/matRad/LICENSES.txt. No part \n% of the matRad project, including this file, may be copied, modified, \n% propagated, or distributed except according to the terms contained in the \n% LICENSE file.\n%\n% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%% \n% In this example we will show \n% (i) how to load patient data into matRad\n% (ii) how to setup a proton dose calculation \n% (iii) how to inversely optimize the pencil beam intensities directly from command window in MATLAB.\n% (iv) how to re-optimize a treatment plan\n% (v) how to manipulate the CT cube by adding noise to the cube \n% (vi) how to recalculate the dose considering the manipulated CT cube and the previously optimized pencil beam intensities\n% (vii) how to compare the two results\n\n%% Patient Data Import\n% Let's begin with a clear Matlab environment and import the prostate \n% patient into your workspace.\n\nmatRad_rc; %If this throws an error, run it from the parent directory first to set the paths\n\nload('PROSTATE.mat');\n\n%% Treatment Plan\n% The next step is to define your treatment plan labeled as 'pln'. This \n% structure requires input from the treatment planner and defines \n% the most important cornerstones of your treatment plan.\n\npln.radiationMode = 'protons'; \npln.machine = 'generic_MCsquare';\npln.numOfFractions = 30;\npln.propOpt.bioOptimization = 'const_RBExD'; \npln.propStf.gantryAngles = [90 270];\npln.propStf.couchAngles = [0 0];\npln.propStf.bixelWidth = 3;\npln.propStf.numOfBeams = numel(pln.propStf.gantryAngles);\npln.propStf.isoCenter = ones(pln.propStf.numOfBeams,1) * matRad_getIsoCenter(cst,ct,0);\npln.propOpt.runDAO = 0;\npln.propOpt.runSequencing = 0;\n\n% dose calculation settings\npln.propDoseCalc.doseGrid.resolution.x = 3; % [mm]\npln.propDoseCalc.doseGrid.resolution.y = 3; % [mm]\npln.propDoseCalc.doseGrid.resolution.z = 3; % [mm]\n\n%% Generate Beam Geometry STF\nstf = matRad_generateStf(ct,cst,pln);\n\n%% Dose Calculation\ndij = matRad_calcParticleDoseMC(ct,stf,pln,cst);\n\n%% Inverse Optimization for IMPT\nresultGUI = matRad_fluenceOptimization(dij,cst,pln);\n\n%% Calculate quality indicators \n[dvh,qi] = matRad_indicatorWrapper(cst,pln,resultGUI);\nixRectum = 1;\ndisplay(qi(ixRectum).D_5);\n\n%%\n% Let's change the optimization parameter of the rectum in such a way that it\n% will be better spared. We increase the penalty and lower the threshold \n% of the squared overdose objective function. Afterwards we re-optimize \n% the treatment plan and evaluate dose statistics one more time.\n\nobjective = cst{ixRectum,6}{1}; %This gives a struct\nobjective = matRad_DoseOptimizationFunction.createInstanceFromStruct(objective); %Now we turn it into a class\nobjective = objective.setDoseParameters(40); %We can simply call this function to change the/all dose parameter(s)\ncst{ixRectum,6}{1} = struct(objective); % We put it back as struct\n\ncst{ixRectum,6}{1}.parameters{1} = 40;\ncst{ixRectum,6}{1}.penalty = 500;\nresultGUI = matRad_fluenceOptimization(dij,cst,pln);\n[dvh2,qi2] = matRad_indicatorWrapper(cst,pln,resultGUI);\ndisplay(qi2(ixRectum).D_5);\n\n%% Plot the Resulting Dose Slice\n% Let's plot the transversal iso-center dose slice\nslice = round(pln.propStf.isoCenter(1,3)./ct.resolution.z);\nfigure\nimagesc(resultGUI.RBExDose(:,:,slice)),colorbar, colormap(jet)\n\n%%\n% Now let's simulate a range undershoot by scaling the relative stopping power cube by 3.5% percent\nct_manip = ct;\nct_manip.cubeHU{1} = 1.035*ct_manip.cubeHU{1};\n\n%% Recalculate Plan with MC square\n% Let's use the existing optimized pencil beam weights and recalculate the RBE weighted dose\nresultGUI_noise = matRad_calcDoseDirectMC(ct_manip,stf,pln,cst,resultGUI.w);\n\n%% Visual Comparison of results\n% Let's compare the new recalculation against the optimization result.\nplane = 3;\ndoseWindow = [0 max([resultGUI.RBExDose(:); resultGUI_noise.RBExDose(:)])];\n\nfigure,title('original plan')\nmatRad_plotSliceWrapper(gca,ct,cst,1,resultGUI.RBExDose,plane,slice,[],0.75,colorcube,[],doseWindow,[]);\nfigure,title('manipulated plan')\nmatRad_plotSliceWrapper(gca,ct_manip,cst,1,resultGUI_noise.RBExDose,plane,slice,[],0.75,colorcube,[],doseWindow,[]);\n\n% Let's plot single profiles along the beam direction\nixProfileY = round(pln.propStf.isoCenter(1,1)./ct.resolution.x);\n\nprofileOrginal = resultGUI.RBExDose(:,ixProfileY,slice);\nprofileNoise = resultGUI_noise.RBExDose(:,ixProfileY,slice);\n\nfigure,plot(profileOrginal,'LineWidth',2),grid on,hold on, \n plot(profileNoise,'LineWidth',2),legend({'original profile','noise profile'}),\n xlabel('mm'),ylabel('Gy(RBE)'),title('profile plot')\n \n%% Quantitative Comparison of results\n% Compare the two dose cubes using a gamma-index analysis.\n\ndoseDifference = 2;\ndistToAgreement = 2;\nn = 1;\n\n[gammaCube,gammaPassRateCell] = matRad_gammaIndex(...\n resultGUI_noise.RBExDose,resultGUI.RBExDose,...\n [ct.resolution.x, ct.resolution.y, ct.resolution.z],...\n [doseDifference distToAgreement],slice,n,'global',cst);\n\n", "meta": {"author": "e0404", "repo": "matRad", "sha": "0a03aee5ef4a100dbc4bef8927db41b59f44946e", "save_path": "github-repos/MATLAB/e0404-matRad", "path": "github-repos/MATLAB/e0404-matRad/matRad-0a03aee5ef4a100dbc4bef8927db41b59f44946e/examples/matRad_example6_protonsNoise.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6370308082623217, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.31353900591534367}} {"text": "function jed = nyt_to_jed ( volume, issue )\n\n%*****************************************************************************80\n%\n%% NYT_TO_JED converts an NYT date to a JED.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 28 February 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer VOLUME, ISSUE, the New York Times\n% volume and issue.\n%\n% Output, real JED, the Julian Ephemeris Date.\n%\n jed_epoch_50000 = 2449790.5;\n \n if ( 149 < volume )\n\n jed = jed_epoch_50000 + issue - 50000 + 500;\n%\n% Take care of the bizarre case of the second half of Volume 149,\n% Jan 1 2000 to Sep 17 2000, issues 51254 through ?, which were also\n% lowered by 500.\n%\n elseif ( volume == 149 && issue < 51600 )\n jed = jed_epoch_50000 + issue - 50000 + 500;\n elseif ( 44028 <= issue )\n jed = jed_epoch_50000 + issue - 50000;\n%\n% Factor in the strike of 1978.\n%\n else\n jed = jed_epoch_50000 + issue - 50000 - 88;\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/calpak/nyt_to_jed.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.31350102996167467}} {"text": "function [dataout] = ft_eventtiminganalysis(cfg, data)\n\n% FT_EVENTTIMINGANALYSIS computes a model of single trial event-\n% related activity, by estimating per trial the latency (and\n% amplitude) of event-related signal components.\n%\n% Use as\n% [dataout] = ft_eventtiminganalysis(cfg, data)\n% where data is single-channel raw data as obtained by FT_PREPROCESSING\n% and cfg is a configuration structure according to\n%\n% cfg.method = method for estimating event-related activity\n% 'aseo', analysis of single-trial ERP and ongoing\n% activity (according to Xu et al, 2009)\n% 'gbve', graph-based variability estimation\n% (according to Gramfort et al, IEEE TBME 2009)\n% cfg.channel = Nx1 cell-array with selection of channels (default = 'all'),\n% see FT_CHANNELSELECTION for details\n% cfg.trials = 'all' or a selection given as a 1xN vector (default = 'all')\n% cfg.output = 'model', or 'residual', which returns the modelled data,\n% or the residuals.\n%\n% Method specific options are specified in the appropriate substructure.\n%\n% For the ASEO method, the following options can be specified:\n% cfg.aseo.noiseEstimate = 'non-parametric' or 'parametric', estimate noise\n% using parametric or non-parametric (default) method\n% cfg.aseo.tapsmofrq = value, smoothing parameter of noise for\n% nonparametric estimation (default = 5)\n% cfg.aseo.jitter = value, time jitter in initial timewindow\n% estimate (in seconds). default 0.050 seconds\n% cfg.aseo.numiteration = value, number of iteration (default = 1)\n% cfg.aseo.initlatency = Nx2 matrix, initial set of latencies in seconds of event-\n% related components, give as [comp1start, comp1end;\n% comp2start, comp2end] (default not\n% specified). For multiple channels it should\n% be a cell-array, one matrix per channel\n% Alternatively, rather than specifying a (set of latencies), one can also\n% specify:\n%\n% cfg.aseo.initcomp = vector, initial estimate of the waveform\n% components. For multiple channels it should\n% be a cell-array, one matrix per channel.\n%\n% For the GBVE method, the following options can be specified:\n% cfg.gbve.sigma = vector, range of sigma values to explore in \n% cross-validation loop (default: 0.01:0.01:0.2)\n% cfg.gbve.distance = scalar, distance metric to use as\n% evaluation criterion, see plugin code for\n% more informatoin\n% cfg.gbve.alpha = vector, range of alpha values to explor in\n% cross-validation loop (default: [0 0.001 0.01 0.1])\n% cfg.gbve.exponent = scalar, see plugin code for information\n% cfg.gbve.use_maximum = boolean, (default: 1) consider the positive going peak\n% cfg.gbve.show_pca = boolean, see plugin code (default 0)\n% cfg.gbve.show_trial_number = boolean, see plugin code (default 0)\n% cfg.gbve.verbose = boolean (default: 1)\n% cfg.gbve.disp_log = boolean, see plugin code (default 0)\n% cfg.gbve.latency = vector [min max], latency range in s\n% (default: [-inf inf])\n% cfg.gbve.xwin = scalar smoothing parameter for moving\n% average smoothing (default: 1), see\n% eeglab's movav function for more\n% information.\n% \n% To facilitate data-handling and distributed computing you can use\n% cfg.inputfile = ...\n% cfg.outputfile = ...\n% If you specify one of these (or both) the input data will be read from a *.mat\n% file on disk and/or the output data will be written to a *.mat file. These mat\n% files should contain only a single variable, corresponding with the\n% input/output structure.\n%\n% See also FT_SINGLETRIALANALYSIS_ASEO\n\n% Copyright (C) 2018-2019, Jan-Mathijs Schoffelen DCCN\n%\n% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org\n% for the documentation and details.\n%\n% FieldTrip is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% FieldTrip is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with FieldTrip. If not, see .\n%\n% $Id$\n\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 loadvar data\nft_preamble provenance data\nft_preamble trackconfig\n\n% the ft_abort variable is set to true or false in ft_preamble_init\nif ft_abort\n % do not continue function execution in case the outputfile is present and the user indicated to keep it\n return\nend\n\n% ensure that the input data is valid for this function\ndata = ft_checkdata(data, 'datatype', {'raw+comp', 'raw'}, 'feedback', 'yes', 'hassampleinfo', 'yes');\n\n% ensure that the required options are present\ncfg = ft_checkconfig(cfg, 'required', {'method'});\ncfg.trials = ft_getopt(cfg, 'trials', 'all', 1); % all trials as default\ncfg.channel = ft_getopt(cfg, 'channel', 'all');\ncfg.output = ft_getopt(cfg, 'output', 'model');\n% ensure that the options are valid\ncfg = ft_checkopt(cfg, 'method', 'char', {'aseo' 'gbve'});\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% the actual computation is done in the middle part\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% select trials of interest\ntmpcfg = keepfields(cfg, {'trials' 'channel' 'showcallinfo'});\ndata = ft_selectdata(tmpcfg, data);\n% restore the provenance information\n[cfg, data] = rollback_provenance(cfg, data);\n\n% some error checks\nif isfield(data, 'trial') && numel(data.trial)==0, ft_error('no trials were selected'); end\nif numel(data.label)==0, ft_error('no channels were selected'); end\n\nswitch cfg.method \n case 'aseo'\n % define general variables that are used locally\n fsample = data.fsample; % Sampling Frequency in Hz\n nchan = numel(data.label);\n nsample = numel(data.time{1}); %FIXME ASSUMING FIXED TIME AXIS ACROSS ALL TRIALS\n\n % setting a bunch of options, to be passed on to the lower level function\n if ~isfield(cfg, 'aseo'), cfg.aseo = []; end \n cfg.aseo.thresholdAmpH = ft_getopt(cfg.aseo, 'thresholdAmpH', 0.5);\n cfg.aseo.thresholdAmpL = ft_getopt(cfg.aseo, 'thresholdAmpL', 0.1);\n cfg.aseo.thresholdCorr = ft_getopt(cfg.aseo, 'thresholdCorr', 0.2);\n cfg.aseo.maxOrderAR = ft_getopt(cfg.aseo, 'maxOrderAR', 5);\n cfg.aseo.noiseEstimate = ft_getopt(cfg.aseo, 'noiseEstimate', 'nonparametric');\n cfg.aseo.numiteration = ft_getopt(cfg.aseo, 'numiteration', 1);\n cfg.aseo.tapsmofrq = ft_getopt(cfg.aseo, 'tapsmofrq', 5);\n cfg.aseo.fsample = fsample;\n cfg.aseo.nsample = nsample;\n cfg.aseo.pad = ft_getopt(cfg.aseo, 'pad', (2.*nsample)/fsample); \n \n % deal with the different ways with which the initial waveforms can be defined\n initlatency = ft_getopt(cfg.aseo, 'initlatency', {});\n initcomp = ft_getopt(cfg.aseo, 'initcomp', {});\n jitter = ft_getopt(cfg.aseo, 'jitter', 0.050); % half temporal width of shift in s\n \n if isempty(initlatency) && isempty(initcomp)\n ft_error('for the ASEO method you should supply either an initial estimate of the waveform component, or a set of latencies');\n elseif ~isempty(initlatency)\n % this takes precedence, and should contain per channel the begin and\n % end points of the subwindows in time, based on which the initial\n % subcomponents are estimated\n \n % ensure it to be a cell-array if the input is a matrix\n if ~iscell(initlatency)\n initlatency = repmat({initlatency},[1 nchan]);\n end\n make_init = true;\n elseif ~isempty(initcomp)\n % ensure it to be a cell-array if the input is a matrix\n if ~iscell(initcomp)\n initcomp = repmat({initcomp}, [1 nchan]);\n end\n make_init = false;\n end\n \n if make_init\n assert(numel(initlatency)==nchan);\n for k = 1:nchan\n % preprocessing data\n tmp = cellrowselect(data.trial,k);\n chandat = cat(1,tmp{:});\n chandat = ft_preproc_baselinecorrect(chandat, nearest(data.time{1}, -inf), nearest(data.time{1}, 0));\n avgdat = nanmean(chandat, 1);\n \n % set the initial ERP waveforms according to the preset parameters\n ncomp = size(initlatency{k},1);\n initcomp{k} = zeros(nsample, ncomp);\n for m = 1:ncomp\n begsmp = nearest(data.time{1},initlatency{k}(m, 1));\n endsmp = nearest(data.time{1},initlatency{k}(m, 2));\n if begsmp<1, begsmp = 1; end\n if endsmp>nsample, endsmp = nsample; end\n \n tmp = avgdat(begsmp:endsmp)';\n initcomp{k}(begsmp:endsmp, m) = tmp;\n end\n initcomp{k} = initcomp{k} - repmat(mean(initcomp{k}),nsample,1);\n end \n else\n assert(numel(initcomp)==nchan);\n end\n \n if ~iscell(jitter)\n jitter = repmat({jitter}, [1 nchan]);\n end\n \n for k = 1:numel(jitter)\n if ~isempty(jitter{k})\n if size(jitter{k},1)~=size(initcomp{k},2), jitter{k} = repmat(jitter{k}(1,:),[size(initcomp{k},2) 1]); end\n end\n end\n \n % initialize the output data\n dataout = removefields(data, 'cfg');\n for k = 1:numel(data.trial)\n dataout.trial{k}(:) = nan;\n end\n \n % initialize the struct that will contain the output parameters\n params = struct([]);\n \n % do the actual computations\n for k = 1:nchan\n % preprocessing data\n tmp = cellrowselect(data.trial,k);\n chandat = cat(1,tmp{:});\n \n % baseline correction\n chandat = ft_preproc_baselinecorrect(chandat, nearest(data.time{1}, -inf), nearest(data.time{1}, 0));\n \n % do zero-padding and FFT to the signal and initial waveforms\n npad = cfg.aseo.pad*fsample; % length of data + zero-padding number\n nfft = 2.^(ceil(log2(npad)))*2;\n initcomp_fft = fft(initcomp{k}, nfft); % Fourier transform of the initial waveform\n chandat_fft = fft(chandat', nfft); % Fourier transform of the signal\n \n cfg.aseo.jitter = jitter{k};\n output = ft_singletrialanalysis_aseo(cfg, chandat_fft, initcomp_fft);\n \n params(k).latency = output(end).lat_est./fsample;\n params(k).amplitude = output(end).amp_est;\n params(k).components = output(end).erp_est;\n params(k).rejectflag = output(end).rejectflag;\n params(k).noise = output(end).noise;\n \n for m = 1:numel(data.trial)\n if output(end).rejectflag(m)==0\n switch cfg.output\n case 'model'\n dataout.trial{m}(k,:) = data.trial{m}(k,:)-output(end).residual(:,m)';\n case 'residual'\n dataout.trial{m}(k,:) = output(end).residual(:,m)';\n end\n end\n end\n end\n \ncase 'gbve'\n ft_hastoolbox('lagextraction', 1);\n ft_hastoolbox('eeglab', 1); % because the low-level code might use a specific moving average function from EEGLAB\n ft_hastoolbox('cellfunction', 1);\n \n if ~isfield(cfg, 'gbve'), cfg.gbve = []; end\n cfg.gbve.NORMALIZE_DATA = ft_getopt(cfg.gbve, 'NORMALIZE_DATA', true);\n cfg.gbve.CENTER_DATA = ft_getopt(cfg.gbve, 'CENTER_DATA', false);\n cfg.gbve.USE_ADAPTIVE_SIGMA= ft_getopt(cfg.gbve, 'USE_ADAPTIVE_SIGMA', false);\n cfg.gbve.sigma = ft_getopt(cfg.gbve, 'sigma', 0.01:0.01:0.2);\n cfg.gbve.distance = ft_getopt(cfg.gbve, 'distance', 'corr2');\n cfg.gbve.alpha = ft_getopt(cfg.gbve, 'alpha', [0 0.001 0.01 0.1]);\n cfg.gbve.exponent = ft_getopt(cfg.gbve, 'exponent', 1);\n cfg.gbve.use_maximum = ft_getopt(cfg.gbve, 'use_maximum', 1); % consider the positive going peak\n cfg.gbve.show_pca = ft_getopt(cfg.gbve, 'show_pca', false);\n cfg.gbve.show_trial_number = ft_getopt(cfg.gbve, 'show_trial_number', false);\n cfg.gbve.verbose = ft_getopt(cfg.gbve, 'verbose', true);\n cfg.gbve.disp_log = ft_getopt(cfg.gbve, 'disp_log', false);\n cfg.gbve.latency = ft_getopt(cfg.gbve, 'latency', [-inf inf]);\n cfg.gbve.xwin = ft_getopt(cfg.gbve, 'xwin', 1); % default is a bit of smoothing\n \n nchan = numel(data.label);\n ntrl = numel(data.trial);\n \n tmin = nearest(data.time{1}, cfg.gbve.latency(1));\n tmax = nearest(data.time{1}, cfg.gbve.latency(2));\n\n % initialize the struct that will contain the output parameters\n dataout = removefields(data, 'cfg');\n params = struct([]);\n for k = 1:nchan\n % preprocessing data\n options = cfg.gbve;\n \n fprintf('--- Processing channel %d\\n',k);\n \n tmp = cellrowselect(data.trial,k);\n chandat = cat(1,tmp{:});\n points = chandat(:,tmin:tmax);\n \n % perform a loop across alpha values, cross validation\n alphas = options.alpha;\n \n if length(alphas) > 1 % Use Cross validation error if multiple alphas are specified\n best_CVerr = -Inf;\n\n K = 5;\n disp(['--- Running K Cross Validation (K = ',num2str(K),')']);\n\n block_idx = fix(linspace(1, ntrl, K+1)); % K cross validation\n for jj=1:length(alphas)\n options.alpha = alphas(jj);\n\n CVerr = 0;\n for kk = 1:K\n bidx = block_idx(kk):block_idx(kk+1);\n idx = 1:ntrl;\n idx(bidx) = [];\n\n data_k = chandat(idx,:);\n points_k = points(idx,:);\n [order,lags] = extractlag(points_k,options);\n\n data_reordered = data_k(order,:);\n lags = lags + tmin;\n [data_aligned, dum] = perform_realign(data_reordered, data.time{1}, lags);\n data_aligned(~isfinite(data_aligned)) = nan;\n ep_evoked = nanmean(data_aligned);\n ep_evoked = ep_evoked ./ norm(ep_evoked);\n\n data_k = chandat(bidx,:);\n data_norm = sqrt(sum(data_k.^2,2));\n data_k = diag(1./data_norm)*data_k;\n data_k(data_norm==0,:) = 0;\n \n for pp=1:length(bidx)\n c = xcorr(ep_evoked,data_k(pp,:));\n CVerr = CVerr + max(c(:));\n end\n end\n\n CVerr = CVerr/ntrl;\n\n if CVerr > best_CVerr\n best_CVerr = CVerr;\n best_alpha = alphas(jj);\n end\n end\n options.alpha = best_alpha;\n end\n\n if options.use_maximum\n [order,lags] = extractlag( points, options );\n else\n [order,lags] = extractlag( -points, options );\n end\n disp(['---------- Using alpha = ',num2str(options.alpha)]);\n data_reordered = chandat(order,:);\n lags = lags + tmin;\n [data_aligned] = perform_realign(data_reordered, data.time{1}, lags );\n data_aligned(~isfinite(data_aligned)) = nan;\n \n [dum,order_inv] = sort(order);\n lags_no_order = lags(order_inv);\n data_aligned = data_aligned(order_inv,:);\n \n params(k).latency = data.time{1}(lags_no_order)';\n switch cfg.output\n case 'model'\n tmp = mat2cell(data_aligned, ones(1,size(data_aligned,1)), size(data_aligned,2))';\n dataout.trial = cellrowassign(dataout.trial, tmp, k);\n case 'residual'\n % to be done\n error('not yet implemented');\n end\n end\n \nend\n\ndataout.params = params;\ndataout.cfg = cfg;\n\n% do the general cleanup and bookkeeping at the end of the function\nft_postamble debug\nft_postamble trackconfig\nft_postamble previous data\nft_postamble provenance dataout\nft_postamble history dataout\nft_postamble savevar dataout\n\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/external/fieldtrip/ft_eventtiminganalysis.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6513548646660542, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.31296212431481907}} {"text": "function [traj, infStates] = tapas_hhmm(r, p, varargin)\n% Estimates a hierarchical hidden Markov model (HHMM)\n%\n% This function can be called in two ways:\n% \n% (1) hhmm(r, p)\n% \n% where r is the structure generated by fitModel and p is the parameter vector in native space;\n%\n% (2) hhmm(r, ptrans, 'trans')\n% \n% where r is the structure generated by fitModel, ptrans is the parameter vector in\n% transformed space, and 'trans' is a flag indicating this.\n%\n% --------------------------------------------------------------------------------------------------\n% Copyright (C) 2013 Christoph Mathys, TNU, UZH & ETHZ\n%\n% This file is part of the HGF toolbox, which is released under the terms of the GNU General Public\n% Licence (GPL), version 3. You can redistribute it and/or modify it under the terms of the GPL\n% (either version 3 or, at your option, any later version). For further details, see the file\n% COPYING or .\n\n% Transform paramaters back to their native space if needed\nif ~isempty(varargin) && strcmp(varargin{1},'trans');\n [p pstruct] = hhmm_transp(r, p);\nend\n\n% Fixed configuration elements\n%\n% Number of possible outcomes\nm = r.c_prc.n_outcomes;\n\n% Get model tree (N is for node)\nN = pstruct.N;\n\n% Check constraints\nif ~isempty(N{1}.V)\n error('tapas:hgf:hhmm:IllegEntryProbRoot', 'Illegal entry probability for root node.');\nend\n\nfor id = 1:length(N)\n if isempty(N{id}.A) == isempty(N{id}.B)\n error('tapas:hgf:hhmm:IllegCombOfAB', 'Illegal combination of A and B for node no. %d.', id);\n end\n \n if length(N{id}.children(:)) ~= size(N{id}.A,2)\n error('tapas:hgf:hhmm:NumOfChildIncons', 'Number of children inconsistent with A for node no. %d.', id);\n end\n \n if ~isempty(N{id}.A) && any(sum(N{id}.A,2)>1)\n error('tapas:hgf:hhmm:IllegA', 'Illegal transition matrix A for node no. %d: row sums have to be less than or equal to 1.', id);\n end\n \n if ~isempty(N{id}.A)\n for cid = N{id}.children\n cidx = find(N{id}.children==cid);\n if ~isempty(N{cid}.children) && N{id}.A(cidx,cidx) ~= 0\n error('tapas:hgf:hhmm:IllegASelf', 'Illegal transition matrix A for node no. %d: only production nodes may have self-transitions.', id);\n end\n end\n end\n \n if ~isempty(N{id}.B) && sum(N{id}.B(:))~=1\n error('tapas:hgf:hhmm:IllegB', 'Illegal outcome contingency vector B for node no. %d.', id);\n end\n \n if ~isempty(N{id}.children)\n Vsum = 0;\n for cid = N{id}.children\n Vsum = Vsum + N{cid}.V;\n end\n \n if Vsum ~= 1\n error('tapas:hgf:hhmm:IllegV', 'Illegal vertical transition probabilities V from node no. %d.', id);\n end\n end\nend\n\n% Flatten the tree into one large transition matrix\n% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n% Find production nodes\npn = [];\nfor id = 1:length(N)\n if isempty(N{id}.children)\n pn = [pn, id];\n end\nend\nflatDim = length(pn);\n\n% Initialize outcome contingency matrix\nBflat = NaN(m,flatDim);\n\n% Fill Bflat\nfor i = 1:flatDim\n Bflat(:,i) = N{pn(i)}.B';\nend\n\n% Check Bflat\nif any(~isfinite(Bflat(:)))\n error('tapas:hgf:hhmm:NoOutConMat', 'Could not construct outcome contingency matrix.');\nend\n\n% Initialize flattened transitioned matrix\nAflat = NaN(flatDim);\n\n% Fill Aflat\nfor i = 1:flatDim\n for j = 1:flatDim\n if N{pn(i)}.parent == N{pn(j)}.parent\n % If the production nodes are siblings, read out\n % their parent's A matrix\n pid = N{pn(i)}.parent;\n idx = find(N{pid}.children==pn(i));\n jdx = find(N{pid}.children==pn(j));\n Aflat(i,j) = N{pid}.A(idx,jdx);\n else\n % Otherwise, determine their lowest common ancestor\n % and use that to calculate the transition probability\n caid = ca(N,pn(i),pn(j));\n tp = 1;\n\n nid = pn(i);\n pid = N{nid}.parent;\n nidx = find(N{pid}.children==nid);\n\n % Move up to one node below lowest common ancestor from start node pn(i)\n while pid ~= caid\n aend = 1-sum(N{pid}.A(nidx,:));\n tp = tp*aend;\n\n nid = pid;\n pid = N{nid}.parent;\n nidx = find(N{pid}.children==nid);\n end\n\n % Do the horizontal transition to the ancestral line of target node pn(j)\n ancj = anc(N,pn(j));\n while ancj(1) ~= caid\n ancj(1) = [];\n end\n ancj(1) = [];\n\n caidxi = nidx;\n caidxj = find(N{caid}.children==ancj(1));\n tp = tp*N{caid}.A(caidxi,caidxj);\n \n % Go down to the target node pn(j)\n ancj(1) = [];\n while ~isempty(ancj)\n tp = tp*N{ancj(1)}.V;\n ancj(1) = [];\n end\n\n Aflat(i,j) = tp;\n end\n end\nend\n\n% Check Aflat\nif any(~isfinite(Aflat(:)))\n error('tapas:hgf:hhmm:NoFlatTransMat', 'Could not flatten transition matrix.');\nend\n\n% Calculate prior probabilities of production nodes\npnp = NaN(1,flatDim);\nfor i = 1:flatDim\n anci = anc(N,pn(i));\n anci(1) = [];\n p = 1;\n while ~isempty(anci)\n p = p*N{anci(1)}.V;\n anci(1) = [];\n end\n pnp(i) = p;\nend\n\n% Check pnp\nif sum(pnp) ~= 1\n error('tapas:hgf:hhmm:NoPriorProdNodes', 'Cannot calculate prior probabilities of production nodes.');\nend\n\n% Input and number of trials\nu = r.u(:,1);\nn = length(u);\n\n% Initialize alpha-prime\nalpr = NaN(n,flatDim);\n\n% alpr(1,:)\naltmp = pnp.*Bflat(u(1),:);\nllh = sum(altmp);\nalpr(1,:) = altmp./llh;\n\n% Pass through alpha-prime update loop\nfor k = 2:1:n\n if not(ismember(k, r.ign))\n \n %%%%%%%%%%%%%%%%%%%%%%\n % Effect of input u(k)\n %%%%%%%%%%%%%%%%%%%%%%\n \n altmp = Bflat(u(k),:).*(alpr(k-1,:)*Aflat);\n llh = sum(altmp);\n alpr(k,:) = altmp./llh;\n else\n alpr(k,:) = alpr(k-1,:);\n end\nend\n\n% Predicted states\nalprhat = [pnp; alpr];\nalprhat(end,:) = [];\n\n% Create result data structure\ntraj = struct;\n\ntraj.alpr = alpr;\ntraj.alprhat = alprhat;\n\n% Create matrix needed by observation model\ninfStates = traj.alpr;\n\nend % function hhmm\n\n% ----------------------------------------------------------------------------------------\n% Find lowest common ancestor of nodes\nfunction ca = ca(N,ida,idb)\n % Find ancestors of ida and idb\n anca = anc(N,ida);\n ancb = anc(N,idb);\n \n % Determine lowest common ancestor\n ca = NaN;\n aa = anca(1);\n ab = ancb(1);\n while aa == ab && ~isempty(anca) && ~isempty(ancb)\n ca = aa;\n anca(1) = [];\n ancb(1) = [];\n aa = anca(1);\n ab = ancb(1);\n end\n \n if aa == ab\n ca = aa;\n end\nend\n\n% ----------------------------------------------------------------------------------------\n% Find ancestors of a node\nfunction anc = anc(N,id)\n anc = id;\n idt = N{id}.parent;\n while ~isempty(idt)\n anc = [idt, anc];\n idt = N{idt}.parent;\n end\nend\n", "meta": {"author": "translationalneuromodeling", "repo": "tapas", "sha": "604c56843c15411f5bd80190f81d845ac57d8592", "save_path": "github-repos/MATLAB/translationalneuromodeling-tapas", "path": "github-repos/MATLAB/translationalneuromodeling-tapas/tapas-604c56843c15411f5bd80190f81d845ac57d8592/HGF/tapas_hhmm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.672331699179286, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.3125680634325904}} {"text": "% This file is part of TREEQSM.\n%\n% TREEQSM 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% TREEQSM 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 TREEQSM. If not, see .\n\nfunction [Curve,Ind] = boundary_curve(P,Curve0,rball,dmax)\n\n% ---------------------------------------------------------------------\n% BOUNDARY_CURVE.M Determines the boundary curve based on the\n% previously defined boundary curve.\n%\n% Version 1.1.0\n% Latest update 3 May 2022\n%\n% Copyright (C) 2015-2022 Pasi Raumonen\n% ---------------------------------------------------------------------\n%\n% Inputs:\n% P Point cloud of the cross section\n% Curve0 Seed points from previous cross section curve\n% rball Radius of the balls centered at seed points\n% dmax Maximum distance between concecutive curve points, if larger,\n% then create a new one between the points\n% ---------------------------------------------------------------------\n\n% Changes from version 1.0.0 to 1.1.0, 3 May 2022:\n% 1) Increased the cubical neighborhood in the generation of the segments\n\n%% Partition the point cloud into cubes\nMin = double(min([P(:,1:2); Curve0(:,1:2)]));\nMax = double(max([P(:,1:2); Curve0(:,1:2)]));\nN = double(ceil((Max-Min)/rball)+5);\n% cube coordinates of the section points\nCC = floor([P(:,1)-Min(1) P(:,2)-Min(2)]/rball)+3;\n% Sorts the points according a lexicographical order\nS = [CC(:,1) CC(:,2)-1]*[1 N(1)]';\n[S,I] = sort(S);\n% Define \"partition\"\nnp = size(P,1);\npartition = cell(N(1),N(2));\np = 1; % The index of the point under comparison\nwhile p <= np\n t = 1;\n while (p+t <= np) && (S(p) == S(p+t))\n t = t+1;\n end\n q = I(p);\n partition{CC(q,1),CC(q,2)} = I(p:p+t-1);\n p = p+t;\nend\n\n\n%% Define segments using the previous points\n% cube coordinates of the seed points:\nCC = floor([Curve0(:,1)-Min(1) Curve0(:,2)-Min(2)]/rball)+3;\nI = CC < 3;\nCC(I) = 3;\nnc = size(Curve0,1); % number of sets\nDist = 1e8*ones(np,1); % distance of point to the closest center\nSoP = zeros(np,1); % the segment the points belong to\nRadius = rball^2;\nfor i = 1:nc\n points = partition(CC(i,1)-2:CC(i,1)+2,CC(i,2)-2:CC(i,2)+2);\n points = vertcat(points{:});\n V = [P(points,1)-Curve0(i,1) P(points,2)-Curve0(i,2)];\n dist = sum(V.*V,2);\n PointsInBall = dist < Radius;\n points = points(PointsInBall);\n dist = dist(PointsInBall);\n D = Dist(points);\n L = dist < D;\n I = points(L);\n Dist(I) = dist(L);\n SoP(I) = i;\nend\n\n%% Finalise the segments\n% Number of points in each segment and index of each point in its segment\nNum = zeros(nc,1);\nIndPoints = zeros(np,1);\nfor i = 1:np\n if SoP(i) > 0\n Num(SoP(i)) = Num(SoP(i))+1;\n IndPoints(i) = Num(SoP(i));\n end\nend\n% Continue if enough non-emtpy segments\nif nnz(Num) > 0.05*nc\n % Initialization of the \"Seg\"\n Seg = cell(nc,1);\n for i = 1:nc\n Seg{i} = zeros(Num(i),1);\n end\n % Define the \"Seg\"\n for i = 1:np\n if SoP(i) > 0\n Seg{SoP(i),1}(IndPoints(i),1) = i;\n end\n end\n\n %% Define the new curve points as the average of the segments\n Curve = zeros(nc,3); % the new boundary curve\n Empty = false(nc,1);\n for i = 1:nc\n S = Seg{i};\n if ~isempty(S)\n Curve(i,:) = mean(P(S,:),1);\n if norm(Curve(i,:)-Curve0(i,:)) > 1.25*dmax\n Curve(i,:) = Curve0(i,:);\n end\n else\n Empty(i) = true;\n end\n end\n\n %% Interpolate for empty segments\n % For empty segments create points by interpolation from neighboring \n % non-empty segments\n if any(Empty)\n for i = 1:nc\n if Empty(i)\n if i > 1 && i < nc\n k = 0;\n while i+k <= nc && Empty(i+k)\n k = k+1;\n end\n if i+k <= nc\n LineEle = Curve(i+k,:)-Curve(i-1,:);\n else\n LineEle = Curve(1,:)-Curve(i-1,:);\n end\n if k < 5\n for j = 1:k\n Curve(i+j-1,:) = Curve(i-1,:)+j/(k+1)*LineEle;\n end\n else\n Curve(i:i+k-1,:) = Curve0(i:i+k-1,:);\n end\n elseif i == 1\n a = 0;\n while Empty(end-a)\n a = a+1;\n end\n b = 1;\n while Empty(b)\n b = b+1;\n end\n LineEle = Curve(b,:)-Curve(nc-a,:);\n n = a+b-1;\n if n < 5\n for j = 1:a-1\n Curve(nc-a+1+j,:) = Curve(nc-a,:)+j/n*LineEle;\n end\n for j = 1:b-1\n Curve(j,:) = Curve(nc-a,:)+(j+a-1)/n*LineEle;\n end\n else\n Curve(nc-a+2:nc,1:2) = Curve0(nc-a+2:nc,1:2);\n Curve(nc-a+2:nc,3) = Curve0(nc-a+2:nc,3);\n Curve(1:b-1,1:2) = Curve0(1:b-1,1:2);\n Curve(1:b-1,3) = Curve0(1:b-1,3);\n end\n elseif i == nc\n LineEle = Curve(1,:)-Curve(nc-1,:);\n Curve(i,:) = Curve(nc-1,:)+0.5*LineEle;\n end\n end\n end\n end\n\n % Correct the height\n Curve(:,3) = min(Curve(:,3));\n\n % Check self-intersection\n [Intersect,IntersectLines] = check_self_intersection(Curve(:,1:2));\n\n % If self-intersection, try to modify the curve\n j = 1;\n while Intersect && j <= 5\n n = size(Curve,1);\n InterLines = (1:1:n)';\n NumberOfIntersections = cellfun('length',IntersectLines(:,1));\n I = NumberOfIntersections > 0;\n InterLines = InterLines(I);\n CrossLen = vertcat(IntersectLines{I,2});\n if length(CrossLen) == length(InterLines)\n LineEle = Curve([2:end 1],:)-Curve(1:end,:);\n d = sqrt(sum(LineEle.*LineEle,2));\n m = length(InterLines);\n for i = 1:2:m\n if InterLines(i) ~= n\n Curve(InterLines(i)+1,:) = Curve(InterLines(i),:)+...\n 0.9*CrossLen(i)/d(InterLines(i))*LineEle(InterLines(i),:);\n else\n Curve(1,:) = Curve(InterLines(i),:)+...\n 0.9*CrossLen(i)/d(InterLines(i))*LineEle(InterLines(i),:);\n end\n end\n [Intersect,IntersectLines] = check_self_intersection(Curve(:,1:2));\n j = j+1;\n else\n j = 6;\n end\n end\n\n %% Add new points if too large distances\n LineEle = Curve([2:end 1],:)-Curve(1:end,:);\n d = sum(LineEle.*LineEle,2);\n Large = d > dmax^2;\n m = nnz(Large);\n if m > 0\n Curve0 = zeros(nc+m,3);\n Ind = zeros(nc+m,2);\n t = 0;\n for i = 1:nc\n if Large(i)\n t = t+1;\n Curve0(t,:) = Curve(i,:);\n if i < nc\n Ind(t,:) = [i i+1];\n else\n Ind(t,:) = [i 1];\n end\n t = t+1;\n Curve0(t,:) = Curve(i,:)+0.5*LineEle(i,:);\n if i < nc\n Ind(t,:) = [i+1 0];\n else\n Ind(t,:) = [1 0];\n end\n else\n t = t+1;\n Curve0(t,:) = Curve(i,:);\n if i < nc\n Ind(t,:) = [i i+1];\n else\n Ind(t,:) = [i 1];\n end\n end\n end\n Curve = Curve0;\n\n else\n Ind = [(1:1:nc)' [(2:1:nc)'; 1]];\n end\n\n\n %% Remove new points if too small distances\n nc = size(Curve,1);\n LineEle = Curve([2:end 1],:)-Curve(1:end,:);\n d = sum(LineEle.*LineEle,2);\n Small = d < (0.333*dmax)^2;\n m = nnz(Small);\n if m > 0\n for i = 1:nc-1\n if ~Small(i) && Small(i+1)\n Ind(i,2) = -1;\n elseif Small(i) && Small(i+1)\n Small(i+1) = false;\n end\n end\n if ~Small(nc) && Small(1)\n Ind(nc,2) = -1;\n Ind(1,2) = -1;\n Small(1) = false;\n Small(nc) = true;\n I = Ind(:,2) > 0;\n Ind(2:end,1) = Ind(2:end,1)+1;\n Ind(I,2) = Ind(I,2)+1;\n\n end\n Ind = Ind(~Small,:);\n Curve = Curve(~Small,:);\n end\n\nelse\n % If not enough new points, return the old curve\n Ind = [(1:1:nc)' [(2:1:nc)'; 1]];\n Curve = Curve0;\nend\n", "meta": {"author": "InverseTampere", "repo": "TreeQSM", "sha": "6630bbf516f8b53adb7d60a2cccbd21e6fe51226", "save_path": "github-repos/MATLAB/InverseTampere-TreeQSM", "path": "github-repos/MATLAB/InverseTampere-TreeQSM/TreeQSM-6630bbf516f8b53adb7d60a2cccbd21e6fe51226/src/triangulation/boundary_curve.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.3125228910109688}} {"text": "function q = conjexp(p)\n\n% conjexp\n%\n% 1/p+1/q=1\n\n\nq = p/(p-1);\nif p==1\n q = Inf;\nend\nif p==Inf\n q = p;\nend\n\nend", "meta": {"author": "optimaltransport", "repo": "optimaltransport.github.io", "sha": "2fa6db6e6a48ab9bd6676088db00bd7c5c8b4203", "save_path": "github-repos/MATLAB/optimaltransport-optimaltransport.github.io", "path": "github-repos/MATLAB/optimaltransport-optimaltransport.github.io/optimaltransport.github.io-2fa6db6e6a48ab9bd6676088db00bd7c5c8b4203/code/gradflow-metric/conjexp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5926665855647394, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.31252288342323714}} {"text": "function y = abs( x )\n\n%Disciplined convex/geometric programming information for ABS:\n% ABS(X) is convex and nonmonotonic in X. Therefore, when used in\n% DCPs, X must be affine. ABS(X) is not useful in DGPs, since all\n% log-convex and log-concave expressions are already positive.\n\n%\n% Determine the expression types\n%\n\n% 0 : convex, concave, invalid\n% 1 : constant\n% 2 : real affine\n% 3 : complex affine\npersistent remap\nif isempty( remap ),\n remap_1 = cvx_remap( 'constant' );\n remap_2 = cvx_remap( 'real-affine' );\n remap_3 = cvx_remap( 'complex-affine' );\n remap_4 = cvx_remap( 'log-valid' );\n remap = remap_1 + ( 2 * remap_2 + 3 * remap_3 + 4 * remap_4 ) .* ~remap_1;\nend\nv = remap( cvx_classify( x ) );\n\n%\n% Process each type of expression one piece at a time\n%\n\nvu = sort( v(:) );\nvu = vu([true;diff(vu)~=0]);\nnv = length( vu );\nsx = x.size_;\nif nv ~= 1,\n y = cvx( sx, [] );\nend\nfor k = 1 : nv,\n\n %\n % Select the category of expression to compute\n %\n\n vk = vu( k );\n if nv == 1,\n xt = x;\n else\n t = v == vk;\n xt = cvx_subsref( x, t );\n end\n\n %\n % Perform the computations\n %\n\n switch vk,\n case 0,\n % Invalid\n error( 'Disciplined convex programming error:\\n Illegal operation: abs( {%s} ).', cvx_class( xt ) );\n case 1,\n % Constant\n cvx_optval = cvx( builtin( 'abs', cvx_constant( xt ) ) );\n case 2,\n % Real affine\n w = [];\n st = size( xt );\n cvx_begin\n epigraph variable w( st )\n { xt, w } == lorentz( st, 0 ); %#ok\n cvx_end\n case 3,\n % Complex affine\n w = [];\n st = size( xt );\n cvx_begin\n epigraph variable w( st )\n { xt, w } == complex_lorentz( st, 0 ); %#ok\n cvx_end\n case 4,\n % log-affine, log-convex\n cvx_optval = xt;\n otherwise,\n error( 'Shouldn''t be here.' );\n end\n\n %\n % Store the results\n %\n\n if nv == 1,\n y = cvx_optval;\n else\n y = cvx_subsasgn( y, t, cvx_optval );\n end\n\nend\n\n% Copyright 2005-2016 CVX Research, Inc.\n% See the file LICENSE.txt for full copyright information.\n% The command 'cvx_where' will show where this file is located.\n", "meta": {"author": "cvxr", "repo": "CVX", "sha": "a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd", "save_path": "github-repos/MATLAB/cvxr-CVX", "path": "github-repos/MATLAB/cvxr-CVX/CVX-a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd/builtins/@cvx/abs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6548947155710233, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.31210949503028357}} {"text": "function [isih] = ft_spike_isi(cfg, spike)\n\n% FT_SPIKE_ISI computes the interspike interval histogram\n%\n% The input SPIKE should be organised as\n% a) the spike datatype, obtained from FT_SPIKE_MAKETRIALS\n% b) the raw datatype, containing binary spike trains, obtained from\n% FT_APPENDSPIKE or FT_CHECKDATA. In this case the raw datatype is\n% converted to the spike datatype.\n%\n% Use as\n% [isih] = ft_spike_isi(cfg, spike)\n%\n% Configurations:\n% cfg.outputunit = 'spikecount' (default) or 'proportion' (sum of all bins = 1).\n% cfg.spikechannel = string or index of spike channels to\n% trigger on (default = 'all')\n% See FT_CHANNELSELECTION for details.\n% cfg.trials = numeric selection of trials (default = 'all')\n% cfg.bins = ascending vector of isi bin edges.\n% cfg.latency = [begin end] in seconds, 'max' (default), 'min', 'prestim'(t<=0), or\n% 'poststim' (t>=0).\n% If 'max', we use all available latencies.\n% If 'min', we use only the time window contained by all trials.\n% If 'prestim' or 'poststim', we use time to or\n% from 0, respectively.\n%` cfg.keeptrials = 'yes' or 'no'. If 'yes', we keep the individual\n% isis between spikes and output as isih.isi\n% cfg.param = string, one of\n% 'gamfit' : returns [shape scale] for gamma distribution fit\n% 'coeffvar' : coefficient of variation (sd / mean)\n% 'lv' : Shinomoto's Local Variation measure (2009)\n%\n% Outputs:\n% isih.avg = nUnits-by-nBins interspike interval histogram\n% isih.time = 1 x nBins bincenters corresponding to isih.avg\n% isih.isi = 1-by-nUnits cell with interval to previous spike per spike.\n% For example isih.isi{1}(2) = 0.1 means that the\n% second spike fired was 0.1 s later than the\n% first. Note that jumps within trials or first\n% spikes within trials are given NaNs.\n% isih.label = 1-by-nUnits cell-array with labels\n\n% Copyright (C) 2010-2012, Martin Vinck\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% 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 provenance spike\n\n\n% check if data is of proper format\nspike = ft_checkdata(spike,'datatype', 'spike', 'feedback', 'yes');\n\n% get the default options\ncfg.outputunit = ft_getopt(cfg,'outputunit','spikecount');\ncfg.spikechannel = ft_getopt(cfg,'spikechannel', 'all');\ncfg.trials = ft_getopt(cfg,'trials', 'all');\ncfg.latency = ft_getopt(cfg,'latency','maxperiod');\ncfg.keeptrials = ft_getopt(cfg,'keeptrials', 'yes');\ncfg.bins = ft_getopt(cfg,'bins', 0:0.002:1);\ncfg.param = ft_getopt(cfg,'param', 'coeffvar');\n\n% ensure that the options are valid\ncfg = ft_checkopt(cfg,'outputunit','char', {'spikecount', 'proportion'});\ncfg = ft_checkopt(cfg,'bins', 'ascendingdoublevector');\ncfg = ft_checkopt(cfg,'spikechannel',{'cell', 'char', 'double'});\ncfg = ft_checkopt(cfg,'latency', {'char', 'ascendingdoublebivector'});\ncfg = ft_checkopt(cfg,'trials', {'char', 'doublevector', 'logical'});\ncfg = ft_checkopt(cfg,'keeptrials', 'char', {'yes', 'no'});\ncfg = ft_checkopt(cfg,'param', 'char', {'gamfit', 'coeffvar', 'lv'});\n\ncfg = ft_checkconfig(cfg, 'allowed', {'param', 'outputunit', 'bins', 'spikechannel', 'latency', 'trials', 'keeptrials'});\n\n% get the number of trials or change DATA according to cfg.trials\nif strcmp(cfg.trials,'all')\n cfg.trials = 1:size(spike.trialtime,1);\nelseif islogical(cfg.trials) || all(cfg.trials==0 | cfg.trials==1)\n cfg.trials = find(cfg.trials);\nend\ncfg.trials = sort(cfg.trials);\n\ncfg.channel = ft_channelselection(cfg.spikechannel, spike.label);\nspikesel = match_str(spike.label, cfg.channel);\nnUnits = length(spikesel); % number of spike channels\nif nUnits==0, error('No spikechannel selected by means of cfg.spikechannel'); end\n\n% determine the duration of each trial\nbegTrialLatency = spike.trialtime(cfg.trials,1);\nendTrialLatency = spike.trialtime(cfg.trials,2);\n\n% select the latencies\nif strcmp(cfg.latency,'minperiod')\n cfg.latency = [max(begTriallatency) min(endTriallatency)];\nelseif strcmp(cfg.latency,'maxperiod')\n cfg.latency = [min(begTrialLatency) max(endTrialLatency)];\nelseif strcmp(cfg.latency,'prestim')\n cfg.latency = [min(begTrialLatency) 0];\nelseif strcmp(cfg.latency,'poststim')\n cfg.latency = [0 max(endTrialLatency)];\nend\n\n% construct the isi bins\nbins = cfg.bins;\nnBins = length(bins)-1;\n\n% compute the interspike interval\nkeepTrials = strcmp(cfg.keeptrials,'yes');\nif keepTrials, isiSpike = cell(1,nUnits); end % contains the individual histogram spike times\nisihist = zeros(nUnits,nBins+1); % isi histogram\nout = [];\nfor iUnit = 1:nUnits\n unitIndx = spikesel(iUnit);\n \n % only select the spikes in the right latencies and trials\n spikeTrials = spike.trial{unitIndx}(:)'; % ensure row vector\n spikeTimes = spike.time{unitIndx}(:)'; % ensure row vector\n \n % select only the spikes in the window and with the selected trials\n spikesInTrials = ismember(spikeTrials, cfg.trials); % row vec\n spikesInWin = spikeTimes>=cfg.latency(1)&spikeTimes<=cfg.latency(2); % row vec\n spikeTimes = spikeTimes(spikesInTrials & spikesInWin);\n spikeTrials = spikeTrials(spikesInTrials & spikesInWin);\n \n % find the spikes that jumped to the next trial, replace them with NaNs\n trialJump = logical([1 diff(spikeTrials(:)')]);\n isi = [NaN diff(spikeTimes(:)')];\n isi(trialJump) = NaN;\n \n switch cfg.param\n case 'coeffvar'\n out(iUnit) = nanstd(isi)./nanmean(isi);\n case 'gamfit'\n data = isi(~isnan(isi)); % remove the nans from isiSpike\n if ~isempty(data)\n [out(iUnit,:)] = mle(data,'distribution', 'gamma'); % fit a gamma distribution\n else\n out(iUnit,:) = [NaN NaN];\n end\n case 'lv'\n dIsi = isi(1:end-1) - isi(2:end);\n sumIsi = isi(1:end-1) + isi(2:end);\n sl = ~isnan(dIsi) & ~isnan(sumIsi); % remove if one has nan\n df = sum(sl) - 1;\n out(iUnit) = (3/df)*sum((dIsi(sl)./sumIsi(sl)).^2);\n end\n\n % convert and store the isi\n if keepTrials, isiSpike{iUnit} = isi; end\n isihist(iUnit,:) = histc(isi,bins);\nend\n\nisihist(:,end) = []; % the last number is only an equality to a bin edge\nif strcmp(cfg.outputunit,'proportion')\n isihist = isihist./repmat(nansum(isihist,2),1,size(isihist,2));\nend\n\n% gather the rest of the results\nif strcmp(cfg.keeptrials,'yes'), isih.isi = isiSpike; end\nisih.time = bins(1:end-1);\nisih.avg = isihist;\nisih.dimord = 'chan_time';\nisih.label = spike.label(spikesel);\nparam = cfg.param;\nisih.(param) = out;\n\n% do the general cleanup and bookkeeping at the end of the function\n\nft_postamble previous spike\nft_postamble provenance isih\nft_postamble history isih\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/contrib/spike/ft_spike_isi.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6187804337438502, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.31180727876618697}} {"text": "function [ node_xyz, tet_node ] = tet_mesh_order4_example_set ( node_num, ...\n tet_num )\n\n%*****************************************************************************80\n%\n%% TET_MESH_ORDER4_EXAMPLE_SET sets an example linear tet mesh.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 19 August 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer NODE_NUM, the number of nodes.\n%\n% Input, integer TET_NUM, the number of tetrahedrons.\n%\n% Output, real NODE_XYZ(3,NODE_NUM), the node coordinates.\n%\n% Output, integer TET_NODE(4,TET_NUM), the nodes \n% forming each tet.\n%\n tet_node(1:4,1:tet_num) = [ ...\n 1, 2, 4, 10; ...\n 2, 4, 5, 10; ...\n 2, 5, 10, 11; ...\n 2, 3, 5, 11; ...\n 4, 5, 10, 13; ...\n 3, 5, 6, 11; ...\n 5, 10, 11, 13; ...\n 4, 5, 7, 13; ...\n 5, 6, 8, 14; ...\n 5, 7, 8, 13; ...\n 6, 8, 9, 14; ...\n 11, 13, 14, 19; ...\n 12, 14, 15, 20; ...\n 3, 6, 11, 12; ...\n 5, 6, 11, 14; ...\n 6, 9, 14, 15; ...\n 6, 11, 12, 14; ...\n 6, 12, 14, 15; ...\n 7, 8, 13, 16; ...\n 5, 8, 13, 14; ...\n 10, 11, 13, 19; ...\n 8, 9, 14, 17; ...\n 11, 12, 14, 20; ...\n 5, 11, 13, 14; ...\n 8, 13, 14, 16; ...\n 9, 14, 15, 17; ...\n 13, 14, 16, 22; ...\n 8, 14, 16, 17; ...\n 14, 15, 17, 23; ...\n 14, 16, 17, 22; ...\n 9, 15, 17, 18; ...\n 15, 17, 18, 23; ...\n 14, 17, 22, 23; ...\n 13, 14, 19, 22; ...\n 11, 14, 19, 20; ...\n 14, 15, 20, 23; ...\n 15, 20, 21, 23; ...\n 21, 23, 24, 29; ...\n 20, 22, 23, 28; ...\n 14, 19, 20, 22; ...\n 15, 18, 23, 24; ...\n 12, 15, 20, 21; ...\n 15, 21, 23, 24; ...\n 16, 17, 22, 25; ...\n 19, 20, 22, 28; ...\n 17, 18, 23, 26; ...\n 20, 21, 23, 29; ...\n 14, 20, 22, 23; ...\n 17, 22, 23, 25; ...\n 18, 23, 24, 26; ...\n 22, 23, 25, 31; ...\n 17, 23, 25, 26; ...\n 23, 24, 26, 32; ...\n 23, 25, 26, 31; ...\n 18, 24, 26, 27; ...\n 24, 26, 27, 32; ...\n 23, 26, 31, 32; ...\n 22, 23, 28, 31; ...\n 20, 23, 28, 29; ...\n 23, 24, 29, 32; ...\n 24, 29, 30, 32; ...\n 30, 32, 33, 38; ...\n 29, 31, 32, 37; ...\n 23, 28, 29, 31; ...\n 24, 27, 32, 33; ...\n 21, 24, 29, 30; ...\n 24, 30, 32, 33; ...\n 25, 26, 31, 34; ...\n 28, 29, 31, 37; ...\n 26, 27, 32, 35; ...\n 29, 30, 32, 38; ...\n 23, 29, 31, 32; ...\n 26, 31, 32, 34; ...\n 27, 32, 33, 35; ...\n 31, 32, 34, 40; ...\n 26, 32, 34, 35; ...\n 32, 33, 35, 41; ...\n 32, 34, 35, 40; ...\n 27, 33, 35, 36; ...\n 33, 35, 36, 41; ...\n 32, 35, 40, 41; ...\n 31, 32, 37, 40; ...\n 29, 32, 37, 38; ...\n 32, 33, 38, 41; ...\n 33, 38, 39, 41; ...\n 39, 41, 42, 47; ...\n 38, 40, 41, 46; ...\n 32, 37, 38, 40; ...\n 33, 36, 41, 42; ...\n 30, 33, 38, 39; ...\n 33, 39, 41, 42; ...\n 34, 35, 40, 43; ...\n 37, 38, 40, 46; ...\n 35, 36, 41, 44; ...\n 38, 39, 41, 47; ...\n 32, 38, 40, 41; ...\n 35, 40, 41, 43; ...\n 36, 41, 42, 44; ...\n 40, 41, 43, 49; ...\n 35, 41, 43, 44; ...\n 41, 42, 44, 50; ...\n 41, 43, 44, 49; ...\n 36, 42, 44, 45; ...\n 42, 44, 45, 50; ...\n 41, 44, 49, 50; ...\n 40, 41, 46, 49; ...\n 38, 41, 46, 47; ...\n 41, 42, 47, 50; ...\n 42, 47, 48, 50; ...\n 48, 50, 51, 56; ...\n 47, 49, 50, 55; ...\n 41, 46, 47, 49; ...\n 42, 45, 50, 51; ...\n 39, 42, 47, 48; ...\n 42, 48, 50, 51; ...\n 43, 44, 49, 52; ...\n 46, 47, 49, 55; ...\n 44, 45, 50, 53; ...\n 47, 48, 50, 56; ...\n 41, 47, 49, 50; ...\n 44, 49, 50, 52; ...\n 45, 50, 51, 53; ...\n 49, 50, 52, 58; ...\n 44, 50, 52, 53; ...\n 50, 51, 53, 59; ...\n 50, 52, 53, 58; ...\n 45, 51, 53, 54; ...\n 51, 53, 54, 59; ...\n 50, 53, 58, 59; ...\n 49, 50, 55, 58; ...\n 47, 50, 55, 56; ...\n 50, 51, 56, 59; ...\n 51, 56, 57, 59; ...\n 50, 55, 56, 58; ...\n 51, 54, 59, 60; ...\n 48, 51, 56, 57; ...\n 51, 57, 59, 60; ...\n 52, 53, 58, 61; ...\n 53, 54, 59, 62; ...\n 50, 56, 58, 59; ...\n 53, 58, 59, 61; ...\n 54, 59, 60, 62; ...\n 53, 59, 61, 62; ...\n 54, 60, 62, 63 ]';\n\n node_xyz(1:3,1:node_num) = [ ...\n 0.0, 0.0, 0.0; ...\n 0.0, 0.0, 0.5; ...\n 0.0, 0.0, 1.0; ...\n 0.0, 0.5, 0.0; ...\n 0.0, 0.5, 0.5; ...\n 0.0, 0.5, 1.0; ...\n 0.0, 1.0, 0.0; ...\n 0.0, 1.0, 0.5; ...\n 0.0, 1.0, 1.0; ...\n 0.5, 0.0, 0.0; ...\n 0.5, 0.0, 0.5; ...\n 0.5, 0.0, 1.0; ...\n 0.5, 0.5, 0.0; ...\n 0.5, 0.5, 0.5; ...\n 0.5, 0.5, 1.0; ...\n 0.5, 1.0, 0.0; ...\n 0.5, 1.0, 0.5; ...\n 0.5, 1.0, 1.0; ...\n 1.0, 0.0, 0.0; ...\n 1.0, 0.0, 0.5; ...\n 1.0, 0.0, 1.0; ...\n 1.0, 0.5, 0.0; ...\n 1.0, 0.5, 0.5; ...\n 1.0, 0.5, 1.0; ...\n 1.0, 1.0, 0.0; ...\n 1.0, 1.0, 0.5; ...\n 1.0, 1.0, 1.0; ...\n 1.5, 0.0, 0.0; ...\n 1.5, 0.0, 0.5; ...\n 1.5, 0.0, 1.0; ...\n 1.5, 0.5, 0.0; ...\n 1.5, 0.5, 0.5; ...\n 1.5, 0.5, 1.0; ...\n 1.5, 1.0, 0.0; ...\n 1.5, 1.0, 0.5; ...\n 1.5, 1.0, 1.0; ...\n 2.0, 0.0, 0.0; ...\n 2.0, 0.0, 0.5; ...\n 2.0, 0.0, 1.0; ...\n 2.0, 0.5, 0.0; ...\n 2.0, 0.5, 0.5; ...\n 2.0, 0.5, 1.0; ...\n 2.0, 1.0, 0.0; ...\n 2.0, 1.0, 0.5; ...\n 2.0, 1.0, 1.0; ...\n 2.5, 0.0, 0.0; ...\n 2.5, 0.0, 0.5; ...\n 2.5, 0.0, 1.0; ...\n 2.5, 0.5, 0.0; ...\n 2.5, 0.5, 0.5; ...\n 2.5, 0.5, 1.0; ...\n 2.5, 1.0, 0.0; ...\n 2.5, 1.0, 0.5; ...\n 2.5, 1.0, 1.0; ...\n 3.0, 0.0, 0.0; ...\n 3.0, 0.0, 0.5; ...\n 3.0, 0.0, 1.0; ...\n 3.0, 0.5, 0.0; ...\n 3.0, 0.5, 0.5; ...\n 3.0, 0.5, 1.0; ...\n 3.0, 1.0, 0.0; ...\n 3.0, 1.0, 0.5; ...\n 3.0, 1.0, 1.0 ]';\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/tet_mesh/tet_mesh_order4_example_set.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6076631840431539, "lm_q2_score": 0.5117166047041652, "lm_q1q2_score": 0.31095134134228497}} {"text": "function y = abs( x )\n\n%Disciplined convex/geometric programming information for ABS:\n% ABS(X) is convex and nonmonotonic in X. Therefore, when used in\n% DCPs, X must be affine. ABS(X) is not useful in DGPs, since all\n% log-convex and log-concave expressions are already positive.\n\n%\n% Determine the expression types\n%\n\n% 0 : convex, concave, invalid\n% 1 : constant\n% 2 : real affine\n% 3 : complex affine\npersistent remap\nif isempty( remap ),\n remap_1 = cvx_remap( 'constant' );\n remap_2 = cvx_remap( 'real-affine' );\n remap_3 = cvx_remap( 'complex-affine' );\n remap_4 = cvx_remap( 'log-valid' );\n remap = remap_1 + ( 2 * remap_2 + 3 * remap_3 + 4 * remap_4 ) .* ~remap_1;\nend\nv = remap( cvx_classify( x ) );\n\n%\n% Process each type of expression one piece at a time\n%\n\nvu = sort( v(:) );\nvu = vu([true;diff(vu)~=0]);\nnv = length( vu );\nsx = x.size_;\nif nv ~= 1,\n y = cvx( sx, [] );\nend\nfor k = 1 : nv,\n\n %\n % Select the category of expression to compute\n %\n\n vk = vu( k );\n if nv == 1,\n xt = x;\n else\n t = v == vk;\n xt = cvx_subsref( x, t );\n end\n\n %\n % Perform the computations\n %\n\n switch vk,\n case 0,\n % Invalid\n error( 'Disciplined convex programming error:\\n Illegal operation: abs( {%s} ).', cvx_class( xt ) );\n case 1,\n % Constant\n cvx_optval = cvx( builtin( 'abs', cvx_constant( xt ) ) );\n case 2,\n % Real affine\n st = size( xt );\n cvx_begin\n epigraph variable w( st )\n { xt, w } == lorentz( st, 0 );\n cvx_end\n case 3,\n % Complex affine\n st = size( xt );\n cvx_begin\n epigraph variable w( st )\n { xt, w } == complex_lorentz( st, 0 );\n cvx_end\n case 4,\n % log-affine, log-convex\n cvx_optval = xt;\n otherwise,\n error( 'Shouldn''t be here.' );\n end\n\n %\n % Store the results\n %\n\n if nv == 1,\n y = cvx_optval;\n else\n y = cvx_subsasgn( y, t, cvx_optval );\n end\n\nend\n\n% Copyright 2010 Michael C. Grant and Stephen P. Boyd.\n% See the file COPYING.txt for full copyright information.\n% The command 'cvx_where' will show where this file is located.\n", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/dependencies/cvx-1.21.b795/builtins/@cvx/abs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6859494421679929, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.31091471180218766}} {"text": "%\n% Original source\n% http://www.mat.univie.ac.at/~neum/glopt/coconut/Benchmark/Library1/alkyl.mod\n%\nfunction test_alkyl\n \n addpath('../lib') ;\n\n auxdata = {} ;\n options.lb = [ 0, 0, 0, 0, 0, 0.85, 0.9, 3, 1.2, 1.45, 0.99, 0.99, 0.9, 0.99 ] ;\n options.ub = [ 2, 1.6, 1.2, 5, 2, 0.93, 0.95, 12, 4, 1.62, 1.01010101010101, 1.01010101010101, 1.11111111111111, 1.01010101010101 ] ;\n\n % The constraint functions are bounded to zero\n options.cl = zeros(1,7); % constraints\n options.cu = zeros(1,7);\n \n % Set up the auxiliary data.\n options.auxdata = auxdata ;\n \n % Set the IPOPT options.\n options.ipopt.jac_d_constant = 'no';\n options.ipopt.hessian_constant = 'no';\n options.ipopt.mu_strategy = 'adaptive';\n options.ipopt.max_iter = 400;\n options.ipopt.tol = 1e-10;\n options.ipopt.linear_solver = 'ma57';\n %options.ipopt.linear_solver = 'mumps';\n %options.ipopt.linear_solver = 'pardiso';\n \n % The callback functions.\n funcs.objective = @objective;\n funcs.constraints = @constraints;\n funcs.gradient = @gradient;\n funcs.jacobian = @jacobian;\n funcs.jacobianstructure = @jacobianstructure;\n if true\n funcs.hessian = @hessian;\n funcs.hessianstructure = @hessianstructure;\n options.ipopt.derivative_test = 'second-order';\n else\n options.ipopt.hessian_approximation = 'limited-memory';\n options.ipopt.limited_memory_update_type = 'bfgs' ; % {bfgs}, sr1 = 6; % {6}\n options.ipopt.derivative_test = 'first-order';\n end\n\n % Run IPOPT.\n x0 = [ 1.745, ...\n 1.2, ...\n 1.1, ...\n 3.048, ...\n 1.974, ...\n 0.893, ...\n 0.928, ...\n 8, ...\n 3.6, ...\n 1.45, ...\n 1, ...\n 1, ...\n 1, ...\n 1 ] ; \n\n tic\n [x, info] = ipopt_auxdata(x0,funcs,options);\n elapsed = toc ;\n\n info;\n\n x\n\nend\n\n%%\n% map the indices with the corresponding index in the spase matrix\nfunction f = objective( x, auxdata )\n x2 = x(1) ;\n x3 = x(2) ;\n x4 = x(3) ;\n x5 = x(4) ;\n x6 = x(5) ;\n x7 = x(6) ;\n x8 = x(7) ;\n x9 = x(8) ;\n x10 = x(9) ;\n x11 = x(10) ;\n x12 = x(11) ;\n x13 = x(12) ;\n x14 = x(13) ;\n x15 = x(14) ;\n f = - 6.3*x5*x8 + 5.04*x2 + 0.35*x3 + x4 + 3.36*x6 ;\nend\n\n%% \n% map the indices with the corresponding index in the spase matrix\nfunction g = gradient(x,auxdata)\n x2 = x(1) ;\n x3 = x(2) ;\n x4 = x(3) ;\n x5 = x(4) ;\n x6 = x(5) ;\n x7 = x(6) ;\n x8 = x(7) ;\n x9 = x(8) ;\n x10 = x(9) ;\n x11 = x(10) ;\n x12 = x(11) ;\n x13 = x(12) ;\n x14 = x(13) ;\n x15 = x(14) ;\n g = [ 5.04, 0.35, 1, -6.3*x8, 3.36, 0, -6.3*x5, 0, 0, 0, 0, 0, 0, 0 ] ;\nend\n\nfunction c = constraints(x,auxdata)\n x2 = x(1) ;\n x3 = x(2) ;\n x4 = x(3) ;\n x5 = x(4) ;\n x6 = x(5) ;\n x7 = x(6) ;\n x8 = x(7) ;\n x9 = x(8) ;\n x10 = x(9) ;\n x11 = x(10) ;\n x12 = x(11) ;\n x13 = x(12) ;\n x14 = x(13) ;\n x15 = x(14) ;\n e2 = - 0.819672131147541*x2 + x5 - 0.819672131147541*x6 ;\n e3 = 0.98*x4 - x7*(0.01*x5*x10 + x4) ;\n e4 = - x2*x9 + 10*x3 + x6 ;\n e5 = x5*x12 - x2*(1.12 + 0.13167*x9 - 0.0067*x9*x9) ;\n e6 = x8*x13 - 0.01*(1.098*x9 - 0.038*x9*x9) - 0.325*x7 - 0.57425;\n e7 = x10*x14 + 22.2*x11 - 35.82;\n e8 = x11*x15 - 3*x8 + 1.33 ;\n c = [e2;e3;e4;e5;e6;e7;e8] ;\nend\n\nfunction jac = jacobian(x,auxdata)\n x2 = x(1) ;\n x3 = x(2) ;\n x4 = x(3) ;\n x5 = x(4) ;\n x6 = x(5) ;\n x7 = x(6) ;\n x8 = x(7) ;\n x9 = x(8) ;\n x10 = x(9) ;\n x11 = x(10) ;\n x12 = x(11) ;\n x13 = x(12) ;\n x14 = x(13) ;\n x15 = x(14) ;\n\n jac = sparse(7,14) ;\n \n jac(1,1) = -0.819672131147541 ;\n jac(1,4) = 1 ;\n jac(1,5) = -0.819672131147541 ;\n \n jac(2,3) = 0.98 - x7 ;\n jac(2,4) = -x7*(0.01*x10);\n jac(2,6) = -(0.01*x5*x10 + x4);\n jac(2,9) = - x7*(0.01*x5);\n \n jac(3,1) = -x9 ;\n jac(3,2) = 10 ;\n jac(3,5) = 1 ;\n jac(3,8) = -x2 ;\n\n jac(4,1) = -(1.12 + 0.13167*x9 - 0.0067*x9*x9) ;\n jac(4,4) = x12 ;\n jac(4,8) = -x2*(0.13167 - 2*0.0067*x9) ;\n jac(4,11) = x5 ;\n\n jac(5,6) = -0.325;\n jac(5,7) = x13 ;\n jac(5,8) = - 0.01*(1.098 - 2*0.038*x9) ;\n jac(5,12) = x8 ;\n\n jac(6,9) = x14;\n jac(6,10) = 22.2;\n jac(6,13) = x10;\n\n jac(7,7) = -3 ;\n jac(7,10) = x15 ;\n jac(7,14) = x11 ;\n\nend\n\nfunction jac = jacobianstructure(auxdata)\n jac = sparse(7,14) ;\n \n jac(1,1) = 1 ;\n jac(1,4) = 1 ;\n jac(1,5) = 1 ;\n \n jac(2,3) = 1 ;\n jac(2,4) = 1 ;\n jac(2,6) = 1 ;\n jac(2,9) = 1 ;\n \n jac(3,1) = 1 ;\n jac(3,2) = 1 ;\n jac(3,5) = 1 ;\n jac(3,8) = 1 ;\n\n jac(4,1) = 1 ;\n jac(4,4) = 1 ;\n jac(4,8) = 1 ;\n jac(4,11) = 1 ;\n\n jac(5,6) = 1 ;\n jac(5,7) = 1 ;\n jac(5,8) = 1 ;\n jac(5,12) = 1 ;\n\n jac(6,9) = 1 ;\n jac(6,10) = 1 ;\n jac(6,13) = 1 ;\n\n jac(7,7) = 1 ;\n jac(7,10) = 1 ;\n jac(7,14) = 1 ;\nend\n\nfunction H = hessian(x, sigma, L, auxdata)\n\n x2 = x(1) ;\n x3 = x(2) ;\n x4 = x(3) ;\n x5 = x(4) ;\n x6 = x(5) ;\n x7 = x(6) ;\n x8 = x(7) ;\n x9 = x(8) ;\n x10 = x(9) ;\n x11 = x(10) ;\n x12 = x(11) ;\n x13 = x(12) ;\n x14 = x(13) ;\n x15 = x(14) ;\n\n Hf = sparse(14,14) ;\n Hf(4,7) = -6.3 ;\n Hf(7,4) = -6.3 ;\n\n H2 = sparse(14,14) ;\n H2(3,6) = -1 ;\n H2(6,3) = -1;\n H2(4,6) = -(0.01*x10) ;\n H2(6,4) = -(0.01*x10);\n H2(4,9) = -x7*0.01 ;\n H2(9,4) = -x7*0.01 ;\n H2(6,9) = -(0.01*x5);\n H2(9,6) = -(0.01*x5);\n\n H3 = sparse(14,14) ;\n H3(1,8) = -1 ;\n H3(8,1) = -1 ;\n\n H4 = sparse(14,14) ;\n H4(1,8) = -(0.13167 - 2*0.0067*x9) ;\n H4(8,1) = -(0.13167 - 2*0.0067*x9) ;\n H4(4,11) = 1 ;\n H4(11,4) = 1 ;\n H4(8,8) = x2*2*0.0067 ;\n\n H5 = sparse(14,14) ;\n H5(7,12) = 1 ;\n H5(12,7) = 1 ;\n H5(8,8) = 0.01*(2*0.038) ;\n\n H6 = sparse(14,14) ; \n H6(9,13) = 1;\n H6(13,9) = 1;\n\n H7 = sparse(14,14) ;\n H7(10,14) = 1 ;\n H7(14,10) = 1 ;\n\n H = tril(sparse(sigma * Hf + L(2)*H2 + L(3)*H3 + L(4)*H4 + L(5)*H5 + L(6)*H6 + L(7)*H7)) ;\nend\n\nfunction H = hessianstructure(auxdata)\n\n Hf = sparse(14,14) ;\n Hf(4,7) = 1;\n Hf(7,4) = 1;\n\n H2 = sparse(14,14) ;\n H2(3,6) = 1;\n H2(6,3) = 1;\n H2(4,6) = 1;\n H2(6,4) = 1;\n H2(4,9) = 1;\n H2(9,4) = 1;\n H2(6,9) = 1;\n H2(9,6) = 1;\n\n H3 = sparse(14,14) ;\n H3(1,8) = 1;\n H3(8,1) = 1;\n\n H4 = sparse(14,14) ;\n H4(1,8) = 1;\n H4(8,1) = 1;\n H4(4,11) = 1;\n H4(11,4) = 1;\n H4(8,8) = 1;\n\n H5 = sparse(14,14) ;\n H5(7,12) = 1;\n H5(12,7) = 1;\n H5(8,8) = 1;\n\n H6 = sparse(14,14) ; \n H6(9,13) = 1;\n H6(13,9) = 1;\n\n H7 = sparse(14,14) ;\n H7(10,14) = 1 ;\n H7(14,10) = 1 ;\n\n H = tril(sparse(Hf+H2+H3+H4+H5+H6+H7)) ;\nend\n", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/math/ipopt/examples/test_alkyl.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6619228625116081, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.31030323349505373}} {"text": "close all\nclear\n\n%------------------------------------------------------------------------------------------\nnb = 1000;%Total number of initial states\nnmpcd=zeros(1,nb);%Store computing time for one time-step for NMPC-DCBF\nimpcd=zeros(1,nb);%Store computing time for one time-step for iMPC-DCBF\nnmpcinf=zeros(1,1);%Store infeasible rate for one time-step for NMPC-DCBF\nimpcinf=zeros(1,1);%Store infeasible rate for one time-step for iMPC-DCBF\ni=24;%i is number of horozon\nts = 1;%Total time steps\nload(gamma1_0p4gamma2_0p4\\InitialStateData');%Load the generated 1000 initial states\n[a, b, c, d]=compare(i,ts,nb,InitialMat);%Involves NMPC-DCBF and iMPC-DCBF\nnmpcd(1,:)=a;\nimpcd(1,:)=b;\nnmpcinf(1,1)=c;\nimpcinf(1,1)=d;\nnmpcplot1=nmpcd(1,:);\nnmpcplot1(nmpcplot1==-1)=[];%Eliminate infeasible one time-step trajectories\nimpcplot1=impcd(1,:);\nimpcplot1(impcplot1==-1)=[];%Eliminate infeasible one time-step trajectories\n\nsave('timecom24','nmpcplot1','impcplot1');\nsave('feasibility24','nmpcinf','impcinf');\n\ndistnmpc = fitdist(nmpcplot1','Normal');\ndistimpc = fitdist(impcplot1','Normal');\nmu1=distnmpc.mu;%Get mean of sample of computing time for NMPC-DCBF\nmu2=distimpc.mu;%Get mean of sample of computing time for iMPC-DCBF\nsigma1=distnmpc.sigma;%Get variance of sample of computing time for NMPC-DCBF\nsigma2=distimpc.sigma;%Get variance of sample of computing time for iMPC-DCBF\n\n\n%Initialize atmosphere parameters\nfunction [tnmpc, timpc, ratiotnmpc, ratiotimpc]=compare(N11,ttsim,samplen,InitialMat)\ntnmpc=[];\ntimpc=[];\nfor i=1:samplen\nN1=N11;\ntsim=ttsim;\nxini1=InitialMat(1,i);\nyini1=InitialMat(2,i);\nthetaini1=InitialMat(3,i);\nvini1=InitialMat(4,i);\nx01=[xini1;yini1;thetaini1;vini1];\nx02=[xini1 yini1 thetaini1 vini1];\nt1 = nmpcdcbf(x01, N1, tsim);\nt2 = impcdcbf(x02, N1, tsim);\ntindex=[N11 i];\ndisp(tindex);\ntnmpc=[tnmpc t1];%Computing time for NMPC-DCBF\ntimpc=[timpc t2];%Computing time for iMPC-DCBF\nend\nnnmpc1 = length(tnmpc);\nnimpc1 = length(timpc);\ntnmpcs = tnmpc;\ntimpcs = timpc;\ntnmpcs(tnmpcs==-1)=[];\ntimpcs(timpcs==-1)=[];\nnnmpc2 = length(tnmpcs);\nnimpc2 = length(timpcs);\nratiotnmpc = (nnmpc1-nnmpc2)/nnmpc1;%Infeasible rate for NMPC-DCBF\nratiotimpc = (nimpc1-nimpc2)/nimpc1;%Infeasible rate for iMPC-DCBF\nend\n\n\n\n\nfunction t1 = nmpcdcbf(x00, N1, ttsim)\n%% General Flags\nrun_nmpc_dcbf_one = true;\nrun_nmpc_dcbf_multiple = true;\n\n%% Setup and Parameters\nx0 = x00;\ndt = 0.1;\ntime_total = ttsim *dt;\nP = zeros(4,4);%Weight matrix P\nP(1,1) = 10; P(2,2) = 10; P(3,3) = 10;P(4,4) = 10;\nQ = zeros(4,4);%Weight matrix Q\nQ(1,1) = 10; Q(2,2) = 10; Q(3,3) = 10;Q(4,4) = 10;\nR = zeros(4,4);%Weight matrix R\nR(1,1) = 1; R(2,2) = 1;R(3,3) = 1000;R(4,4) = 1000;\n%Variables range as below\nxmin = [-10; -10; -10;-10];\nxmax = [10; 10; 10;10];\numin = [-7; -5;-inf;-inf];\numax = [7; 5;inf;inf];\n\n%% Discrete-time unicycle model\nsystem.dt = dt;\nsystem.A = [1 0 0 0;\n 0 1 0 0;\n 0 0 1 0;\n 0 0 0 1];\nsystem.B = [x0(4,1)*cos(x0(3,1))*dt;\n x0(4,1)*sin(x0(3,1))*dt;\n 0;\n 0];\nsystem.C =[0 0 0 0;\n 0 0 0 0;\n 1*dt 0 0 0;\n 0 1*dt 0 0];\nsystem.xl = xmin;\nsystem.xu = xmax;\nsystem.ul = umin;\nsystem.uu = umax;\n\n%% NMPC-DCBF parameters\nparams_nmpc_dcbf.Q = Q;\nparams_nmpc_dcbf.R = R;\nparams_nmpc_dcbf.P = P;\nparams_nmpc_dcbf.gamma1 = 0.4;\nparams_nmpc_dcbf.gamma2 = 0.4;\n\n%% Obstacle\nobs.pos1 = [0; 0];\nobs.r1 = 1;\n\n\n\n%% Simulate NMPC-DCBF with other N\nparams_nmpc_dcbf.N = N1;\nif run_nmpc_dcbf_one\n fprintf('Run NMPC-DCBF-24\\n');\n controller_nmpc_dcbf_multiple24 = NMPCDCBF2(x0, system, params_nmpc_dcbf);%Highest order mcbf=2\n controller_nmpc_dcbf_multiple24.obs = obs;\n controller_nmpc_dcbf_multiple24.sim(time_total);\nend\nt1=controller_nmpc_dcbf_multiple24.tt;\nend\n\n\nfunction t2=impcdcbf(x00, N1, ttsim)\nt2=0;\nxo = 0;\nyo = 0;\nr = 1;\nN = N1;%Number of horizon\nK1 = 1000;%Maximum iteration times, jmax\nK = 1000;%Maximum iteration times, jmax\ndt = 0.1;\ngamma1 = 4;\ngamma2 = 4;\nnsim = ttsim;\n\ntic;\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 = x00;\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);%First order CBF constraints\nlcbf = -abc(3, :);\nlcbf(1) = [];\nlcbf = lcbf';\nucbf = inf * ones(N, 1);\nA2cbf = cbfmat2(abc, nx, nu, dt, gamma1, gamma2, x0);%Second order CBF constraints\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];\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!')\n t2=-1;\n return\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)%Iterations for the first time-step\n storagex = ctrlx;%store the state variables and inputs in order to compare them with the next iteration\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];\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 t2=-1;\n return\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);\nt2=t2+toc;\nreturn\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)%Iterations for the left time steps\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];\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 t2=-1;\n return\n end\n ctrlx = res.x(1:(N+1)*nx);\n ctrlu = res.x((N+1)*nx+1:(N+1)*nx+N*nu);\n x0 = ctrlx(1:nx);\n testx0 = [testx0 x0];\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\nend\n\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/benchmark/gamma1_0p4gamma2_0p4/test_each_horizon/test_N24.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926666143433998, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.31021376608253215}} {"text": "%-------------------------------------------------------------------------------------------------------------------%\n%\n% IB2d is an Immersed Boundary Code (IB) for solving fully coupled non-linear \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: nick.battista@unc.edu\n% Date Created: May 27th, 2015\n% Institution: UNC-CH\n%\n% This code is capable of creating Lagrangian Structures using:\n% \t1. Springs\n% \t2. Beams (*torsional springs)\n% \t3. Target Points\n%\t4. Muscle-Model (combined Force-Length-Velocity model, \"Hill+(Length-Tension)\")\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 (nick.battista@unc.edu) know.\n%\n%--------------------------------------------------------------------------------------------------------------------%\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: updates the spring attributes!\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction springs_info = update_Springs(dt,current_time,xLag,yLag,springs_info)\n\n%springs_info: col 1: starting spring pt (by lag. discretization)\n% col 2: ending spring pt. (by lag. discretization)\n% col 3: spring stiffness\n% col 4: spring resting lengths\n\n\nt = current_time; %CURRENT TIME IN SIM.\nds1 = 3.906250e-03; %PHASE 1 Lag. Spacing\nds2 = 3.342919e-03; %PHASE 2 Lag. Spacing\n\nNbody = 106; %Number of springs before bell connections\nRL = give_Resting_Lengths(); %Resting Lengths for Phase 1 (col 1) and Phase 2 (col 2)\n\n% CHANGE RESTING LENGTH BTWN SIDES OF JELLYFISH BELL\nfor i=1:length( springs_info(:,4) )\n \n if i <= Nbody\n springs_info(i,4) = ds1 + 5*t*(ds2-ds1);\n else\n ii = i-Nbody;\n springs_info(i,4) = RL(ii,1) + 5*t*( RL(ii,2) - RL(ii,1) );\n %springs_info(107+(i-1),4) = distVec(i)*abs( cos(4*pi*current_time) );\n %springs_info(107+(i-1),4) = distVec(i) * ( 1 - 0.75*( sin(4*pi*current_time) ) );\n end\nend\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: give Resting Lengths (hardcoded!)\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction RL = give_Resting_Lengths()\n\nRL = [0.150000000000000 0.075000000000000\n 0.149926741000240 0.074973170433545\n 0.149706855857594 0.074892624017213\n 0.149340020675537 0.074758187724185\n 0.148825697410294 0.074569727429823\n 0.148163136564709 0.074326763924451\n 0.147351380996092 0.074028781527991\n 0.146388643571571 0.073675421427274\n 0.145274017365354 0.073265752667258\n 0.144005152820154 0.072798927606369\n 0.142580953464829 0.072274183901744\n 0.140998544348621 0.071690309088121\n 0.139255611062067 0.071045912762170\n 0.137348541189626 0.070339929225114\n 0.135274492318472 0.069570469632096\n 0.133030516962324 0.068735403317456\n 0.130612168717920 0.067832977122889\n 0.128014600466564 0.066860709378195\n 0.125234180745507 0.065816586316769\n 0.122265614832230 0.064697078425658\n 0.119103315657513 0.063499067862592\n 0.115741451424401 0.062218444447808\n 0.112173999448214 0.060850772863983\n 0.108392818785359 0.059391311235482\n 0.104393528844001 0.057835033327000\n 0.100165653754868 0.056174749467196\n 0.095702659718569 0.054402747848968\n 0.090998237021989 0.052510837712120\n 0.086041701055792 0.050487212358191\n 0.080827140474999 0.048320369497431\n 0.075349280754860 0.045994841644143\n 0.069598549422225 0.043493120994599\n 0.063573706279126 0.040793235757662\n 0.057274941348722 0.037865974506005\n 0.050704050274530 0.034676918247010\n 0.043870119404512 0.031179908592683\n 0.036787309077097 0.027316537892343\n 0.029477909226729 0.023009349350403\n 0.021975429586313 0.018167707789027\n 0.014318966133393 0.012694598507574\n 0.006558552552061 0.006558010776142];", "meta": {"author": "nickabattista", "repo": "IB2d", "sha": "392d99c228cc801ff65766889c72e2e1492fe747", "save_path": "github-repos/MATLAB/nickabattista-IB2d", "path": "github-repos/MATLAB/nickabattista-IB2d/IB2d-392d99c228cc801ff65766889c72e2e1492fe747/matIB2d/Examples/Example_Jellyfish_Swimming/Failed_Attempts/Jellyfish_Spring_RL_Interpolation/update_Springs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.30990871777005324}} {"text": "function g = tensorKernGradient(kern, x, varargin)\n\n% TENSORKERNGRADIENT Gradient of TENSOR kernel's parameters.\n% FORMAT\n% DESC computes the gradient of functions with respect to the\n% tensor product\n% kernel's parameters. As well as the kernel structure and the\n% input positions, the user provides a matrix PARTIAL which gives\n% the partial derivatives of the function with respect to the\n% relevant elements of the kernel matrix. \n% ARG kern : the kernel structure for which the gradients are being\n% computed.\n% ARG x : the input locations for which the gradients are being\n% computed. \n% ARG partial : matrix of partial derivatives of the function of\n% interest with respect to the kernel matrix. The argument takes\n% the form of a square matrix of dimension numData, where numData is\n% the number of rows in X.\n% RETURN g : gradients of the function of interest with respect to\n% the kernel parameters. The ordering of the vector should match\n% that provided by the function kernExtractParam.\n%\n% FORMAT\n% DESC computes the derivatives as above, but input locations are\n% now provided in two matrices associated with rows and columns of\n% the kernel matrix. \n% ARG kern : the kernel structure for which the gradients are being\n% computed.\n% ARG x1 : the input locations associated with the rows of the\n% kernel matrix.\n% ARG x2 : the input locations associated with the columns of the\n% kernel matrix.\n% ARG partial : matrix of partial derivatives of the function of\n% interest with respect to the kernel matrix. The matrix should\n% have the same number of rows as X1 and the same number of columns\n% as X2 has rows.\n% RETURN g : gradients of the function of interest with respect to\n% the kernel parameters.\n%\n% SEEALSO tensorKernParamInit, kernGradient, tensorKernDiagGradient, kernGradX\n%\n% COPYRIGHT : Neil D. Lawrence, 2006\n\n% KERN\n\n \n% Last of varargin is covGrad.\n g = zeros(1, kern.nParams);\n startVal = 1;\n endVal = 0;\n twoXin = 0;\n if length(varargin) > 1\n twoXin = 1;\n x2 = varargin{1};\n covGrad = varargin{end};\n else\n covGrad = varargin{end};\n end\n \n for i = 1:length(kern.comp)\n tempKern = tensorKernSlash(kern, i);\n if twoXin\n tempCovGrad = covGrad.*kernCompute(tempKern, x, x2);\n else\n tempCovGrad = covGrad.*kernCompute(tempKern, x);\n end\n endVal = endVal + kern.comp{i}.nParams;\n if ~isempty(kern.comp{i}.index)\n % only part of the data is involved in the kernel.\n if ~twoXin\n g(1, startVal:endVal) = kernGradient(kern.comp{i}, ...\n x(:, kern.comp{i}.index), ...\n tempCovGrad);\n else\n g(1, startVal:endVal) = kernGradient(kern.comp{i}, ...\n x(:, kern.comp{i}.index), ...\n x2(:, kern.comp{i}.index), ...\n tempCovGrad);\n end\n else\n if ~twoXin\n % all the data is involved with the kernel.\n g(1, startVal:endVal) = kernGradient(kern.comp{i}, x, ...\n tempCovGrad);\n else\n g(1, startVal:endVal) = kernGradient(kern.comp{i}, x, x2, ...\n tempCovGrad);\n end\n end\n startVal = endVal + 1;\nend\ng = g*kern.paramGroups;\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/kern/tensorKernGradient.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.30985973660344424}} {"text": "% sim_press_shaped.m\n% Robin Simpson and Jamie Near, 2014.\n% \n% USAGE:\n% out = sim_press_shaped(n,sw,Bfield,linewidth,sys,tau1,tau2,RF,tp,dx,dy,Gx,Gy,flipAngle,centreFreq)\n% \n% DESCRIPTION:\n% This function simulates the PRESS experiment. The excitation is\n% simulated as an instantaneous rotation, and the refocusing pulses are\n% simulated as shaped rotations.\n%\n% It employs coherence selection to only include desired coherence orders\n% of the spin system being simulated. For the PRESS experiment, the desired\n% coherence after the excitation pulse is -1, +1 after the first refocusing\n% pulse and -1 after the final refocusing pulse.\n% \n% Finally, this code simulates the spectrum at a given point in space (x,y),\n% given the values of the slice selection gradients (Gx, and Gy). The pulse\n% waveform is assumed to be the same for both refocusing pulses. In order\n% to fully simulate the MEGA-PRESS experiment, you have to run this\n% simulation many times at various points in space (x,y), and then add\n% together the resulting spectra. \n% \n% INPUTS:\n% n = number of points in fid/spectrum\n% sw = desired spectral width in [Hz]\n% Bfield = main magnetic field strength in [T]\n% linewidth = linewidth in [Hz]\n% sys = spin system definition structure\n% tau1 = echo time 1 in [ms].\n% tau2 = echo time 2 in [ms].\n% RF = RF pulse definition structure for refoc pulses (obtain using 'io_loadRFwaveform.m')\n% tp = RF pulse duration in [ms]\n% dx = position offset in x-direction (corresponding to first refocusing pulse) [cm]\n% dy = position offset in y-direction (corresponding to second refocusing pulse) [cm]\n% Gx = gradient strength for first selective refocusing pulse [G/cm]\n% Gy = gradient strength for second selective refocusing pulse [G/cm]\n% flipAngle = flip angle of refocusing pulses [degrees] (Optional. Default = 180 deg)\n% centreFreq= centre frequency of the spectrum in [ppm] (Optional. Default = 2.3)\n%\n% OUTPUTS:\n% out = simulated spectrum, in FID-A structure format, using PRESS \n% sequence.\n\nfunction out = sim_press_shaped(n,sw,Bfield,linewidth,sys,tau1,tau2,RF,tp,dx,dy,Gx,Gy,flipAngle,centreFreq)\n\nif nargin<15\n centreFreq=2.3;\n if nargin<14\n flipAngle=180;\n end\nend\n \nif tau1= R.lowerBounds(iDim) & X(:,iDim) <= R.upperBounds(iDim);\n end\n \n vals = zeros(size(X,1),1);\n vals(isIn) = 1/R.area();\n end\n \n function vals = logPdf(R,X)\n [isValid, reasonStr] = R.isValid;\n assert(isValid,'LOGPDF cannot yet be evaluated. This RV is not yet valid %s.',reasonStr);\n \n vals = log(pdf(R,X));\n end\n \n function vals = cdf(R,X)\n X = R.dataInputParse(X); % Basic error checking etc\n assert(size(X,2) == R.nDimensions,'Data, RV dimensionality missmatch. Input data, X, has dimensionality %d and this RV has dimensionality %d.', size(X,2), R.nDimensions)\n vals = prod(max(bsxfun(@minus,bsxfun(@min,X,R.upperBounds),R.lowerBounds),0),2)./R.area();\n end\n \n function a = area(R)\n a = prod(R.upperBounds - R.lowerBounds);\n end\n \n function vals = draw(R,N)\n if nargin < 2\n N = 1;\n end\n \n assert(numel(N)==1 && N==floor(N) && N > 0,'N must be a positive integer scalar.')\n \n [isValid, reasonStr] = R.isValid;\n assert(isValid,'DRAW cannot yet be evaluated. This RV is not yet valid %s.',reasonStr);\n \n vals = bsxfun(@plus,bsxfun(@times,rand(N,R.nDimensions),R.upperBounds - R.lowerBounds),R.lowerBounds);\n end\n \n function val = get.nDimensions(R)\n val = length(R.upperBounds);\n end\n end\n \n methods (Hidden = true)\n function [val, reasonStr] = isValid(R)\n if numel(R) > 1\n val = false(size(R));\n for iR = 1:numel(R)\n [val(iR), reasonStr] = isValid(R(iR));\n end\n return\n end\n \n badOrder = ~all(R.upperBounds>R.lowerBounds);\n \n val = ~isempty(R.upperBounds) && ~isempty(R.lowerBounds) && ~badOrder;\n \n if val\n reasonStr = '';\n else\n badUpper = isempty(R.upperBounds);\n badLower = isempty(R.lowerBounds);\n \n if badUpper && ~badLower\n reasonStr = 'because upperBounds has not been set';\n elseif ~badUpper && badLower\n reasonStr = 'because lowerBounds has not been set';\n elseif badUpper && badLower\n reasonStr = 'because upperBounds and lowerBounds have not been set';\n elseif badOrder\n reasonStr = 'because at least one entry of lowerBounds is greater than the corresponding entry of upperBounds';\n else\n reasonStr = 'because of an unknown reason';\n end\n end\n end\n \n function val = plotLimits(R)\n [isValid, reasonStr] = R.isValid;\n if isValid\n \n range = R.upperBounds-R.lowerBounds;\n \n val = zeros(2*R.nDimensions,1);\n val(1:2:end) = R.lowerBounds-range/10;\n val(2:2:end) = R.upperBounds+range/10;\n \n \n else\n error('prtRvUniform:plotLimits','Plotting limits can not be determined for this RV. It is not yet valid %s.',reasonStr)\n end\n end\n end\nend\n", "meta": {"author": "covartech", "repo": "PRT", "sha": "4305e612af048e7dbf3d9392efc7436db125b1fc", "save_path": "github-repos/MATLAB/covartech-PRT", "path": "github-repos/MATLAB/covartech-PRT/PRT-4305e612af048e7dbf3d9392efc7436db125b1fc/rv/prtRvUniform.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.5621765008857982, "lm_q1q2_score": 0.30953852211854904}} {"text": "function [rtk,stat0]=relpos(rtk,obsr,obsb,nav)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%% relative positioning %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%input: rtk - rtk control struct\n% obsr - rover observations\n% obsb - base observations\n% nav - navigation message\n%output: rtk - rtk control struct\n% stat0 - state (0:error 1:ok)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%relative positioning include PPD, PPK and PPS\n%PPD:post-processing differenced, based on double-differenced PR\n%PPK:post-processing kinematic, based on double-differenced CP and PR\n%PPS:post-processing static, based on double-differenced CP and PR\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nglobal glc\nopt=rtk.opt; nf=rtk.NF; dt=timediff(obsr(1).time,obsb(1).time);\nnobsr=size(obsr,1); nobsb=size(obsb,1);\n\nif rtk.opt.mode<=glc.PMODE_DGNSS\n stat=glc.SOLQ_DGNSS;\nelse\n stat=glc.SOLQ_FLOAT;\nend\n\nfor i=1:glc.MAXSAT\n [sys,~]=satsys(i);\n rtk.sat(i).sys=sys;\n for j=1:glc.NFREQ\n rtk.sat(i).vsat(j)=0;\n end\n for j=1:glc.NFREQ\n rtk.sat(i).snr(j)=0;\n end \nend\n\nsvr=satposs(obsr,nav,opt.sateph);\nsvb=satposs(obsb,nav,opt.sateph);\n\n% zero-differenced residuals for base\n[zdb,stat_tmp]=zdres(2,obsb,svb,nav,rtk.basepos,opt,rtk);\nif stat_tmp==0,stat0=0;return;end\n\nind=selcomsat(obsr,obsb,opt,zdb);\nif ind.ns==0,stat0=0;return;end\n\n% debug tracing\n% fprintf('\\n\\n\\n');\n% fprintf('time=%d\\n',obsr(1).time.time);\n% fprintf('before time update\\n');\n% printx(rtk.x,rtk);\n% printP(rtk.P,rtk);\n\n% time update\nrtk=udstate(rtk,obsr,obsb,nav,ind);\n\n% debug tracing\n% fprintf('after time update\\n');\n% printx(rtk.x,rtk);\n% printP(rtk.P,rtk);\n\nxp=rtk.x; Pp=zeros(rtk.nx,rtk.nx);\nfor i=1:opt.niter\n \n % zero-differenced residuals for rover\n [zdr,stat_tmp]=zdres(1,obsr,svr,nav,xp(1:3),opt,rtk);\n if stat_tmp==0,stat=glc.SOLQ_NONE;break;end\n \n % double-differenced residuals,measurement matrix and noise matrix\n [rtk,v,H,R,nv,~]=ddres(rtk,nav,dt,xp,Pp,zdr,zdb,ind);\n if nv<=0,stat=glc.SOLQ_NONE;break;end\n \n % debug tracing\n% printv(v);\n% printH(H);\n% printR(R);\n \n % measurement update\n Pp=rtk.P;\n [xp,Pp,stat_tmp]=Kfilter_h(v,H,R,xp,Pp);\n if stat_tmp==0\n [week,sow]=time2gpst(obs(1).time);\n fprintf('Warning:GPS week = %d sow = %.3f,filter error!\\n',week,sow);\n stat=glc.SOLQ_NONE;\n break;\n end\n \n % debug tracing\n% fprintf('after measurement update\\n');\n% printx(xp,rtk);\n% printP(Pp,rtk);\n \nend\n\nif stat~=glc.SOLQ_NONE\n % zero-differenced residuals for rover\n [zdr,stat_tmp]=zdres(1,obsr,svr,nav,xp(1:3),opt,rtk);\n if stat_tmp~=0\n % post-fit residuals for float solution\n [rtk,v,~,R,nv,vflag]=ddres(rtk,nav,dt,xp,Pp,zdr,zdb,ind);\n % validation of float solution\n if valpos_rel(rtk,v,R,vflag,nv,4)\n rtk.x=xp; rtk.P=Pp;\n rtk.sol.ns=0;\n for i=1:ind.ns\n for f=1:nf\n sati=ind.sat(i);\n if ~rtk.sat(sati).vsat(f),continue;end\n rtk.sat(sati).lock(f)=rtk.sat(sati).lock(f)+1;\n rtk.sat(sati).outc(f)=0;\n if f==1,rtk.sol.ns=rtk.sol.ns+1;end\n end\n end\n if rtk.sol.ns<4,stat=glc.SOLQ_NONE;end\n else\n stat=glc.SOLQ_NONE;\n end \n end \nend\n\n% ambiguity resolution\nif stat~=glc.SOLQ_NONE\n [rtk,~,xa,nb]=resamb(rtk);\n if nb>1\n % zero-differenced residuals for rover\n [zdr,stat_tmp]=zdres(1,obsr,svr,nav,xa(1:3),opt,rtk);\n if stat_tmp~=0\n % post-fit reisiduals for fixed solution\n [rtk,v,~,R,nv,vflag]=ddres(rtk,nav,dt,xa,Pp,zdr,zdb,ind);\n % validation of fixed solution\n if valpos_rel(rtk,v,R,vflag,nv,4)\n rtk.nfix=rtk.nfix+1;\n if rtk.nfix>=opt.minfix&&rtk.opt.modear==glc.ARMODE_FIXHOLD\n % hold integer ambiguity\n rtk=holdamb(rtk,xa);\n end\n stat=glc.SOLQ_FIX;\n end\n end\n end\nend\n\n% save solution status\nif stat==glc.SOLQ_FIX\n rtk.sol.pos=rtk.xa(1:3)';\n rtk.sol.posP(1)=rtk.Pa(1,1); rtk.sol.posP(2)=rtk.Pa(2,2);\n rtk.sol.posP(3)=rtk.Pa(3,3); rtk.sol.posP(4)=rtk.Pa(1,2);\n rtk.sol.posP(5)=rtk.Pa(2,3); rtk.sol.posP(6)=rtk.Pa(1,3);\n if rtk.opt.dynamics==1\n rtk.sol.vel=rtk.xa(4:6)';\n rtk.sol.velP(1)=rtk.Pa(4,4); rtk.sol.velP(2)=rtk.Pa(5,5);\n rtk.sol.velP(3)=rtk.Pa(6,6); rtk.sol.velP(4)=rtk.Pa(4,5);\n rtk.sol.velP(5)=rtk.Pa(5,6); rtk.sol.velP(6)=rtk.Pa(4,6);\n end\nelse\n rtk.sol.pos=rtk.x(1:3)';\n rtk.sol.posP(1)=rtk.P(1,1); rtk.sol.posP(2)=rtk.P(2,2);\n rtk.sol.posP(3)=rtk.P(3,3); rtk.sol.posP(4)=rtk.P(1,2);\n rtk.sol.posP(5)=rtk.P(2,3); rtk.sol.posP(6)=rtk.P(1,3);\n if rtk.opt.dynamics==1\n rtk.sol.vel=rtk.xa(4:6)';\n rtk.sol.velP(1)=rtk.P(4,4); rtk.sol.velP(2)=rtk.P(5,5);\n rtk.sol.velP(3)=rtk.P(6,6); rtk.sol.velP(4)=rtk.P(4,5);\n rtk.sol.velP(5)=rtk.P(5,6); rtk.sol.velP(6)=rtk.P(4,6);\n end\n rtk.nfix=0;\nend\n\nfor i=1:nobsr\n for j=1:nf\n if obsr(i).L(j)==0,continue;end\n rtk.sat(obsr(i).sat).pt(1,j)=obsr(i).time;\n rtk.sat(obsr(i).sat).ph(1,j)=obsr(i).L(j);\n end\nend\nfor i=1:nobsb\n for j=1:nf\n if obsb(i).L(j)==0,continue;end\n rtk.sat(obsb(i).sat).pt(2,j)=obsb(i).time;\n rtk.sat(obsb(i).sat).ph(2,j)=obsb(i).L(j);\n end\nend\n\nfor i=1:ind.ns\n for j=1:nf\n rtk.sat(ind.sat(i)).snr(j)=obsr(ind.ir(i)).S(j);\n end\nend\n\nfor i=1:glc.MAXSAT\n for j=1:nf\n if rtk.sat(i).fix(j)==2&&stat~=glc.SOLQ_FIX\n rtk.sat(i).fix(j)=1;\n end\n if bitand(rtk.sat(i).slip(j),1)\n rtk.sat(i).slipc(j)=rtk.sat(i).slipc(j)+1;\n end\n end\nend\n\nif stat~=glc.SOLQ_NONE,rtk.sol.stat=stat;end\n\nstat0=(stat~=glc.SOLQ_NONE);\n\nreturn\n\n", "meta": {"author": "kaichen686", "repo": "GINav", "sha": "bc6b3ab6c40db996a4fd8e8ca5b748fe21a23666", "save_path": "github-repos/MATLAB/kaichen686-GINav", "path": "github-repos/MATLAB/kaichen686-GINav/GINav-bc6b3ab6c40db996a4fd8e8ca5b748fe21a23666/src/gnss/relpos/relpos.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6926419958239133, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.3085924663483097}} {"text": "function varargout = MDOF_vibration_calculator3(varargin)\n% MDOF_VIBRATION_CALCULATOR3 M-file for MDOF_vibration_calculator3.fig\n% MDOF_VIBRATION_CALCULATOR3, by itself, creates a new MDOF_VIBRATION_CALCULATOR3 or raises the existing\n% singleton*.\n%\n% H = MDOF_VIBRATION_CALCULATOR3 returns the handle to a new MDOF_VIBRATION_CALCULATOR3 or the handle to\n% the existing singleton*.\n%\n% MDOF_VIBRATION_CALCULATOR3('CALLBACK',hObject,eventData,handles,...) calls the local\n% function named CALLBACK in MDOF_VIBRATION_CALCULATOR3.M with the given input arguments.\n%\n% MDOF_VIBRATION_CALCULATOR3('Property','Value',...) creates a new MDOF_VIBRATION_CALCULATOR3 or raises the\n% existing singleton*. Starting from the left, property value pairs are\n% applied to the GUI before MDOF_vibration_calculator3_OpeningFcn gets called. An\n% unrecognized property name or invalid value makes property application\n% stop. All inputs are passed to MDOF_vibration_calculator3_OpeningFcn via varargin.\n%\n% *See GUI Options on GUIDE's Tools menu. Choose \"GUI allows only one\n% instance to run (singleton)\".\n%\n% See also: GUIDE, GUIDATA, GUIHANDLES\n\n% Edit the above text to modify the response to help MDOF_vibration_calculator3\n\n% Last Modified by GUIDE v2.5 11-Oct-2011 22:48:12\n\n% Begin initialization code - DO NOT EDIT\ngui_Singleton = 1;\ngui_State = struct('gui_Name', mfilename, ...\n 'gui_Singleton', gui_Singleton, ...\n 'gui_OpeningFcn', @MDOF_vibration_calculator3_OpeningFcn, ...\n 'gui_OutputFcn', @MDOF_vibration_calculator3_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 MDOF_vibration_calculator3 is made visible.\nfunction MDOF_vibration_calculator3_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 MDOF_vibration_calculator3 (see VARARGIN)\n\n% Choose default command line output for MDOF_vibration_calculator3\nhandles.output = hObject;\n\n% Update handles structure\nguidata(hObject, handles);\nglobal CC\nCC = 0;\ninitial_function(hObject, eventdata, handles)\n% UIWAIT makes MDOF_vibration_calculator3 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 = MDOF_vibration_calculator3_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\n% --- Executes on button press in pushbutton1.\nfunction pushbutton1_Callback(hObject, eventdata, handles)\n% hObject handle to pushbutton1 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nclc\n\nAcquiringData(hObject, eventdata, handles);\nCalculating_Modal_Equation(hObject, eventdata, handles)\n[z,wn,f0,wdr,x0,v0] = Definding_Modal_Equa_values(hObject, eventdata, handles);\nDisplaying_Modal_Equation(z,wn,f0,wdr,x0,v0,hObject, eventdata, handles);\nCalculation_XDisplacement(hObject, eventdata, handles);\n% Displaying_XDisplacement(hObject, eventdata, handles)\nPlotting_XT(hObject, eventdata, handles)\nPlotting_RT(hObject, eventdata, handles)\n\nfunction Animation_2mass(hObject, eventdata, handles)\nglobal XT t CC\n\naxes(handles.axes1); cla(handles.axes1);\nset(handles.pushbutton3, 'string','Stop');\n if CC == 0\n CC = 1;\n else\n CC = 0;\n end\nposx=[0.5 -0.5 -0.5 0.5]; \nposy=[0.5 0.5 -0.5 -0.5];\nh1=line(0,0);\n\nline([-5 10],[-0.5 -0.5],'color','k','linewidth',2);%base line\nline([0 0],[-0.5 5],'color','k','linewidth',2); %a wall on left \nblock1=patch(posx,posy,'y'); \nblock2=patch(posx,posy,'g');\n\naxes(handles.axes1);\naxis([0 10 -1 1]);\nRatio = 1/max(max(abs(XT)));\nxini = [3; 6];\nfor i = 1 : length(t)\n if ishandle(h1) == 0 || CC == 0\n set(handles.pushbutton3, 'string','Play');\n cla(handles.axes1);\n break\n else \n Movx1 = xini(1) + Ratio * XT(1,i);\n Movx2 = xini(2) + Ratio * XT(2,i);\n set(h1,'xdata',[0 Movx1-0.5 Movx2-0.5],'ydata',[0 0 0]);\n set(block1,'xdata', posx + Movx1, 'ydata', posy);\n set(block2,'xdata', posx + Movx2, 'ydata', posy);\n\n pause(0.015);\n end\nend\nCC = 0;\nset(handles.pushbutton3, 'string','Play');\n\n% --- Executes on button press in pushbutton3.\nfunction pushbutton3_Callback(hObject, eventdata, handles)\n% hObject handle to pushbutton3 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nAnimation_2mass(hObject, eventdata, handles)\n\nfunction Plotting_RT(hObject, eventdata, handles)\nglobal t RT\nplot(handles.axes2,t, RT);legend(handles.axes2,'r_1(t)','r_2(t)');\nxlabel(handles.axes2,'Time, t'); ylabel(handles.axes2,'Displacement')\n\nfunction Plotting_XT(hObject, eventdata, handles)\nglobal t XT\nplot(handles.axes3,t, XT);legend(handles.axes3,'x_1(t)','x_2(t)');\nxlabel(handles.axes3,'Time, t'); ylabel(handles.axes3,'Displacement')\n\n% function Displaying_XDisplacement(hObject, eventdata, handles)\n% global S func\n% \n% switch func\n% case 1\n% R1 = get(handles.text10,'string');\n% R2 = get(handles.text11,'string');\n% R1a = str2num(R1(11:15)); R1b = R1(16:35);\n% R2a = str2num(R2(11:15)); R2b = R2(16:35);\n% \n% X11 = S(1,1)*R1a; X12 = S(1,2)*R2a;\n% X21 = S(2,1)*R1a; X22 = S(2,2)*R2a;\n% \n% set(handles.text14, 'string',['']);\n% case 2 \n% set(handles.text14,'string',' Sorry ');\n% set(handles.text15,'string',' Sorry ');\n% case 3\n% set(handles.text14,'string',' Sorry ');\n% set(handles.text15,'string',' Sorry ');\n% end\n\n% set(handles.text14,'string','')\n% set(handles.text15,'string','')\n\n\nfunction Calculation_XDisplacement(hObject, eventdata, handles)\nglobal RT S XT\nXT = S*RT;\n\nfunction Displaying_Modal_Equation(z,wn,f0,wdr,x0,v0, hObject, eventdata, handles)\nglobal M t func RT S\nzz = z*0.5./wn; wwn = wn; wwdr = wdr; xx0 = x0; vv0 = v0; ff0 = f0;\nRT = zeros(length(M),length(t));\n\nfor i = 1 : length(M)\n z = zz(i); wn = wwn(i); wdr = wwdr(i); \n x0 = xx0(i); v0 = vv0(i); f0 = ff0(i);\n% z,wn,wdr,x0,v0,f0\n\n switch func\n case 1 % func 1 : F0 = 0\n if z >= 1\n warndlg('This is not underdamp system because ...the damping ratio is larger than 1. Please insert the value correctly.');\n %XT = 0*t; \n else\n wd = wn*sqrt(1-z^2);\n X = f0/sqrt((wn^2 - wdr^2)^2 + (2*z*wn*wdr)^2);\n Theta = atan(2*z*wn*wdr/(wn^2 - wdr^2));\n Phi = atan((wd*(x0 - X*cos(Theta)))/(v0 + (x0 - X*cos(Theta))*z*wn - wdr*X*sin(Theta)));\n A = (x0 - X*cos(Theta))/sin(Phi);\n RT(i,:) = A*exp(-z*wn*t).*sin(wd*t + Phi) + X*cos(wdr*t - Theta);\n if i == 1\n if z == 0\n set(handles.text10, 'string',[' r1(t) = ',sprintf('%4.3f',A),...\n ' sin(',sprintf('%4.3f',wd),...\n 't + ',sprintf('%4.3f',Phi),')']);\n else\n set(handles.text10, 'string',[' r1(t) = ',sprintf('%4.3f',A),...\n 'exp(',sprintf('%4.3f',-z*wn),'t) sin(',sprintf('%4.3f',wd),...\n 't + ',sprintf('%4.3f',Phi),')']);\n end\n else\n if z == 0\n set(handles.text11, 'string',[' r2(t) = ',sprintf('%4.3f',A),...\n ' sin(',sprintf('%4.3f',wd),...\n 't + ',sprintf('%4.3f',Phi),')']);\n else\n set(handles.text11, 'string',[' r2(t) = ',sprintf('%4.3f',A),...\n 'exp(',sprintf('%4.3f',-z*wn),'t) sin(',sprintf('%4.3f',wd),...\n 't + ',sprintf('%4.3f',Phi),')']);\n end\n end\n end\n case 2 % func 1 : F0 cos wt\n wd = wn*sqrt(1-z^2);\n \n X = f0/sqrt((wn^2 - wdr^2)^2 + (2*z*wn*wdr)^2);\n Theta = atan(2*z*wn*wdr/(wn^2 - wdr^2));\n Phi = atan((wd*(x0 - X*cos(Theta)))/(v0 + (x0 - X*cos(Theta))*z*wn - wdr*X*sin(Theta)));\n A = (x0 - X*cos(Theta))/sin(Phi);\n RT(i,:) = A*exp(-z*wn*t).*sin(wd*t + Phi) + X*cos(wdr*t - Theta);\n if i ==1\n if z == 0\n set(handles.text10, 'string',[' r1(t) = ',sprintf('%4.3f',A),...\n ' sin(', sprintf('%4.3f',wd),'t + ',...\n sprintf('%4.3f',Phi),') + ',sprintf('%4.3f',X),'cos(',sprintf('%4.3f',wdr),...\n 't - ',sprintf('%4.3f',Theta),')']);\n else\n set(handles.text10, 'string',[' r1(t) = ',sprintf('%4.3f',S(1,1)*A),'exp(',...\n sprintf('%4.3f',-z*wn),'t) sin(', sprintf('%4.3f',wd),'t + ',...\n sprintf('%4.3f',Phi),') + ',sprintf('%4.3f',X),'cos(',sprintf('%4.3f',wdr),...\n 't - ',sprintf('%4.3f',Theta),')']);\n end \n else\n if z == 0\n set(handles.text11, 'string',[' r2(t) = ',sprintf('%4.3f',A),...\n ' sin(', sprintf('%4.3f',wd),'t + ',...\n sprintf('%4.3f',Phi),') + ',sprintf('%4.3f',X),'cos(',sprintf('%4.3f',wdr),...\n 't - ',sprintf('%4.3f',Theta),')']);\n else\n set(handles.text11, 'string',[' r2(t) = ',sprintf('%4.3f',A),'exp(',...\n sprintf('%4.3f',-z*wn),'t) sin(', sprintf('%4.3f',wd),'t + ',...\n sprintf('%4.3f',Phi),') + ',sprintf('%4.3f',X),'cos(',sprintf('%4.3f',wdr),...\n 't - ',sprintf('%4.3f',Theta),')']);\n end\n end\n\n case 3 % func 1 : F0 sin wt\n wd = wn*sqrt(1-z^2);\n T = f0/sqrt((wn^2 - wdr^2)^2 + (2*z*wn*wdr)^2);\n X = f0/((wn^2 - wdr^2)^2 + (2*z*wn*wdr)^2);\n Theta = atan(2*z*wn*wdr/(wn^2 - wdr^2));\n Phi = atan((wd*(x0 + X*cos(Theta)))/(v0 + (x0 + X*cos(Theta))*z*wn + wdr*X*sin(Theta)));\n A = (x0 + X*cos(Theta))/sin(Phi);\n RT(i,:) = A*exp(-z*wn*t).*sin(wd*t + Phi) + T*sin(wdr*t + Theta);\n if i == 1\n if z == 0\n set(handles.text10, 'string',[' r1(t) = ',sprintf('%4.3f',A),...\n ' sin(', sprintf('%4.3f',wd),'t + ',...\n sprintf('%4.3f',Phi),') + ',sprintf('%4.3f',T),'sin(',sprintf('%4.3f',wdr),...\n 't + ',sprintf('%4.3f',Theta),')']);\n else\n set(handles.text10, 'string',[' r1(t) = ',sprintf('%4.3f',A),'exp(',...\n sprintf('%4.3f',-z*wn),'t) sin(', sprintf('%4.3f',wd),'t + ',...\n sprintf('%4.3f',Phi),') + ',sprintf('%4.3f',T),'sin(',sprintf('%4.3f',wdr),...\n 't + ',sprintf('%4.3f',Theta),')']);\n end\n else\n if z == 0\n set(handles.text11, 'string',[' r2(t) = ',sprintf('%4.3f',A),' sin(', sprintf('%4.3f',wd),'t + ',...\n sprintf('%4.3f',Phi),') + ',sprintf('%4.3f',T),'sin(',sprintf('%4.3f',wdr),...\n 't + ',sprintf('%4.3f',Theta),')']);\n else\n set(handles.text11, 'string',[' r2(t) = ',sprintf('%4.3f',A),'exp(',...\n sprintf('%4.3f',-z*wn),'t) sin(', sprintf('%4.3f',wd),'t + ',...\n sprintf('%4.3f',Phi),') + ',sprintf('%4.3f',T),'sin(',sprintf('%4.3f',wdr),...\n 't + ',sprintf('%4.3f',Theta),')']);\n end\n end\n end\nend\n\n\nfunction [z,wn,f0,wdr,x0,v0] = Definding_Modal_Equa_values(hObject, eventdata, handles)\n\nglobal M B F0 w wn\nglobal PCMP PKMP S Sinv \n\n\nx0 = str2num(get(handles.edit9,'string'));\nv0 = str2num(get(handles.edit10,'string'));\n\n% x0, v0,\n% Intial value of modal equation\nr0 = Sinv*x0; x0 = r0;\nrdot0 = Sinv*v0; v0 = rdot0;\nzz = diag(PCMP);\n\n% Define each of modal equation value\n\nfor i = 1 : length(M) \n z(i) = zz(i);\n wn(i) = sqrtm(PKMP(i,i)); \n FF = S'*B.*F0;\n f0(i) = FF(i,2);\n wdr(i) = w;\nend\nz = z'; f0 = f0'; wdr = wdr';\n% r0, rdot0, f0, F0,z,wn,wdr\n\n\n\nfunction Calculating_Modal_Equation(hObject, eventdata, handles)\n\nglobal M C K\nglobal CM PCMP KM PKMP U S Sinv wn\n\nMinvsquare = inv(chol(M));\nKM = Minvsquare*K*Minvsquare;\nCM = Minvsquare*C*Minvsquare;\nU = chol(M);\n[P,lam] = eig(U'\\K/U);\n[w,k] = sort(sqrt(diag(lam)));\nP = P(:,k);\n for i = 1:length(M)\n if P(1,i) < 0\n P(:,i) = -P(:,i);\n end\n end\nPKMP = P'*KM*P;\nPCMP = P'*CM*P;\nS = U\\P; Sinv = inv(S); wn = w;\n% S,Sinv,U,PKMP,PCMP, wn\n\nfunction AcquiringData(hObject, eventdata, handles)\n\nglobal M C K B F0 w t x0 v0\n\nM = str2num(get(handles.edit1,'string'));\nC = str2num(get(handles.edit2,'string'));\nK = str2num(get(handles.edit3,'string'));\nB = str2num(get(handles.edit4,'string'));\nF0 = str2num(get(handles.edit5,'string'));\nw = str2num(get(handles.edit6,'string'));\nt0 = str2num(get(handles.edit7,'string'));\ntf = str2num(get(handles.edit8,'string'));\nx0 = str2num(get(handles.edit9,'string'));\nv0 = str2num(get(handles.edit10,'string'));\n\nt = t0:0.05:tf;\nif size(C) ~= size(M)\n warndlg('Please check matrix size of M, C, K')\nend\n\n% M, C, K, B, F0, w, t, x0, v0\n\n% --- Executes on selection change in popupmenu1.\nfunction popupmenu1_Callback(hObject, eventdata, handles)\n% hObject handle to popupmenu1 (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: contents = cellstr(get(hObject,'String')) returns popupmenu1 contents as cell array\n% contents{get(hObject,'Value')} returns selected item from popupmenu1\nglobal func\n\nswitch get(hObject,'Value')\n case 1\n func = 1; \n set(handles.edit5,'string',0);set(handles.edit5,'enable','off');\n set(handles.edit6,'string',0);set(handles.edit6,'enable','off');\n case 2\n func = 2;\n set(handles.edit5,'enable','on');\n set(handles.edit6,'enable','on');\n case 3\n func = 3;\n set(handles.edit5,'enable','on');\n set(handles.edit6,'enable','on');\nend\n \nfunction initial_function(hObject, eventdata, handles)\nglobal func\n func = 1; \n set(handles.edit5,'string',0);set(handles.edit5,'enable','off');\n set(handles.edit6,'string',0);set(handles.edit6,'enable','off');\n set(handles.popupmenu1,'value',1);\n set(handles.axes1,'visible','off');\n \n% --- Executes on button press in pushbutton2.\nfunction pushbutton2_Callback(hObject, eventdata, handles)\n% hObject handle to pushbutton2 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nglobal func\n\nset(handles.edit1,'string','[3 0 ; 0 1]');\nset(handles.edit2,'string','[0 0 ; 0 0]');\nset(handles.edit3,'string','[3 -1 ; -1 3]');\nset(handles.edit4,'string','[0 0 ; 0 1]');\nset(handles.edit5,'string','1');set(handles.edit5,'enable','on');\nset(handles.edit6,'string','1');set(handles.edit6,'enable','on');\nset(handles.edit9,'string','[1;0]');\nset(handles.edit10,'string','[0;0]');\nset(handles.popupmenu1,'value',1);\n func = 1; \n\nfunction edit1_Callback(hObject, eventdata, handles)\n% hObject handle to edit1 (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 edit1 as text\n% str2double(get(hObject,'String')) returns contents of edit1 as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction edit1_CreateFcn(hObject, eventdata, handles)\n% hObject handle to edit1 (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 edit2_Callback(hObject, eventdata, handles)\n% hObject handle to edit2 (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 edit2 as text\n% str2double(get(hObject,'String')) returns contents of edit2 as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction edit2_CreateFcn(hObject, eventdata, handles)\n% hObject handle to edit2 (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 edit3_Callback(hObject, eventdata, handles)\n% hObject handle to edit3 (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 edit3 as text\n% str2double(get(hObject,'String')) returns contents of edit3 as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction edit3_CreateFcn(hObject, eventdata, handles)\n% hObject handle to edit3 (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 edit4_Callback(hObject, eventdata, handles)\n% hObject handle to edit4 (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 edit4 as text\n% str2double(get(hObject,'String')) returns contents of edit4 as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction edit4_CreateFcn(hObject, eventdata, handles)\n% hObject handle to edit4 (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\n\n% --- Executes during object creation, after setting all properties.\nfunction popupmenu1_CreateFcn(hObject, eventdata, handles)\n% hObject handle to popupmenu1 (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 edit5_Callback(hObject, eventdata, handles)\n% hObject handle to edit5 (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 edit5 as text\n% str2double(get(hObject,'String')) returns contents of edit5 as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction edit5_CreateFcn(hObject, eventdata, handles)\n% hObject handle to edit5 (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 edit6_Callback(hObject, eventdata, handles)\n% hObject handle to edit6 (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 edit6 as text\n% str2double(get(hObject,'String')) returns contents of edit6 as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction edit6_CreateFcn(hObject, eventdata, handles)\n% hObject handle to edit6 (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 edit7_Callback(hObject, eventdata, handles)\n% hObject handle to edit7 (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 edit7 as text\n% str2double(get(hObject,'String')) returns contents of edit7 as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction edit7_CreateFcn(hObject, eventdata, handles)\n% hObject handle to edit7 (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 edit8_Callback(hObject, eventdata, handles)\n% hObject handle to edit8 (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 edit8 as text\n% str2double(get(hObject,'String')) returns contents of edit8 as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction edit8_CreateFcn(hObject, eventdata, handles)\n% hObject handle to edit8 (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 edit9_Callback(hObject, eventdata, handles)\n% hObject handle to edit9 (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 edit9 as text\n% str2double(get(hObject,'String')) returns contents of edit9 as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction edit9_CreateFcn(hObject, eventdata, handles)\n% hObject handle to edit9 (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 edit10_Callback(hObject, eventdata, handles)\n% hObject handle to edit10 (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 edit10 as text\n% str2double(get(hObject,'String')) returns contents of edit10 as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction edit10_CreateFcn(hObject, eventdata, handles)\n% hObject handle to edit10 (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 \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/33278-multi-degree-of-freedom-vibration-calculator/MDOF_vibration_calculator3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.30853350645981986}} {"text": "function []=uw_sb_unwrap_space_time(day,ifgday_ix,unwrap_method,time_win,la_flag,bperp,n_trial_wraps,prefilt_win,scf_flag,temp,n_temp_wraps,max_bperp_for_temp_est)\n%UW_SB_UNWRAP_SPACE_TIME smooth and unwrap phase diffs between neighboring data points in time\n%\n% Andy Hooper, June 2007\n%\n% ======================================================================\n% 07/2008 AH: Allow isolated images, not included in any interferogram\n% 01/2010 AH: Allow for non-positive definite inverse var/covar matrix\n% 01/2012 AH: New option la_flag that estimates LA error for each arc\n% 02/2012 AH: New method 3D_NEW\n% 02/2012 AH: New method 3D_FULL\n% 03/2012 AH: version updated for subsets of full network\n% 10/2012 AH: Bug corrected in 3D_FULL\n% 11/2012 AH: Add temperature option and scf_flag\n% 09/2013 DB: Fix compatibility issue with matlab 2009\n% 10/2013 DB: Fix introduced bug on them variable\n% 09/2014 DB: Fix the order in which isolated dates are removed. Start\n% from big to small.\n% 02/2014 AH: Add predefined ph_uw option\n% ======================================================================\n% \n%\ndisp('Unwrapping in time-space...')\n\n\nuw=load('uw_grid');\nui=load('uw_interp');\n\nn_ifg=uw.n_ifg;\nn_ps=uw.n_ps;\nnzix=uw.nzix;\nij=uw.ij;\n\nif isempty(uw.ph_uw_predef)\n predef_flag='n';\nelse\n predef_flag='y';\nend\n\n\nn_image=size(day,1);\nmaster_ix=find(day==0);\n[nrow,ncol]=size(ui.Z);\n\nday_pos_ix=find(day>0);\n[tempdummy,I]=min(day(day_pos_ix));\ndph_space=((uw.ph(ui.edgs(:,3),:).*conj(uw.ph(ui.edgs(:,2),:))));\nif predef_flag=='y'\n dph_space_uw=uw.ph_uw_predef(ui.edgs(:,3),:)-uw.ph_uw_predef(ui.edgs(:,2),:);\n predef_ix=~isnan(dph_space_uw);\n dph_space_uw=dph_space_uw(predef_ix);\nelse\n predef_ix=[];\nend\nclear uw tempdummy\n\ndph_space=dph_space./abs(dph_space);\n\n\nifreq_ij=[];\njfreq_ij=[];\n\nG=zeros(n_ifg,n_image);\nfor i=1:n_ifg\n G(i,ifgday_ix(i,1))=-1;\n G(i,ifgday_ix(i,2))=1;\nend\n\nnzc_ix=sum(abs(G))~=0; % non-zero column index\nday=day(nzc_ix);\nn_image=size(day,1);\nG=G(:,nzc_ix);\nzc_ix=find(nzc_ix==0);\nzc_ix = sort(zc_ix,'descend'); % fix to make sure the order goes from largest to smallest\nfor i=1:length(zc_ix)\n ifgday_ix(ifgday_ix>zc_ix(i))=ifgday_ix(ifgday_ix>zc_ix(i))-1;\nend\nn=size(G,2);\n\nif ~isempty(temp)\n temp_flag='y';\nelse\n temp_flag='n';\nend\n \n\nif strcmpi(temp_flag,'y')\n fprintf(' Estimating temperature correlation (elapsed time=%ds)\\n',round(toc))\n ix=abs(bperp)0); % segemnts after peak where rising\n if ~isempty(rising_ix)\n peak_end_ix=rising_ix(1)+coh_max_ix-1;\n else\n peak_end_ix=n_trials;\n end\n coh_trial(peak_start_ix:peak_end_ix)=0;\n if coh_max-max(coh_trial)>0.1 % diff between peak and next peak at least 0.1 \n K0=pi/4/temp_range_sub*trial_mult(coh_max_ix);\n resphase=cpxphase.*exp(-1i*(K0*temp_sub)); % subtract approximate fit\n offset_phase=sum(resphase);\n resphase=angle(resphase*conj(offset_phase)); % subtract offset, take angle (unweighted)\n weighting=abs(cpxphase); \n mopt=double(weighting.*temp_sub)\\double(weighting.*resphase);\n Kt(i)=K0+mopt;\n phase_residual=cpxphase.*exp(-1i*(Kt(i)*temp_sub)); \n mean_phase_residual=sum(phase_residual); \n coh(i)=abs(mean_phase_residual)/sum(abs(phase_residual)); \n end\n end\n \n clear cpxphase_mat trial_phase_mat phaser \n Kt(coh<0.31)=0; % not to be trusted;\n dph_space=dph_space.*exp(-1i*Kt*temp');\n if predef_flag=='y'\n dph_temp=Kt*temp';\n dph_space_uw=dph_space_uw-dph_temp(predef_ix);\n clear dph_temp\n end\n dph_sub=dph_sub.*exp(-1i*Kt*temp_sub');\n \nend\n\n\nif strcmpi(la_flag,'y') \n\n fprintf(' Estimating look angle error (elapsed time=%ds)\\n',round(toc))\n \n bperp_range=max(bperp)-min(bperp);\n ix=find(abs(diff(ifgday_ix,[],2))==1); \n\n if length(ix)>=length(day)-1 % if almost full chain is present\n fprintf(' using sequential daisy chain of interferograms\\n')\n dph_sub=dph_space(:,ix); % only ifgs using ith image\n bperp_sub=bperp(ix);\n bperp_range_sub=max(bperp_sub)-min(bperp_sub);\n n_trial_wraps=n_trial_wraps*(bperp_range_sub/bperp_range);\n else\n ifgs_per_image=sum(abs(G));\n [max_ifgs_per_image,max_ix]=max(ifgs_per_image);\n if max_ifgs_per_image>=length(day)-2; % can create chain from (almost) complete single master series\n fprintf(' Using sequential daisy chain of interferograms\\n')\n ix=G(:,max_ix)~=0;\n gsub=G(ix,max_ix);\n sign_ix=-sign(single(gsub'));\n dph_sub=dph_space(:,ix); % only ifgs using chosen master image\n bperp_sub=[bperp(ix)]; \n bperp_sub(sign_ix==-1)=-bperp_sub(sign_ix==-1);\n bperp_sub=[bperp_sub;0]; % add master\n sign_ix=repmat(sign_ix,ui.n_edge,1);\n dph_sub(sign_ix==-1)=conj(dph_sub(sign_ix==-1)); % flip sign if necessary to make ith image master \n dph_sub=[dph_sub,mean(abs(dph_sub),2)]; % add zero phase master\n slave_ix=sum(ifgday_ix(ix,:),2)-max_ix;\n day_sub=day([slave_ix;max_ix]); % extract days for subset\n [day_sub,sort_ix]=sort(day_sub); % sort ascending day\n dph_sub=dph_sub(:,sort_ix); % sort ascending day\n bperp_sub=bperp_sub(sort_ix);\n bperp_sub=diff(bperp_sub);\n bperp_range_sub=max(bperp_sub)-min(bperp_sub);\n n_trial_wraps=n_trial_wraps*(bperp_range_sub/bperp_range); \n n_sub=length(day_sub);\n dph_sub=dph_sub(:,[2:end]).*conj(dph_sub(:,1:end-1)); % sequential dph, to reduce influence of defo\n dph_sub=dph_sub./abs(dph_sub); % normalise\n else % just use all available\n dph_sub=dph_space;\n bperp_sub=bperp;\n bperp_range_sub=bperp_range;\n end\n end\n \n trial_mult=[-ceil(8*n_trial_wraps):ceil(8*n_trial_wraps)];\n n_trials=length(trial_mult);\n trial_phase=bperp_sub/bperp_range_sub*pi/4;\n trial_phase_mat=exp(-j*trial_phase*trial_mult);\n K=zeros(ui.n_edge,1,'single');\n coh=zeros(ui.n_edge,1,'single');\n for i=1:ui.n_edge\n cpxphase=dph_sub(i,:).';\n cpxphase_mat=repmat(cpxphase,1,n_trials);\n phaser=trial_phase_mat.*cpxphase_mat;\n phaser_sum=sum(phaser);\n coh_trial=abs(phaser_sum)/sum(abs(cpxphase));\n [coh_max,coh_max_ix]=max(coh_trial);\n falling_ix=find(diff(coh_trial(1:coh_max_ix))<0); % segemnts prior to peak where falling\n if ~isempty(falling_ix)\n peak_start_ix=falling_ix(end)+1;\n else\n peak_start_ix=1;\n end\n rising_ix=find(diff(coh_trial(coh_max_ix:end))>0); % segemnts after peak where rising\n if ~isempty(rising_ix)\n peak_end_ix=rising_ix(1)+coh_max_ix-1;\n else\n peak_end_ix=n_trials;\n end\n coh_trial(peak_start_ix:peak_end_ix)=0;\n if coh_max-max(coh_trial)>0.1 % diff between peak and next peak at least 0.1\n K0=pi/4/bperp_range_sub*trial_mult(coh_max_ix);\n resphase=cpxphase.*exp(-1i*(K0*bperp_sub)); % subtract approximate fit\n offset_phase=sum(resphase);\n resphase=angle(resphase*conj(offset_phase)); % subtract offset, take angle (unweighted)\n weighting=abs(cpxphase); \n mopt=double(weighting.*bperp_sub)\\double(weighting.*resphase);\n K(i)=K0+mopt;\n phase_residual=cpxphase.*exp(-1i*(K(i)*bperp_sub)); \n mean_phase_residual=sum(phase_residual); \n coh(i)=abs(mean_phase_residual)/sum(abs(phase_residual)); \n end\n end\n \n clear cpxphase_mat trial_phase_mat phaser dph_sub\n K(coh<0.31)=0; % not to be trusted;\n if strcmpi(temp_flag,'y')\n dph_space(K==0,:)=dph_space(K==0,:).*exp(1i*Kt(K==0)*temp'); % add back temp correction if not able to estimate DEM reliably\n Kt(K==0)=0;\n K(Kt==0)=0; \n end\n dph_space=dph_space.*exp(-1i*K*bperp');\n if predef_flag=='y'\n dph_scla=K*bperp';\n dph_space_uw=dph_space_uw-dph_scla(predef_ix);\n clear dph_scla\n end\n \nend\n\nspread=sparse(zeros(ui.n_edge,n_ifg));\n\nif strcmpi(unwrap_method,'2D')\n dph_space_uw=angle(dph_space);\n if strcmpi(la_flag,'y')\n dph_space_uw=dph_space_uw+K*bperp'; % equal to dph_space + integer cycles\n end\n if strcmpi(temp_flag,'y')\n dph_space_uw=dph_space_uw+Kt*temp'; % equal to dph_space + integer cycles\n end\n dph_noise=[];\n save('uw_space_time','dph_space_uw','spread','dph_noise'); \nelseif strcmpi(unwrap_method,'3D_NO_DEF')\n dph_noise=angle(dph_space);\n dph_space_uw=angle(dph_space); \n if strcmpi(la_flag,'y')\n dph_space_uw=dph_space_uw+K*bperp'; % equal to dph_space + integer cycles\n end\n if strcmpi(temp_flag,'y')\n dph_space_uw=dph_space_uw+Kt*temp'; % equal to dph_space + integer cycles\n end\n save('uw_space_time','dph_space_uw','dph_noise','spread');\nelse\n fprintf(' Smoothing in time (elapsed time=%ds)\\n',round(toc))\n \n if strcmpi(unwrap_method,'3D_FULL') \n \n dph_smooth_ifg=nan(size(dph_space),'single');\n \n for i=1:n_image\n ix=G(:,i)~=0;\n if sum(ix)>=n_image-2 % allow only 1 missing ifg for each image as master\n gsub=G(ix,i);\n dph_sub=dph_space(:,ix); % only ifgs using ith image\n sign_ix=repmat(-sign(single(gsub')),ui.n_edge,1);\n dph_sub(sign_ix==-1)=conj(dph_sub(sign_ix==-1)); % flip sign if necessary to make ith image master \n slave_ix=sum(ifgday_ix(ix,:),2)-i;\n day_sub=day(slave_ix); % extract days for subset\n [day_sub,sort_ix]=sort(day_sub); % sort ascending day\n dph_sub=dph_sub(:,sort_ix); % sort ascending day\n dph_sub_angle=angle(dph_sub);\n n_sub=length(day_sub);\n dph_smooth=zeros(ui.n_edge,n_sub,'single');\n for i1=1:n_sub\n time_diff=(day_sub(i1)-day_sub)';\n weight_factor=exp(-(time_diff.^2)/2/time_win^2);\n weight_factor=weight_factor/sum(weight_factor);\n\n dph_mean=sum(dph_sub.*repmat(weight_factor,ui.n_edge,1),2);\n %dph_mean_adj=angle(dph_sub.*repmat(conj(dph_mean),1,n_sub)); % subtract weighted mean\n dph_mean_adj=mod(dph_sub_angle-repmat(angle(dph_mean),1,n_sub)+pi,2*pi)-pi;\n GG=[ones(n_sub,1),time_diff'];\n if size(GG,1)>1\n m=lscov(GG,double(dph_mean_adj)',weight_factor);\n else\n m=zeros(size(GG,1),ui.n_edge);\n end\n %dph_mean_adj=mod(dph_mean_adj-(GG*m)'+pi,2*pi)-pi; % subtract first estimate\n %m2=lscov(GG,double(dph_mean_adj)',weight_factor);\n %dph_smooth(:,i1)=dph_mean.*exp(1i*(m(1,:)'+m2(1,:)')); % add back weighted mean\n dph_smooth(:,i1)=dph_mean.*exp(1i*(m(1,:)')); % add back weighted mean\n end\n dph_smooth_sub=cumsum([angle(dph_smooth(:,1)),angle(dph_smooth(:,2:end).*conj(dph_smooth(:,1:end-1)))],2);\n close_master_ix=find(slave_ix-i>0);\n if isempty(close_master_ix)\n close_master_ix=n_sub;\n else\n close_master_ix=close_master_ix(1);\n if close_master_ix>1\n close_master_ix=[close_master_ix-1;close_master_ix];\n end\n end\n dph_close_master=mean(dph_smooth_sub(:,close_master_ix),2);\n dph_smooth_sub=dph_smooth_sub-repmat(dph_close_master-angle(exp(j*dph_close_master)),1,n_sub);\n dph_smooth_sub=dph_smooth_sub.*sign_ix;\n already_sub_ix=find(~isnan(dph_smooth_ifg(1,ix))); % already unwrapped index\n ix=find(ix);\n already_ix=ix(already_sub_ix);\n std_noise1=std(angle(dph_space(:,already_ix).*exp(-1i*dph_smooth_ifg(:,already_ix))));\n std_noise2=std(angle(dph_space(:,already_ix).*exp(-1i*dph_smooth_sub(:,already_sub_ix))));\n keep_ix=true(n_sub,1);\n keep_ix(already_sub_ix(std_noise11.2,:)=nan;\n \n else\n x=(day-day(1))*(n-1)/(day(end)-day(1)); % use dates for smoothing\n if predef_flag=='y'\n n_dph=size(dph_space,1);\n dph_space_angle=double(angle(dph_space));\n dph_space_angle(predef_ix)=dph_space_uw;\n dph_space_series=zeros(n,n_dph);\n for i=1:n_dph\n W=predef_ix(i,:)+0.01; % give more weight to the predfined unwrapped\n dph_space_series(2:end,i)=lscov(double(G(:,2:end)),dph_space_angle(i,:)',W);\n end\n else\n dph_space_series=[zeros(1,ui.n_edge);double(G(:,2:end))\\double(angle(dph_space))'];\n end\n \n dph_smooth_series=zeros(size(G,2),ui.n_edge,'single');\n\n for i1=1:n\n time_diff_sq=(day(i1)-day).^2;\n weight_factor=exp(-time_diff_sq/2/time_win^2);\n weight_factor=weight_factor/sum(weight_factor);\n dph_smooth_series(i1,:)=sum(dph_space_series.*repmat(weight_factor,1,ui.n_edge));\n end\n\n dph_smooth_ifg=(G*dph_smooth_series)';\n dph_noise=angle(dph_space.*exp(-1i*dph_smooth_ifg));\n\n if strcmpi(unwrap_method,'3D_SMALL_DEF')|...\n strcmpi(unwrap_method,'3D_QUICK')\n not_small_ix=find(std(dph_noise,0,2)>1.3)';\n fprintf(' %d edges with high std dev in time (elapsed time=%ds)\\n',length(not_small_ix),round(toc))\n dph_noise(not_small_ix,:)=nan;\n else % 3D\n uw=load('uw_grid');\n ph_noise=angle(uw.ph.*conj(uw.ph_lowpass));\n clear uw\n dph_noise_sf=((ph_noise(ui.edgs(:,3),:)-(ph_noise(ui.edgs(:,2),:)))); \n m_minmax=repmat([-pi,pi],5,1).*repmat([0.5;0.25;1;0.25;1],1,2);\n anneal_opts=[1;15;0;0;0;0;0];\n covm=cov((dph_noise_sf)); % estimate of covariance\n [W,P]=chol(inv(covm)); % weighting matrix \n if P~=0\n W=diag(1./sqrt(diag(covm)));\n end\n not_small_ix=find(std(dph_noise,0,2)>1)';\n fprintf(' Performing complex smoothing on %d edges (elapsed time=%ds)\\n',length(not_small_ix),round(toc))\n\n n_proc=0;\n for i=not_small_ix\n dph=angle(dph_space(i,:))';\n dph_smooth_series(:,i)=uw_sb_smooth_unwrap(m_minmax,anneal_opts,G,W,dph,x);\n\n n_proc=n_proc+1;\n if round(n_proc/1000)==n_proc/1000\n save('uw_unwrap_time','G','dph_space','dph_smooth_series');\n fprintf('%d edges of %d reprocessed (elapsed time=%ds)\\n',n_proc,length(not_small_ix),round(toc))\n end\n end\n dph_smooth_ifg=(G*dph_smooth_series)';\n dph_noise=angle(dph_space.*exp(-1i*dph_smooth_ifg));\n end\n end\n clear dph_space\n dph_space_uw=dph_smooth_ifg+dph_noise;\n clear dph_smooth_ifg\n \n if strcmpi(la_flag,'y')\n dph_space_uw=dph_space_uw+K*bperp'; % equal to dph_space + integer cycles\n end\n if strcmpi(temp_flag,'y')\n dph_space_uw=dph_space_uw+Kt*temp'; % equal to dph_space + integer cycles\n end\n \n if strcmpi(scf_flag,'y')\n \n fprintf(' Calculating local phase gradients (elapsed time=%ds)\\n',round(toc))\n ifreq_ij=nan(n_ps,n_ifg,'single');\n jfreq_ij=nan(n_ps,n_ifg,'single');\n ifgw=zeros(nrow,ncol);\n uw=load('uw_grid');\n for i=1:n_ifg\n ifgw(nzix)=uw.ph(:,i);\n [ifreq,jfreq,grad_ij,Hmag]=gradient_filt(ifgw,prefilt_win);\n ix=~isnan(ifreq)&Hmag./((abs(ifreq))+1)>3;\n if sum(ix(:))>2\n ifreq_ij(:,i)=griddata(grad_ij(ix,2),grad_ij(ix,1),ifreq(ix),ij(:,2),ij(:,1),'linear');\n end\n ix=~isnan(jfreq)&Hmag./((abs(jfreq))+1)>3;\n if sum(ix(:))>2\n jfreq_ij(:,i)=griddata(grad_ij(ix,2),grad_ij(ix,1),jfreq(ix),ij(:,2),ij(:,1),'linear');\n end\n end\n clear uw\n \n spread2=zeros(size(spread),'single');\n dph_smooth_uw2=nan(ui.n_edge,n_ifg,'single');\n \n fprintf(' Smoothing using local phase gradients (elapsed time=%ds)\\n',round(toc))\n for i=1:ui.n_edge\n nodes_ix=ui.edgs(i,[2:3]);\n ifreq_edge=mean(ifreq_ij(nodes_ix,:));\n jfreq_edge=mean(jfreq_ij(nodes_ix,:));\n diff_i=diff(ij(nodes_ix,1));\n diff_j=diff(ij(nodes_ix,2));\n dph_smooth_uw2(i,:)=diff_i*ifreq_edge+diff_j*jfreq_edge;\n% spread2(i,:)=diff_i*diff(ifreq_ij(nodes_ix,:))+diff_j*diff(jfreq_ij(nodes_ix,:));\n spread2(i,:)=diff(ifreq_ij(nodes_ix,:))+diff(jfreq_ij(nodes_ix,:));\n end\n fprintf(' Choosing between time and phase gradient smoothing (elapsed time=%ds)\\n',round(toc)) \n std_noise=std(dph_noise,0,2);\n dph_noise2=angle(exp(j*(dph_space_uw-dph_smooth_uw2)));\n std_noise2=std(dph_noise2,0,2);\n dph_noise2(std_noise2>1.3,:)=nan;\n shaky_ix=isnan(std_noise) | std_noise>std_noise2; % spatial smoothing works better index\n \n fprintf(' %d arcs smoothed in time, %d in space (elapsed time=%ds)\\n',ui.n_edge-sum(shaky_ix),sum(shaky_ix),round(toc)) \n\n dph_noise(shaky_ix,:)=dph_noise2(shaky_ix,:);\n dph_space_uw(shaky_ix,:)=dph_smooth_uw2(shaky_ix,:)+dph_noise2(shaky_ix,:);\n spread(shaky_ix,:)=spread2(shaky_ix,:);\n else\n shaky_ix=[];\n end\n \n save('uw_space_time','dph_space_uw','dph_noise','G','spread','ifreq_ij','jfreq_ij','shaky_ix','predef_ix');\nend\n", "meta": {"author": "dbekaert", "repo": "StaMPS", "sha": "c159eb81b16c446e0e8fdef7dd435eb22e0240ed", "save_path": "github-repos/MATLAB/dbekaert-StaMPS", "path": "github-repos/MATLAB/dbekaert-StaMPS/StaMPS-c159eb81b16c446e0e8fdef7dd435eb22e0240ed/matlab/uw_sb_unwrap_space_time.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.39606816627404173, "lm_q1q2_score": 0.3078637306605271}} {"text": "function [DEM] = spm_ADEM(DEM)\n% Dynamic expectation maximisation: Active inversion\n% FORMAT DEM = spm_ADEM(DEM)\n%\n% DEM.G - generative process\n% DEM.M - recognition model\n% DEM.C - causes\n% DEM.U - prior expectation of causes\n%__________________________________________________________________________\n%\n% This implementation of DEM is the same as spm_DEM but integrates both the\n% generative process and model inversion in parallel. Its functionality is \n% exactly the same apart from the fact that confounds are not accommodated\n% explicitly. The generative model is specified by DEM.G and the veridical\n% causes by DEM.C; these may or may not be used as priors on the causes for\n% the inversion model DEM.M (i.e., DEM.U = DEM.C). Clearly, DEM.G does not\n% require any priors or precision components; it will use the values of the\n% parameters specified in the prior expectation fields.\n%\n% This routine is not used for model inversion per se but to simulate the\n% dynamical inversion of models. Critically, it includes action \n% variables a - that couple the model back to the generative process \n% This enables active inference (c.f., action-perception) or embodied \n% inference.\n%\n% hierarchical models M(i)\n%--------------------------------------------------------------------------\n% M(i).g = y(t) = g(x,v,P) {inline function, string or m-file}\n% M(i).f = dx/dt = f(x,v,P) {inline function, string or m-file}\n%\n% M(i).pE = prior expectation of p model-parameters\n% M(i).pC = prior covariances of p model-parameters\n% M(i).hE = prior expectation of h hyper-parameters (cause noise)\n% M(i).hC = prior covariances of h hyper-parameters (cause noise)\n% M(i).gE = prior expectation of g hyper-parameters (state noise)\n% M(i).gC = prior covariances of g hyper-parameters (state noise)\n% M(i).Q = precision components (input noise)\n% M(i).R = precision components (state noise)\n% M(i).V = fixed precision (input noise)\n% M(i).W = fixed precision (state noise)\n% M(i).xP = precision (states)\n%\n% M(i).m = number of inputs v(i + 1);\n% M(i).n = number of states x(i)\n% M(i).l = number of output v(i)\n% M(i).k = number of action a(i)\n\n% hierarchical process G(i)\n%--------------------------------------------------------------------------\n% G(i).g = y(t) = g(x,v,a,P) {inline function, string or m-file}\n% G(i).f = dx/dt = f(x,v,a,P) {inline function, string or m-file}\n%\n% G(i).pE = model-parameters\n% G(i).U = precision (action)\n% G(i).V = precision (input noise)\n% G(i).W = precision (state noise)\n%\n% G(1).R = restriction or rate matrix for action [default: 1];\n% G(i).aP = precision (action) [default: exp(-2)]\n%\n% G(i).m = number of inputs v(i + 1);\n% G(i).n = number of states x(i)\n% G(i).l = number of output v(i)\n% G(i).k = number of action a(i)\n%\n%\n% Returns the following fields of DEM\n%--------------------------------------------------------------------------\n%\n% true model-states - u\n%--------------------------------------------------------------------------\n% pU.x = true hidden states\n% pU.v = true causal states v{1} = response (Y)\n% pU.C = prior covariance: cov(v)\n% pU.S = prior covariance: cov(x)\n%\n% model-parameters - p\n%--------------------------------------------------------------------------\n% pP.P = parameters for each level\n%\n% hyper-parameters (log-transformed) - h,g\n%--------------------------------------------------------------------------\n% pH.h = cause noise\n% pH.g = state noise\n%\n% conditional moments of model-states - q(u)\n%--------------------------------------------------------------------------\n% qU.a = Action\n% qU.x = Conditional expectation of hidden states\n% qU.v = Conditional expectation of causal states\n% qU.z = Conditional prediction errors (v)\n% qU.C = Conditional covariance: cov(v)\n% qU.S = Conditional covariance: cov(x)\n%\n% conditional moments of model-parameters - q(p)\n%--------------------------------------------------------------------------\n% qP.P = Conditional expectation\n% qP.C = Conditional covariance\n%\n% conditional moments of hyper-parameters (log-transformed) - q(h)\n%--------------------------------------------------------------------------\n% qH.h = Conditional expectation (cause noise)\n% qH.g = Conditional expectation (state noise)\n% qH.C = Conditional covariance\n%\n% F = log evidence = log marginal likelihood = negative free energy\n%__________________________________________________________________________\n%\n% spm_ADEM implements a variational Bayes (VB) scheme under the Laplace\n% approximation to the conditional densities of states (u), parameters (p)\n% and hyperparameters (h) of any analytic nonlinear hierarchical dynamic\n% model, with additive Gaussian innovations. It comprises three\n% variational steps (D,E and M) that update the conditional moments of u, p\n% and h respectively\n%\n% D: qu.u = max q(p,h)\n% E: qp.p = max q(u,h)\n% M: qh.h = max q(u,p)\n%\n% where qu.u corresponds to the conditional expectation of hidden states x\n% and causal states v and so on. L is the ln p(y,u,p,h|M) under the model\n% M. The conditional covariances obtain analytically from the curvature of\n% L with respect to u, p and h.\n%\n% The D-step is embedded in the E-step because q(u) changes with each\n% sequential observation. The dynamical model is transformed into a static\n% model using temporal derivatives at each time point. Continuity of the\n% conditional trajectories q(u,t) is assured by a continuous ascent of F(t)\n% in generalised co-ordinates. This means DEM can deconvolve online and \n% represents an alternative to Kalman filtering or alternative Bayesian\n% update procedures.\n%\n%__________________________________________________________________________\n% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging\n \n% Karl Friston\n% $Id: spm_ADEM.m 7679 2019-10-24 15:54:07Z spm $\n \n% check model, data, priors and unpack\n%--------------------------------------------------------------------------\nDEM = spm_ADEM_set(DEM);\nM = DEM.M;\nG = DEM.G;\nC = DEM.C;\nU = DEM.U;\n\n% check whether to print \n%--------------------------------------------------------------------------\ntry\n db = DEM.db;\ncatch\n db = 1;\nend\n\n% find or create a DEM figure\n%--------------------------------------------------------------------------\nif db\n Fdem = spm_figure('GetWin','DEM');\nend\n \n% ensure embedding dimensions are compatible\n%--------------------------------------------------------------------------\nG(1).E.n = M(1).E.n;\nG(1).E.d = M(1).E.n;\n \n\n% order parameters (d = n = 1 for static models) and checks\n%==========================================================================\nd = M(1).E.d + 1; % embedding order of q(v)\nn = M(1).E.n + 1; % embedding order of q(x)\ns = M(1).E.s; % smoothness - s.d. (bins)\n\n\n% number of states and parameters - generative model\n%--------------------------------------------------------------------------\nnY = size(C,2); % number of samples\nnl = size(M,2); % number of levels\nnv = sum(spm_vec(M.m)); % number of v (causal states)\nnx = sum(spm_vec(M.n)); % number of x (hidden states)\nny = M(1).l; % number of y (inputs)\nnc = M(end).l; % number of c (prior causes)\nnu = nv*d + nx*n; % number of generalised states\n \n% number of states and parameters - generative process\n%--------------------------------------------------------------------------\ngr = sum(spm_vec(G.l)); % number of v (outputs)\nga = sum(spm_vec(G.k)); % number of a (active states)\ngx = sum(spm_vec(G.n)); % number of x (hidden states)\ngy = G(1).l; % number of y (inputs)\nna = ga; % number of a (action)\n \n% number of iterations\n%--------------------------------------------------------------------------\ntry, nE = M(1).E.nE; catch, nE = 16; end\ntry, nM = M(1).E.nM; catch, nM = 8; end\ntry, dt = M(1).E.dt; catch, dt = 1; end\n \n \n% initialise regularisation parameters\n%--------------------------------------------------------------------------\nte = 2; % log integration time for E-Step\nglobal t\n\n\n% precision (roughness) of generalised fluctuations\n%--------------------------------------------------------------------------\niV = spm_DEM_R(n,s);\niG = spm_DEM_R(n,s);\n\n% time-delay operators (absorb motor delays into motor gain matrix)\n%--------------------------------------------------------------------------\ntry\n nG = norm(iG);\n iG = iG*spm_DEM_T(n,-M(1).Ta);\n iG = iG*nG/norm(iG);\nend\ntry\n Ty = spm_DEM_T(n,-M(1).Ty);\n Ty = kron(Ty,speye(ny,ny));\nend\n \n% precision components Q{} requiring [Re]ML estimators (M-Step)\n%==========================================================================\nQ = {};\nfor i = 1:nl\n q0{i,i} = sparse(M(i).l,M(i).l); %#ok\n r0{i,i} = sparse(M(i).n,M(i).n);\nend\nQ0 = kron(iV,spm_cat(q0));\nR0 = kron(iV,spm_cat(r0));\nfor i = 1:nl\n for j = 1:length(M(i).Q)\n q = q0;\n q{i,i} = M(i).Q{j};\n Q{end + 1} = blkdiag(kron(iV,spm_cat(q)),R0);\n end\n for j = 1:length(M(i).R)\n q = r0;\n q{i,i} = M(i).R{j};\n Q{end + 1} = blkdiag(Q0,kron(iV,spm_cat(q)));\n end\nend\n \n \n% and fixed components P\n%--------------------------------------------------------------------------\nQ0 = kron(iV,spm_cat(spm_diag({M.V})));\nR0 = kron(iV,spm_cat(spm_diag({M.W})));\nQp = blkdiag(Q0,R0);\nnh = length(Q); % number of hyperparameters\niR = [zeros(1,ny),ones(1,nv),ones(1,nx)]; % for empirical priors\niR = kron(speye(n,n),diag(iR)); \n\n% restriction or rate matrices - in terms of precision\n%--------------------------------------------------------------------------\nq0{1} = G(1).U;\nQ0 = kron(iG,spm_cat(q0));\nR0 = kron(iG,spm_cat(r0));\niG = blkdiag(Q0,R0);\n\n% restriction or rate matrices - in terms of dE/da\n%--------------------------------------------------------------------------\ntry\n R = sparse(sum(spm_vec(G.l)),na);\n R(1:ny,:) = G(1).R;\n R = kron(spm_speye(n,1,0),R);\ncatch\n R = 1;\nend\n\n% fixed priors on action (a)\n%--------------------------------------------------------------------------\ntry\n aP = G(1).aP;\ncatch\n aP = exp(-2);\nend\n\n% fixed priors on states (u)\n%--------------------------------------------------------------------------\nxP = spm_cat(spm_diag({M.xP}));\nPx = kron(iV(1:n,1:n),speye(nx,nx)*exp(-8) + xP);\nPv = kron(iV(1:d,1:d),speye(nv,nv)*exp(-8));\nPa = spm_speye(na,na)*aP;\nPu = spm_cat(spm_diag({Px Pv}));\n \n% hyperpriors\n%--------------------------------------------------------------------------\nph.h = spm_vec({M.hE M.gE}); % prior expectation of h\nph.c = spm_cat(spm_diag({M.hC M.gC})); % prior covariances of h\nqh.h = ph.h; % conditional expectation\nqh.c = ph.c; % conditional covariance\nph.ic = spm_inv(ph.c); % prior precision\n \n% priors on parameters (in reduced parameter space)\n%==========================================================================\npp.c = cell(nl,nl);\nqp.p = cell(nl,1);\nfor i = 1:(nl - 1)\n \n % eigenvector reduction: p <- pE + qp.u*qp.p\n %----------------------------------------------------------------------\n qp.u{i} = spm_svd(M(i).pC); % basis for parameters\n M(i).p = size(qp.u{i},2); % number of qp.p\n qp.p{i} = sparse(M(i).p,1); % initial qp.p\n pp.c{i,i} = qp.u{i}'*M(i).pC*qp.u{i}; % prior covariance\n \n try\n qp.e{i} = qp.p{i} + qp.u{i}'*(spm_vec(M(i).P) - spm_vec(M(i).pE));\n catch\n qp.e{i} = qp.p{i}; % initial qp.e\n end\n \nend\nUp = spm_cat(spm_diag(qp.u));\n \n% initialise and augment with confound parameters B; with flat priors\n%--------------------------------------------------------------------------\nnp = sum(spm_vec(M.p)); % number of model parameters\npp.c = spm_cat(pp.c);\npp.ic = spm_inv(pp.c);\n \n% initialise conditional density q(p) (for D-Step)\n%--------------------------------------------------------------------------\nqp.e = spm_vec(qp.e);\nqp.c = sparse(np,np);\n \n% initialise cell arrays for D-Step; e{i + 1} = (d/dt)^i[e] = e[i]\n%==========================================================================\nqu.x = cell(n,1);\nqu.v = cell(n,1);\nqu.a = cell(1,1);\nqu.y = cell(n,1);\nqu.u = cell(n,1);\npu.v = cell(n,1);\npu.x = cell(n,1);\npu.z = cell(n,1);\npu.w = cell(n,1);\n \n[qu.x{:}] = deal(sparse(nx,1));\n[qu.v{:}] = deal(sparse(nv,1));\n[qu.a{:}] = deal(sparse(na,1));\n[qu.y{:}] = deal(sparse(ny,1));\n[qu.u{:}] = deal(sparse(nc,1));\n[pu.v{:}] = deal(sparse(gr,1));\n[pu.x{:}] = deal(sparse(gx,1));\n[pu.z{:}] = deal(sparse(gr,1));\n[pu.w{:}] = deal(sparse(gx,1));\n \n% initialise cell arrays for hierarchical structure of x[0] and v[0]\n%--------------------------------------------------------------------------\nqu.x{1} = spm_vec({M(1:end - 1).x});\nqu.v{1} = spm_vec({M(1 + 1:end).v});\nqu.a{1} = spm_vec({G.a});\npu.x{1} = spm_vec({G.x});\npu.v{1} = spm_vec({G.v});\n \n \n% derivatives for Jacobian of D-step\n%--------------------------------------------------------------------------\nDx = kron(spm_speye(n,n,1),spm_speye(nx,nx,0));\nDv = kron(spm_speye(d,d,1),spm_speye(nv,nv,0));\nDc = kron(spm_speye(d,d,1),spm_speye(nc,nc,0));\nDa = kron(spm_speye(1,1,1),sparse(na,na));\nDu = spm_cat(spm_diag({Dx,Dv}));\nDq = spm_cat(spm_diag({Dx,Dv,Dc,Da}));\n \nDx = kron(spm_speye(n,n,1),spm_speye(gx,gx,0));\nDv = kron(spm_speye(n,n,1),spm_speye(gr,gr,0));\nDp = spm_cat(spm_diag({Dv,Dx,Dv,Dx}));\ndfdw = kron(speye(n,n),speye(gx,gx));\ndydv = kron(speye(n,n),speye(gy,gr));\n \n% and null blocks\n%--------------------------------------------------------------------------\ndVdc = sparse(d*nc,1);\n \n% gradients and curvatures for conditional uncertainty\n%--------------------------------------------------------------------------\ndWdu = sparse(nu,1);\ndWduu = sparse(nu,nu);\n \n% preclude unnecessary iterations\n%--------------------------------------------------------------------------\nif ~np && ~nh, nE = 1; end\n \n \n% create innovations (and add causes)\n%--------------------------------------------------------------------------\n[z,w] = spm_DEM_z(G,nY);\nz{end} = C + z{end};\na = {G.a};\nZ = spm_cat(z(:));\nW = spm_cat(w(:));\nA = spm_cat(a(:));\n \n% Iterate DEM\n%==========================================================================\nF = -Inf;\nfor iE = 1:nE\n \n % get time and clear persistent variables in evaluation routines\n %----------------------------------------------------------------------\n tic; clear spm_DEM_eval\n \n % E-Step: (with embedded D-Step)\n %======================================================================\n \n % [re-]set accumulators for E-Step\n %----------------------------------------------------------------------\n dFdp = zeros(np,1);\n dFdpp = zeros(np,np);\n EE = sparse(0);\n ECE = sparse(0);\n EiSE = sparse(0);\n qp.ic = sparse(0);\n Hqu.c = sparse(0);\n \n \n % [re-]set precisions using [hyper]parameter estimates\n %----------------------------------------------------------------------\n iS = Qp;\n for i = 1:nh\n iS = iS + Q{i}*exp(qh.h(i));\n end\n \n % precision for empirical priors\n %----------------------------------------------------------------------\n iP = iR*iS*iR;\n \n % [re-]set states & their derivatives\n %----------------------------------------------------------------------\n try\n qu = qU(1);\n pu = pU(1);\n end\n \n % D-Step: (nY samples)\n %======================================================================\n for iY = 1:nY\n \n % time (GLOBAL variable for non-automomous systems)\n %------------------------------------------------------------------\n t = iY/nY;\n \n % pass action to pu.a (external states)\n %==================================================================\n try, A = spm_cat({qU.a qu.a}); end\n \n % derivatives of responses and random fluctuations\n %------------------------------------------------------------------\n pu.z = spm_DEM_embed(Z,n,iY);\n pu.w = spm_DEM_embed(W,n,iY);\n pu.a = spm_DEM_embed(A,n,iY);\n qu.u = spm_DEM_embed(U,n,iY);\n \n \n % evaluate generative process\n %------------------------------------------------------------------\n [pu,dg,df] = spm_ADEM_diff(G,pu);\n \n \n % and pass response to qu.y\n %==================================================================\n for i = 1:n\n y = spm_unvec(pu.v{i},{G.v});\n qu.y{i} = y{1};\n end\n \n % sensory delays\n %------------------------------------------------------------------\n try, qu.y = spm_unvec(Ty*spm_vec(qu.y),qu.y); end\n \n \n % evaluate generative model\n %------------------------------------------------------------------ \n [E,dE] = spm_DEM_eval(M,qu,qp);\n \n \n % conditional covariance [of states {u}]\n %------------------------------------------------------------------\n qu.c = spm_inv(dE.du'*iS*dE.du + Pu);\n pu.c = spm_inv(dE.du'*iP*dE.du + Pu);\n Hqu.c = Hqu.c + spm_logdet(qu.c);\n \n % save at qu(t)\n %------------------------------------------------------------------\n qE{iY} = E;\n qC{iY} = qu.c;\n pC{iY} = pu.c;\n qU(iY) = qu;\n pU(iY) = pu;\n \n % and conditional precision\n %------------------------------------------------------------------\n if nh\n ECEu = dE.du*qu.c*dE.du';\n ECEp = dE.dp*qp.c*dE.dp';\n end\n \n \n % uncertainty about parameters dWdv, ... ; W = ln(|qp.c|)\n %==================================================================\n if np\n for i = 1:nu\n CJp(:,i) = spm_vec(qp.c*dE.dpu{i}'*iS);\n dEdpu(:,i) = spm_vec(dE.dpu{i}');\n end\n dWdu = CJp'*spm_vec(dE.dp');\n dWduu = CJp'*dEdpu;\n end\n \n % tensor products for Jacobian (generative process)\n %------------------------------------------------------------------\n Dgda = kron(spm_speye(n,1,1),dg.da);\n Dgdv = kron(spm_speye(n,n,1),dg.dv);\n Dgdx = kron(spm_speye(n,n,1),dg.dx);\n dfda = kron(spm_speye(n,1,0),df.da);\n dfdv = kron(spm_speye(n,n,0),df.dv);\n dfdx = kron(spm_speye(n,n,0),df.dx);\n \n dgda = kron(spm_speye(n,1,0),dg.da);\n dgdx = kron(spm_speye(n,n,0),dg.dx);\n \n % change in error w.r.t. action\n %------------------------------------------------------------------\n Dfdx = 0;\n for i = 1:n\n Dfdx = Dfdx + kron(spm_speye(n,n,-i),df.dx^(i - 1));\n end\n \n % dE/da with restriction (R)\n %------------------------------------------------------------------\n dE.dv = dE.dy*dydv;\n dE.da = dE.dv*((dgda + dgdx*Dfdx*dfda).*R);\n\n \n % first-order derivatives\n %------------------------------------------------------------------\n dVdu = -dE.du'*iS*E - Pu*spm_vec({qu.x{1:n} qu.v{1:d}}) - dWdu/2;\n dVda = -dE.da'*iG*E - Pa*spm_vec( qu.a{1:1});\n \n \n % and second-order derivatives\n %------------------------------------------------------------------\n dVduu = -dE.du'*iS*dE.du - Pu - dWduu/2 ;\n dVdaa = -dE.da'*iG*dE.da - Pa;\n dVduv = -dE.du'*iS*dE.dv;\n dVduc = -dE.du'*iS*dE.dc;\n dVdua = -dE.du'*iS*dE.da;\n dVdav = -dE.da'*iG*dE.dv;\n dVdau = -dE.da'*iG*dE.du;\n dVdac = -dE.da'*iG*dE.dc;\n \n \n % D-step update: of causes v{i}, and hidden states x(i)\n %==================================================================\n \n % states and conditional modes\n %------------------------------------------------------------------\n p = {pu.v{1:n} pu.x{1:n} pu.z{1:n} pu.w{1:n}};\n q = {qu.x{1:n} qu.v{1:d} qu.u{1:d} qu.a{1:1}};\n u = [p q]; \n \n % gradient\n %------------------------------------------------------------------\n dFdu = [ Dp*spm_vec(p); \n spm_vec({dVdu; dVdc; dVda}) + Dq*spm_vec(q)];\n \n \n % Jacobian (variational flow)\n %------------------------------------------------------------------\n dFduu = spm_cat(...\n {Dgdv Dgdx Dv [] [] [] Dgda;\n dfdv dfdx [] dfdw [] [] dfda;\n [] [] Dv [] [] [] [];\n [] [] [] Dx [] [] [];\n dVduv [] [] [] Du+dVduu dVduc dVdua;\n [] [] [] [] [] Dc []\n dVdav [] [] [] dVdau dVdac dVdaa});\n \n \n % update states q = {x,v,z,w} and conditional modes\n %==================================================================\n du = spm_dx(dFduu,dFdu,dt);\n u = spm_unvec(spm_vec(u) + du,u);\n \n % and save them\n %------------------------------------------------------------------\n pu.v(1:n) = u((1:n));\n pu.x(1:n) = u((1:n) + n);\n qu.x(1:n) = u((1:n) + n + n + n + n);\n qu.v(1:d) = u((1:d) + n + n + n + n + n);\n qu.a(1:1) = u((1:1) + n + n + n + n + n + d + d);\n \n\n % Gradients and curvatures for E-Step: W = tr(C*J'*iS*J)\n %==================================================================\n if np\n for i = 1:np\n CJu(:,i) = spm_vec(qu.c*dE.dup{i}'*iS);\n dEdup(:,i) = spm_vec(dE.dup{i}');\n end\n dWdp = CJu'*spm_vec(dE.du');\n dWdpp = CJu'*dEdup;\n \n % Accumulate; dF/dP =
, dF/dpp = ...\n %--------------------------------------------------------------\n dFdp = dFdp - dWdp/2 - dE.dp'*iS*E;\n dFdpp = dFdpp - dWdpp/2 - dE.dp'*iS*dE.dp;\n qp.ic = qp.ic + dE.dp'*iS*dE.dp;\n \n end\n \n % accumulate SSE\n %------------------------------------------------------------------\n EiSE = EiSE + E'*iS*E;\n \n % and quantities for M-Step\n %------------------------------------------------------------------\n if nh\n EE = E*E'+ EE;\n ECE = ECE + ECEu + ECEp;\n end\n \n if nE == 1\n \n % evaluate objective function (F)\n %======================================================================\n J(iY) = - trace(E'*iS*E)/2 ... % states (u)\n + spm_logdet(qu.c) ... % entropy q(u)\n + spm_logdet(iS)/2; % entropy - error\n end\n \n end % sequence (nY)\n \n % augment with priors\n %----------------------------------------------------------------------\n dFdp = dFdp - pp.ic*qp.e;\n dFdpp = dFdpp - pp.ic;\n qp.ic = qp.ic + pp.ic;\n qp.c = spm_inv(qp.ic);\n \n \n % E-step: update expectation (p)\n %======================================================================\n \n % update conditional expectation\n %----------------------------------------------------------------------\n dp = spm_dx(dFdpp,dFdp,{te});\n qp.e = qp.e + dp;\n qp.p = spm_unvec(qp.e,qp.p);\n \n \n % M-step - hyperparameters (h = exp(l))\n %======================================================================\n mh = zeros(nh,1);\n dFdh = zeros(nh,1);\n dFdhh = zeros(nh,nh);\n for iM = 1:nM\n \n % [re-]set precisions using [hyper]parameter estimates\n %------------------------------------------------------------------\n iS = Qp;\n for i = 1:nh\n iS = iS + Q{i}*exp(qh.h(i));\n end\n S = spm_inv(iS);\n dS = ECE + EE - S*nY;\n \n % 1st-order derivatives: dFdh = dF/dh\n %------------------------------------------------------------------\n for i = 1:nh\n dPdh{i} = Q{i}*exp(qh.h(i));\n dFdh(i,1) = -trace(dPdh{i}*dS)/2;\n end\n \n % 2nd-order derivatives: dFdhh\n %------------------------------------------------------------------\n for i = 1:nh\n for j = 1:nh\n dFdhh(i,j) = -trace(dPdh{i}*S*dPdh{j}*S*nY)/2;\n end\n end\n \n % hyperpriors\n %------------------------------------------------------------------\n qh.e = qh.h - ph.h;\n dFdh = dFdh - ph.ic*qh.e;\n dFdhh = dFdhh - ph.ic;\n \n % update ReML estimate of parameters\n %------------------------------------------------------------------\n dh = spm_dx(dFdhh,dFdh);\n qh.h = qh.h + dh;\n mh = mh + dh;\n \n % conditional covariance of hyperparameters\n %------------------------------------------------------------------\n qh.c = -spm_inv(dFdhh);\n \n % convergence (M-Step)\n %------------------------------------------------------------------\n if (dFdh'*dh < 1e-2) || (norm(dh,1) < exp(-8)), break, end\n \n end % M-Step\n \n % evaluate objective function (F)\n %======================================================================\n L = - trace(EiSE)/2 ... % states (u)\n - trace(qp.e'*pp.ic*qp.e)/2 ... % parameters (p)\n - trace(qh.e'*ph.ic*qh.e)/2 ... % hyperparameters (h)\n + Hqu.c/2 ... % entropy q(u)\n + spm_logdet(qp.c)/2 ... % entropy q(p)\n + spm_logdet(qh.c)/2 ... % entropy q(h)\n - spm_logdet(pp.c)/2 ... % entropy - prior p\n - spm_logdet(ph.c)/2 ... % entropy - prior h\n + spm_logdet(iS)*nY/2 ... % entropy - error\n - n*ny*nY*log(2*pi)/2;\n \n \n % if F is increasing, save expansion point and derivatives\n %----------------------------------------------------------------------\n if L > F(end) || iE < 3\n \n % save model-states (for each time point)\n %==================================================================\n for t = 1:length(qU)\n \n % states\n %--------------------------------------------------------------\n a = spm_unvec(qU(t).a{1},{G.a});\n v = spm_unvec(pU(t).v{1},{G.v});\n x = spm_unvec(pU(t).x{1},{G.x});\n z = spm_unvec(pU(t).z{1},{G.v});\n w = spm_unvec(pU(t).w{1},{G.x});\n for i = 1:nl\n try\n PU.v{i}(:,t) = spm_vec(v{i});\n PU.z{i}(:,t) = spm_vec(z{i});\n end\n try\n PU.x{i}(:,t) = spm_vec(x{i});\n PU.w{i}(:,t) = spm_vec(w{i});\n end\n try\n QU.a{i}(:,t) = spm_vec(a{i});\n end\n end\n \n % conditional modes\n %--------------------------------------------------------------\n v = spm_unvec(qU(t).v{1},{M(1 + 1:end).v});\n x = spm_unvec(qU(t).x{1},{M(1:end - 1).x});\n z = spm_unvec(qE{t}(1:(ny + nv)),{M.v});\n w = spm_unvec(qE{t}((1:nx) + (ny + nv)*n),{M.x});\n for i = 1:(nl - 1)\n if M(i).m, QU.v{i + 1}(:,t) = spm_vec(v{i}); end\n if M(i).l, QU.z{i}(:,t) = spm_vec(z{i}); end\n if M(i).n, QU.x{i}(:,t) = spm_vec(x{i}); end\n if M(i).n, QU.w{i}(:,t) = spm_vec(w{i}); end\n end\n QU.v{1}(:,t) = spm_vec(qU(t).y{1}) - spm_vec(z{1});\n QU.z{nl}(:,t) = spm_vec(z{nl});\n \n % and conditional covariances\n %--------------------------------------------------------------\n i = (1:nx);\n QU.S{t} = qC{t}(i,i);\n PU.S{t} = pC{t}(i,i);\n i = (1:nv) + nx*n;\n QU.C{t} = qC{t}(i,i);\n PU.C{t} = pC{t}(i,i);\n end\n \n % save conditional densities\n %------------------------------------------------------------------\n B.QU = QU;\n B.PU = PU;\n B.qp = qp;\n B.qh = qh;\n \n % decrease regularisation\n %------------------------------------------------------------------\n F(iE) = L;\n te = min(te + 1,8);\n \n else\n \n % otherwise, return to previous expansion point and break\n %------------------------------------------------------------------\n QU = B.QU;\n PU = B.PU;\n qp = B.qp;\n qh = B.qh;\n \n % increase regularisation\n %------------------------------------------------------------------\n F(iE) = F(end);\n te = min(te - 1,0);\n \n end\n \n % report and break if convergence\n %======================================================================\n if db\n figure(Fdem)\n spm_DEM_qU(QU)\n if np\n subplot(nl,4,4*nl)\n bar(full(Up*qp.e))\n xlabel({'parameters';'{minus prior}'})\n axis square, grid on\n end\n if length(F) > 2\n subplot(nl,4,4*nl - 1)\n plot(F - F(1))\n xlabel('updates')\n title('log-evidence')\n axis square, grid on\n end\n drawnow\n \n % report (EM-Steps)\n %------------------------------------------------------------------\n str{1} = sprintf('ADEM: %i (%i)',iE,iM);\n str{2} = sprintf('F:%.4e',full(L - F(1)));\n str{3} = sprintf('p:%.2e',full(dp'*dp));\n str{4} = sprintf('h:%.2e',full(mh'*mh));\n str{5} = sprintf('(%.2e sec)',full(toc));\n \n fprintf('%-16s%-16s%-14s%-14s%-16s\\n',str{:})\n end\n \n if (norm(dp,1) < exp(-8)) && (norm(mh,1) < exp(-8)), break, end\n \nend\n \n% assemble output arguments\n%==========================================================================\n\n% conditional moments of model-parameters (rotated into original space)\n%--------------------------------------------------------------------------\nqP.P = spm_unvec(Up*qp.e + spm_vec(M.pE),M.pE);\nqP.C = Up*qp.c*Up';\nqP.V = spm_unvec(diag(qP.C),M.pE);\n \n% conditional moments of hyper-parameters (log-transformed)\n%--------------------------------------------------------------------------\nqH.h = spm_unvec(qh.h,{{M.hE} {M.gE}});\nqH.g = qH.h{2};\nqH.h = qH.h{1};\nqH.C = qh.c;\nqH.V = spm_unvec(diag(qH.C),{{M.hE} {M.gE}});\nqH.W = qH.V{2};\nqH.V = qH.V{1};\n \n% Fill in DEM with response and its causes\n%--------------------------------------------------------------------------\nDEM.pP.P = {G.pE}; % parameters encoding process\n\nDEM.M = M; % generative model\nDEM.U = U; % causes\nDEM.Y = PU.v{1}; % response\n\nDEM.pU = PU; % prior moments of model-states\nDEM.qU = QU; % conditional moments of model-states\nDEM.qP = qP; % conditional moments of model-parameters\nDEM.qH = qH; % conditional moments of hyper-parameters\n \nDEM.F = F; % [-ve] Free energy\ntry\n DEM.J = J; % [-ve] Free energy (over samples)\nend\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/spm_ADEM.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7154240079185318, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.3077377401208135}} {"text": "function dat=readinr(fname)\n%\n% vol=readinr(fname)\n%\n% load a volume from an INR file\n%\n% author: Qianqian Fang (fangq nmr.mgh.harvard.edu)\n% date: 2009/05/03\n%\n% input:\n% fname: input file name\n%\n% output:\n% dat: output, data read from the inr file\n%\n% -- this function is part of iso2mesh toolbox (http://iso2mesh.sf.net)\n%\n\nfid=fopen(fname,'rb');\ns=fread(fid,256,'uchar');\n\ns=char(s)';\n\nif(regexp(s,'#INRIMAGE-4')~=1)\n error('INRIMAGE header was not found')\nend\n\nnx=regexp(s,'XDIM\\s*=\\s*([0-9]+)','tokens');\nif(length(nx)) \n nx=str2num(nx{1}{1});\nelse\n error('no XDIM found');\nend\n\nny=regexp(s,'YDIM\\s*=\\s*([0-9]+)','tokens');\nif(length(ny)) \n ny=str2num(ny{1}{1});\nelse\n error('no YDIM found');\nend\n\nnz=regexp(s,'ZDIM\\s*=\\s*([0-9]+)','tokens');\nif(length(nz)) \n nz=str2num(nz{1}{1});\nelse\n error('no ZDIM found');\nend\n\nnv=regexp(s,'VDIM\\s*=\\s*([0-9]+)','tokens');\nif(length(nv))\n nv=str2num(nv{1}{1});\nelse\n nv=1;\nend\n\ntype=regexp(s,'TYPE=([a-z ]+)','tokens');\nif(length(type))\n type=type{1}{1};\nelse\n error('no TYPE found');\nend\n\npixel=regexp(s,'PIXSIZE=([0-9]+)','tokens');\nif(length(pixel))\n pixel=str2num(pixel{1}{1});\nelse\n error('no PIXSIZE found');\nend\n\n%header=sprintf(['#INRIMAGE-4#{\\nXDIM=%d\\nYDIM=%d\\nZDIM=%d\\nVDIM=1\\nTYPE=%s\\n' ...\n% 'PIXSIZE=%d bits\\nCPU=decm\\nVX=1\\nVY=1\\nVZ=1\\n'],size(vol),btype,bitlen);\n\nif(strcmp(type,'unsigned fixed') & pixel==8)\n dtype='uint8';\nelseif(strcmp(type,'unsigned fixed') & pixel==16)\n dtype='uint16';\nelseif(strcmp(type,'float') & pixel==32)\n dtype='float';\nelseif(strcmp(type,'float') & pixel==64)\n dtype='double';\nelse\n error('volume format not supported');\nend\n\n\ndat=fread(fid,nx*ny*nz*nv,dtype);\nfclose(fid);\n\nif(nv==1)\n dat=reshape(dat,[nx,ny,nz]);\nelse\n dat=reshape(dat,[nx,ny,nz,nv]);\nend\n", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/iso2mesh/readinr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583269796369905, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.30741894736517117}} {"text": "function [RIR_cell] = ISM_RIR_bank_GPU(setupstruc,RIRFileName,varargin)\n%ISM_RIR_bank Bank of RIRs using Lehmann & Johansson's image-source method\n%\n% [RIR_CELL] = ISM_RIR_bank(SETUP_STRUC,RIR_FILE_NAME)\n% [RIR_CELL] = ISM_RIR_bank( ... ,'arg1',val1,'arg2',val2,...)\n%\n% This function generates a bank of room impulse responses (RIRs) for a\n% particular user-defined room setup, using Lehmann and Johansson's\n% implementation of the image-source method (see: \"Prediction of energy\n% decay in room impulse responses simulated with an image-source model\", J.\n% Acoust. Soc. Am., vol. 124(1), pp. 269-277, July 2008). The input\n% SETUP_STRUC is a structure of enviromental parameters containing the\n% following fields:\n%\n% Fs: sampling frequency (in Hz).\n% room: 1-by-3 vector of enclosure dimensions (in m), \n% [x_length y_length z_length].\n% mic_pos: N-by-3 matrix, [x1 y1 z1; x2 y2 z2; ...] positions of N\n% microphones (in m). \n% src_traj: M-by-3 matrix, [x1 y1 z1; x2 y2 z2; ...] positions of M \n% source trajectory points (in m).\n% T20 or T60: scalar value (in s), desired reverberation time.\n% c: (optional) sound velocity (in m/s).\n% abs_weights: (optional) 1-by-6 vector of absorption coefficients weights, \n% [w_x1 w_x2 w_y1 w_y2 w_z1 w_z2].\n%\n% If the field SETUP_STRUC.c is undefined, the function assumes a default\n% value of sound velocity of 343 m/s.\n%\n% The field 'abs_weight' corresponds to the relative weights of each of the\n% six absorption coefficients resulting from the desired reverberation time.\n% For instance, defining 'abs_weights' as [1 1 0.8 0.8 0.6 0.6] will result\n% in the absorption coefficients (alpha) for the walls in the y-dimension\n% being 20% smaller compared to the x-dimension walls, whereas the floor\n% and ceiling will end up with absorption coefficients 40% smaller (e.g.,\n% to simulate the effects of a concrete floor and ceiling). If this field\n% is omitted, the parameter 'abs_weight' will default to [1 1 1 1 1 1],\n% which leads to uniform absorption coefficients for all room boundaries.\n%\n% The structure SETUP_STRUC may contain one of the two fields 'T60' or\n% 'T20'. This function will automatically determine which reverberation\n% type is used and compute the desired room absorption coefficients\n% accordingly. T20 is defined as the time required for the impulse response\n% energy to decay from -5 to -25dB, whereas T60 corresponds to the time\n% required by the impulse response energy to decay by 60dB. Setting the \n% corresponding field value to 0 achieves anechoic impulse responses \n% (direct path only).\n%\n% In addition, a number of other (optional) parameters can be set using a \n% series of 'argument'--value pairs. The following parameters (arguments)\n% can be used:\n%\n% 'Delta_dB': scalar (in dB), parameter determining how much the resulting \n% impulse response is cropped: the impulse response is\n% computed until the time index where its overall energy\n% content has decreased by 'Delta_dB' decibels, after which\n% the computations stop. Not relevant if the reverberation\n% time is set to 0 (anechoic case). Defaults to 50.\n% 'SilentFlag': set to 1 to disable this function's on-screen messages. \n% Defaults to 0.\n%\n% This function returns a 2-dimensional cell array RIR_CELL containing the\n% RIRs for each source trajectory point and each microphone, organised as\n% follows: RIR_CELL{mic_index,traj_index}. The resulting filter length\n% may differ slightly in each computed RIR.\n%\n% This function also saves the computation results on file. The argument\n% RIR_FILE_NAME determines the name of the .mat file where the variable\n% RIR_CELL is to be saved. If a file already exists with the same name as\n% the input argument, the user will be prompted to determine whether the\n% file is to be overwritten or not. The given parameter RIR_FILE_NAME can\n% be a full access path to the desired file. If no access path is given,\n% the file is saved in the current working directory. \n\n% Release date: November 2009\n% Author: Eric A. Lehmann, Perth, Australia (www.eric-lehmann.com)\n%\n% Copyright (C) 2009 Eric A. Lehmann\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\nVarList = {'Delta_dB' 50; % maximum attenuation in RIR computation\n 'SilentFlag' 0; % set to 1 to disable on-screen messages\n 'useGPU' 0}; % whether to use GPU\neval(SetUserVars(VarList,varargin)); % set user-definable variables\n\nif isempty(RIRFileName)\n DoNotSave = 1;\nelse\n DoNotSave = 0;\n if length(RIRFileName)<=4 || ~strcmpi(RIRFileName(end-3:end),'.mat'),\n RIRFileName = [RIRFileName '.mat'];\n end\nend\nif exist(RIRFileName,'file')==2,\n foo = input(' [ISM_RIR_bank] The file name passed as input already exists. Overwrite? [yes/no]: ','s');\n if ~strcmpi(foo,'yes');\n fprintf(' [ISM_RIR_bank] Terminating execution now (no data was saved).\\n');\n return\n end\nend\n\nFs = setupstruc.Fs;\nroom = setupstruc.room;\nmicpos = setupstruc.mic_pos;\nstraj = setupstruc.src_traj;\n\nif isfield(setupstruc,'abs_weights'),\n weights = setupstruc.abs_weights;\nelse\n weights = ones(1,6);\nend\nif isfield(setupstruc,'c'),\n cc = setupstruc.c;\nelse\n cc = 343;\nend\nif isfield(setupstruc,'T60'),\n if isfield(setupstruc, 'reflect_weights')\n beta = setupstruc.reflect_weights;\n else\n alpha = ISM_AbsCoeff('t60',setupstruc.T60,room,weights,'LehmannJohansson','c',cc);\n end\n rttype = 'T60'; rtval = setupstruc.T60;\nelseif isfield(setupstruc,'T20'),\n alpha = ISM_AbsCoeff('t20',setupstruc.T20,room,weights,'LehmannJohansson','c',cc);\n rttype = 'T20'; rtval = setupstruc.T20;\nelse\n error('Missing T60 or T20 field.');\nend\nif isfield(setupstruc, 'reflect_weights')==0\n beta = sqrt(1-alpha);\nend\n\nnMics = size(micpos,1); % number of microphones\nnSPts = size(straj,1); % number of source trajectory points\n\n%-=:=- Compute RIR bank -=:=-\nRIR_cell = cell(nMics,nSPts); % pre-allocate cell array\nif ~SilentFlag, PrintLoopPCw(' [ISM_RIR_bank] Computing room impulse responses. '); end;\nfor mm=1:nMics,\n X_rcv = micpos(mm,:);\n for tt=1:nSPts, % compute ISM room impulse response for each source-receiver combinations\n if ~SilentFlag, PrintLoopPCw((mm-1)*nSPts+tt,nMics*nSPts); end;\n X_src = straj(tt,:);\n if strcmpi(rttype, 'T60') % modified by Xiong Xiao: if we use T60, simply set RIR length to T60 length\n RIR_cell{mm,tt} = ISM_RoomResp_GPU(Fs,beta,rttype,rtval,X_src,X_rcv,room,'SilentFlag',1,'c',cc,'Delta_dB',Delta_dB, 'MaxDelay', rtval, 'useGPU', useGPU);\n else\n RIR_cell{mm,tt} = ISM_RoomResp_GPU(Fs,beta,rttype,rtval,X_src,X_rcv,room,'SilentFlag',1,'c',cc,'Delta_dB',Delta_dB, 'useGPU', useGPU);\n end\n end\nend\n\n%-=:=- Save results into .mat file -=:=-\nif DoNotSave==0\n save(RIRFileName,'RIR_cell');\n if ~SilentFlag, fprintf(' [ISM_RIR_bank] RIR bank parameter ''RIR_cell'' saved in file ''%s''\\n',RIRFileName); end;\nend\n\n", "meta": {"author": "singaxiong", "repo": "SignalGraph", "sha": "e86d973556ae8796a05ee2adbd665f47c8525a21", "save_path": "github-repos/MATLAB/singaxiong-SignalGraph", "path": "github-repos/MATLAB/singaxiong-SignalGraph/SignalGraph-e86d973556ae8796a05ee2adbd665f47c8525a21/signal/array/imageRIR/ISM_RIR_bank_GPU.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.538983220687684, "lm_q1q2_score": 0.3071410173766185}} {"text": "function [y]=multifuncrs(X, funs, eps, varargin)\n% Cross approximation of a (vector-)function of several TT-tensors.\n% [Y]=MULTIFUNCRS(X,FUNS,EPS, VARARGIN)\n% Computes approximation to the functions FUNS(X{1},...,X{N}) with accuracy EPS\n% X should be a cell array of nx TT-tensors of equal sizes.\n% The function FUNS should receive a 2d array V of sizes I x N, where the\n% first dimension stays for the reduced set of spatial indices, and the\n% second is the enumerator of X.\n% The returned sizes should be I x D2, where D2 is the number of\n% components in FUNS. D2 should be either provided as the last (d+1)-th\n% TT-rank of the initial guess, or given explicitly as an option (see\n% below).\n% For example, a linear combination reads FUNS=@(x)(x*W), W is a N x D2\n% matrix.\n%\n% Options are provided in form\n% 'PropertyName1',PropertyValue1,'PropertyName2',PropertyValue2 and so\n% on. The parameters are set to default (in brackets in the following)\n% The list of option names and default values are:\n% o y0 - initial approximation [random rank-2 tensor]\n% o nswp - maximal number of DMRG sweeps [10]\n% o rmax - maximal TT rank [Inf]\n% o verb - verbosity level, 0-silent, 1-sweep info, 2-block info [1]\n% o kickrank - the rank-increasing parameter [5]\n% o d2 - the last rank of y, that is dim(FUNS) [1]\n% o qr - do (or not) qr before maxvol [false]\n%\n% The method is based on the alternating approximation, with \n% the one-block enrichment via KICKRANK random vectors or randomized AMR.\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\nnswp = 10;\nkickrank = 5;\ny = [];\nverb = 1;\n% kicktype = 'rand';\nkicktype = 'amr-two';\npcatype = 'svd';\n%pcatype = 'uchol';\nrmax = Inf;\nd2 = 1;\nwasrand = false;\ntrunctype = 'fro';\ndo_qr = false;\n% trunctype = 'cross';\n\nfor i=1:2:length(varargin)-1\n switch lower(varargin{i})\n case 'nswp'\n nswp=varargin{i+1};\n case 'y0'\n y=varargin{i+1};\n case 'kickrank'\n kickrank=varargin{i+1};\n case 'rmax'\n rmax=varargin{i+1}; \n case 'verb'\n verb=varargin{i+1};\n case 'kicktype'\n kicktype=varargin{i+1}; \n case 'pcatype'\n pcatype=varargin{i+1};\n case 'trunctype'\n trunctype=varargin{i+1}; \n case 'd2'\n d2=varargin{i+1}; \n case 'qr'\n do_qr = varargin{i+1};\n otherwise\n error('Unrecognized option: %s\\n',varargin{i});\n end\nend\n\nnx = numel(X);\nd = X{1}.d;\nn = X{1}.n;\nrx = zeros(d+1,nx);\ncrX = cell(d,nx);\nfor i=1:nx\n rx(:,i) = X{i}.r;\n crX(:,i) = core2cell(X{i});\nend;\n\nif (isempty(y))\n ry = d2*ones(d+1,1); ry(1)=1;\n y = tt_rand(n, d, ry);\n wasrand = true;\nend;\nry = y.r;\ncry = core2cell(y);\n\nRy = cell(d+1,1);\nRy{1} = 1; Ry{d+1}=1;\nRx = cell(d+1,nx);\nfor i=1:nx\n Rx{1,i}=1; Rx{d+1,i}=1;\nend;\n\nblock_order = [+(d), -(d)];\n\n% Orth\nfor i=1:d-1\n cr = cry{i}; % r1,n,d2,r2\n cr = reshape(cr, ry(i)*n(i), ry(i+1));\n [cr, rv]=qr(cr, 0); \n cr2 = cry{i+1};\n cr2 = reshape(cr2, ry(i+1), n(i+1)*ry(i+2));\n cr2 = rv*cr2;\n ry(i+1) = size(cr, 2);\n cr = reshape(cr, ry(i), n(i), ry(i+1));\n cry{i+1} = reshape(cr2, ry(i+1), n(i+1), ry(i+2));\n cry{i} = cr;\n\n % Interface matrix for Y \n Ry{i+1} = Ry{i}*reshape(cr, ry(i), n(i)*ry(i+1));\n Ry{i+1} = reshape(Ry{i+1}, ry(i)*n(i), ry(i+1));\n if (wasrand)\n curind = [];\n while numel(curind)0)\n \n oldy = reshape(cry{i}, d2*ry(i)*n(i)*ry(i+1), 1);\n \n if (~last_sweep)\n % Compute the X superblocks\n curbl = zeros(ry(i)*n(i)*ry(i+1), nx);\n for j=1:nx\n cr = reshape(crX{i,j}, rx(i,j), n(i)*rx(i+1,j));\n cr = Rx{i,j}*cr;\n cr = reshape(cr, ry(i)*n(i), rx(i+1,j));\n cr = cr*Rx{i+1,j};\n curbl(:,j) = cr(:);\n end;\n % Call the function\n newy = funs(curbl); % sizes: rnr x nx -> rnr x d2\n % Multiply with inverted Ry\n newy = reshape(newy, ry(i), n(i)*ry(i+1)*d2);\n newy = (Ry{i}) \\ newy;\n newy = reshape(newy, ry(i)*n(i)*ry(i+1), d2);\n newy = reshape(newy.', d2*ry(i)*n(i), ry(i+1));\n newy = newy / (Ry{i+1});\n newy = reshape(newy, d2*ry(i)*n(i)*ry(i+1), 1);\n else\n newy = oldy;\n end;\n\n dy(i) = norm(newy(:)-oldy)/norm(newy(:));\n max_dy = max(max_dy, dy(i));\n\n % Truncation\n if (dir>0) % left-to-right\n newy = reshape(newy, d2, ry(i)*n(i)*ry(i+1));\n newy = reshape(newy.', ry(i)*n(i), ry(i+1)*d2);\n else\n newy = reshape(newy, d2*ry(i), n(i)*ry(i+1));\n end;\n\n if (kickrank>=0)\n [u,s,v]=svd(newy, 'econ');\n s = diag(s);\n if (strcmp(trunctype, 'fro'))||(last_sweep)\n r = my_chop2(s, eps/sqrt(d)*norm(s));\n else \n % Truncate taking into account the (r+1) overhead in the cross\n cums = (s.*(2:numel(s)+1)').^2;\n cums = cumsum(cums(end:-1:1));\n cums = cums(end:-1:1)./cums(1);\n r = find(cums<(eps^2/d), 1);\n if (isempty(r))\n r = numel(s);\n end;\n end;\n r = min(r, rmax);\n r = min(r, numel(s));\n else\n if (dir>0)\n [u,v]=qr(newy, 0);\n v=v';\n r = size(u,2);\n s = ones(r,1);\n else\n [v,u]=qr(newy.', 0);\n v=conj(v);\n u=u.';\n r = size(u,2);\n s = ones(r,1);\n end;\n end;\n\n if (verb>1)\n \tfprintf('=multifuncrs= block %d{%d}, dy: %3.3e, r: %d\\n', i, dir, dy(i), r);\n end; \n \n % Kicks and interfaces\n if (dir>0)&&(i0)\n if (strcmp(kicktype, 'amr-two'))\n % AMR(two)-like kick. See also the M.Sc.Thesis by D. Zheltkov.\n % The left indices are nested, but the right are chosen\n % randomly. In Zheltkov's work, from all possible n^(d-k)\n % values. However, in the functional-cross it would result\n % in a d^2 complexity. Here, I use only the neighbouring\n % core for randomization. Additionally, the actual kick is\n % performed via the Z=PCA(supercore), since otherwise the\n % rank grows too high.\n \n % Compute the X superblocks\n ind2 = unique(ceil(rand(ry(i+1), 1)*(ry(i+2)*n(i+1))));\n rkick = numel(ind2);\n curbl = zeros(ry(i)*n(i)*rkick, nx);\n for j=1:nx\n cr1 = reshape(crX{i,j}, rx(i,j), n(i)*rx(i+1,j));\n cr1 = Rx{i,j}*cr1;\n cr1 = reshape(cr1, ry(i)*n(i), rx(i+1,j));\n cr2 = reshape(crX{i+1,j}, rx(i+1,j)*n(i+1), rx(i+2,j)); \n cr2 = cr2*Rx{i+2,j}; % now its size rx\n cr2 = reshape(cr2, rx(i+1,j), n(i+1)*ry(i+2));\n cr2 = cr2(:, ind2);\n curbl(:,j) = reshape(cr1*cr2, ry(i)*n(i)*rkick, 1);\n end;\n % Call the function\n uk = funs(curbl); % rnr, d2\n uk = reshape(uk, ry(i), n(i)*rkick*d2);\n uk = Ry{i} \\ uk;\n uk = reshape(uk, ry(i)*n(i), rkick*d2);\n if (strcmp(pcatype, 'svd'))\n [uk,sk,vk]=svd(uk, 'econ');\n uk = uk(:,1:min(kickrank, size(uk,2)));\n else\n uk = uchol(uk.', kickrank+1);\n uk = uk(:,end:-1:max(end-kickrank+1,1));\n end;\n else\n uk = rand(ry(i)*n(i), kickrank);\n end;\n [u,rv]=qr([u,uk], 0);\n radd = size(uk,2);\n end;\n v = [v, zeros(ry(i+1)*d2, radd)];\n v = rv*(v');\n r = size(u,2);\n\n cr2 = cry{i+1};\n cr2 = reshape(cr2, ry(i+1), n(i+1)*ry(i+2));\n v = reshape(v, r*ry(i+1), d2);\n v = reshape(v.', d2*r, ry(i+1));\n v = v*cr2; % size r+radd, n2, r3\n\n ry(i+1) = r;\n\n u = reshape(u, ry(i), n(i), r);\n v = reshape(v, d2, r, n(i+1), ry(i+2));\n\n % Stuff back\n cry{i} = u;\n cry{i+1} = v;\n \n % Recompute left interface matrices\n % Interface matrix for Y\n Ry{i+1} = Ry{i}*reshape(u, ry(i), n(i)*ry(i+1));\n Ry{i+1} = reshape(Ry{i+1}, ry(i)*n(i), ry(i+1));\n curind = maxvol2(Ry{i+1},'qr',do_qr);\n Ry{i+1} = Ry{i+1}(curind, :);\n % Interface matrices for X\n for j=1:nx\n Rx{i+1,j} = reshape(crX{i,j}, rx(i,j), n(i)*rx(i+1,j));\n Rx{i+1,j} = Rx{i,j}*Rx{i+1,j};\n Rx{i+1,j} = reshape(Rx{i+1,j}, ry(i)*n(i), rx(i+1,j));\n Rx{i+1,j} = Rx{i+1,j}(curind, :);\n end;\n elseif (dir<0)&&(i>1) % right-to-left\n u = u(:,1:r)*diag(s(1:r));\n v = conj(v(:,1:r));\n % kick\n radd = 0; rv = 1;\n if (~last_sweep)&&(kickrank>0)\n if (strcmp(kicktype, 'amr-two'))\n % Compute the X superblocks\n ind2 = unique(ceil(rand(ry(i), 1)*(ry(i-1)*n(i-1))));\n rkick = numel(ind2);\n curbl = zeros(rkick*n(i)*ry(i+1), nx);\n for j=1:nx\n cr1 = reshape(crX{i,j}, rx(i,j)*n(i), rx(i+1,j));\n cr1 = cr1*Rx{i+1,j};\n cr1 = reshape(cr1, rx(i,j), n(i)*ry(i+1));\n cr2 = reshape(crX{i-1,j}, rx(i-1,j), n(i-1)*rx(i,j)); \n cr2 = Rx{i-1,j}*cr2; % now its size rx\n cr2 = reshape(cr2, ry(i-1)*n(i-1), rx(i,j));\n cr2 = cr2(ind2, :);\n curbl(:,j) = reshape(cr2*cr1, rkick*n(i)*ry(i+1), 1);\n end;\n % Call the function\n uk = funs(curbl); % rnr x d2\n uk = reshape(uk, rkick*n(i)*ry(i+1), d2);\n uk = reshape(uk.', d2*rkick*n(i), ry(i+1));\n uk = uk / Ry{i+1};\n uk = reshape(uk, d2*rkick, n(i)*ry(i+1));\n if (strcmp(pcatype, 'svd'))\n [vk,sk,uk]=svd(uk, 'econ');\n uk = uk(:,1:min(kickrank, size(uk,2)));\n else\n uk = uchol(uk, kickrank+1);\n uk = uk(:,end:-1:max(end-kickrank+1,1));\n end; \n else\n uk = rand(n(i)*ry(i+1), kickrank);\n end; \n% uk = rand(n(i)*ry(i+1), kickrank);\n [v,rv]=qr([v,uk], 0);\n radd = size(uk,2);\n end;\n u = [u, zeros(d2*ry(i), radd)];\n u = u*(rv.');\n r = size(v,2);\n \n cr2 = cry{i-1};\n cr2 = reshape(cr2, ry(i-1)*n(i-1), ry(i));\n u = reshape(u, d2, ry(i)*r);\n u = reshape(u.', ry(i), r*d2);\n u = cr2*u;\n \n u = reshape(u, ry(i-1)*n(i-1)*r, d2);\n u = reshape(u.', d2, ry(i-1), n(i-1), r);\n v = reshape(v.', r, n(i), ry(i+1));\n \n % Stuff back\n ry(i) = r;\n cry{i-1} = u;\n cry{i} = v;\n \n % Recompute left interface matrices\n % Interface matrix for Y\n Ry{i} = reshape(v, ry(i)*n(i), ry(i+1))*Ry{i+1};\n Ry{i} = reshape(Ry{i}, ry(i), n(i)*ry(i+1));\n curind = maxvol2(Ry{i}.','qr',do_qr);\n Ry{i} = Ry{i}(:, curind);\n % Interface matrices for X\n for j=1:nx\n Rx{i,j} = reshape(crX{i,j}, rx(i,j)*n(i), rx(i+1,j));\n Rx{i,j} = Rx{i,j}*Rx{i+1,j};\n Rx{i,j} = reshape(Rx{i,j}, rx(i,j), n(i)*ry(i+1));\n Rx{i,j} = Rx{i,j}(:, curind);\n end;\n elseif ((dir>0)&&(i==d))\n % Just stuff back the last core\n newy = u(:,1:r)*diag(s(1:r))*(v(:,1:r)');\n newy = reshape(newy, ry(i)*n(i)*ry(i+1), d2);\n cry{i} = reshape(newy.', d2, ry(i), n(i), ry(i+1));\n elseif ((dir<0)&&(i==1))\n % Just stuff back the last core\n newy = u(:,1:r)*diag(s(1:r))*(v(:,1:r)');\n newy = reshape(newy, d2, ry(i), n(i), ry(i+1));\n cry{i} = newy; \n end;\n \n \n i = i+dir;\n % Reversing, residue check, etc\n cur_order(order_index) = cur_order(order_index) - dir;\n % New direction\n if (cur_order(order_index)==0)\n order_index = order_index+1;\n\n if (verb>0)\n fprintf('=multifuncrs= sweep %d{%d}, max_dy: %3.3e, erank: %g\\n', swp, order_index-1, max_dy, sqrt(ry(1:d)'*(n.*ry(2:d+1))/sum(n)));\n end;\n\n if (last_sweep)\n break;\n end;\n\n if (max_dynumel(cur_order)) % New global sweep\n cur_order = block_order;\n order_index = 1;\n %residue\n if (last_sweep)\n cur_order = d-1;\n end;\n\n max_dy = 0;\n swp = swp+1;\n end;\n\n dir = sign(cur_order(order_index));\n i = i+dir;\n end;\nend\n\ncry{d} = permute(cry{d}, [2,3,1]); % d2 is r(d+1)\ny = cell2core(y, cry);\n\nend\n", "meta": {"author": "oseledets", "repo": "TT-Toolbox", "sha": "1b87616b1e84de89699697fe196eba814aabe954", "save_path": "github-repos/MATLAB/oseledets-TT-Toolbox", "path": "github-repos/MATLAB/oseledets-TT-Toolbox/TT-Toolbox-1b87616b1e84de89699697fe196eba814aabe954/cross/multifuncrs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.3069744143648549}} {"text": "function g = linKernGradient(kern, x, varargin)\n\n% LINKERNGRADIENT Gradient of LIN kernel's parameters.\n% FORMAT\n% DESC computes the gradient of functions with respect to the\n% linear\n% kernel's parameters. As well as the kernel structure and the\n% input positions, the user provides a matrix PARTIAL which gives\n% the partial derivatives of the function with respect to the\n% relevant elements of the kernel matrix. \n% ARG kern : the kernel structure for which the gradients are being\n% computed.\n% ARG x : the input locations for which the gradients are being\n% computed. \n% ARG partial : matrix of partial derivatives of the function of\n% interest with respect to the kernel matrix. The argument takes\n% the form of a square matrix of dimension numData, where numData is\n% the number of rows in X.\n% RETURN g : gradients of the function of interest with respect to\n% the kernel parameters. The ordering of the vector should match\n% that provided by the function kernExtractParam.\n%\n% FORMAT\n% DESC computes the derivatives as above, but input locations are\n% now provided in two matrices associated with rows and columns of\n% the kernel matrix. \n% ARG kern : the kernel structure for which the gradients are being\n% computed.\n% ARG x1 : the input locations associated with the rows of the\n% kernel matrix.\n% ARG x2 : the input locations associated with the columns of the\n% kernel matrix.\n% ARG partial : matrix of partial derivatives of the function of\n% interest with respect to the kernel matrix. The matrix should\n% have the same number of rows as X1 and the same number of columns\n% as X2 has rows.\n% RETURN g : gradients of the function of interest with respect to\n% the kernel parameters.\n%\n% SEEALSO linKernParamInit, kernGradient, linKernDiagGradient, kernGradX\n%\n% COPYRIGHT : Neil D. Lawrence, 2004, 2005, 2006, 2009\n\n% KERN\n\n\nif nargin < 4\n [k, sk] = linKernCompute(kern, x);\nelse\n [k, sk] = linKernCompute(kern, x, varargin{1});\nend\ng(1) = sum(sum(varargin{end}.*sk));\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/kern/linKernGradient.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.3067709510666036}} {"text": "function [p,priors]=create_parameters(start_from_mode)\np=struct();\n%--- Targeted steady state values\np.alpha = 0.30; %(1) the average labor income share is 70% (page 15 of paper)\np.r = 1.01; %(2) the average real prime loan rate is 4% per annum (page 15 of paper)\np.ky = 4.6194; %(3) the capital-output ratio is on average 1.15 at the annual frequency (page 15 of paper)\np.ik = 0.2093/4; % (4) the investment-capital ratio is on average 0.209 at the annual frequency\np.qlLeOY = 2.60; %(5) the average land-output ratio is 0.65 at the annual frequency\np.theta_bar = 0.75; %(6) the average nonfarm and nonfiancial businesses' loan-asset ratio is 0.75 at the annual frequency (page 15 of paper)\np.qlLhOY = 5.8011; %(7) the average housing output ratio is 1.45 at the annual frequency\np.n = 1/4; %(8) average market hours is 25% of time endowment\np.lbar = 1; %arbitrary\n\npriors=struct();\npriors.gamma_h ={ 0.7 , 0.0256, 0.7761 , 'beta_pdf(0.9)' , .00000001 , .99999999999};\npriors.gamma_e ={ 0.7 , 0.0256, 0.7761 , 'beta_pdf(0.9)' , .00000001 , .99999999999};\npriors.omega ={ 3.0 , 0.1020, 5.994 , 'gamma_pdf(0.9)' , .00001 , 10 };\npriors.g_trans ={ 0.375, 0.1 , 1.5 , 'gamma_pdf(0.9)' , .00001 , 10 };\npriors.lambda_qbar_trans={ 1.25 , 0.1 , 1.5 , 'gamma_pdf(0.9)' , .00001 , 10 };\npriors.rho_a ={ 0.9 , 0.0256, 0.7761 , 'beta_pdf(0.9)' , .00000001 , .99999999999};\npriors.rho_z ={ 0.9 , 0.0256, 0.7761 , 'beta_pdf(0.9)' , .00000001 , .99999999999};\npriors.rho_v ={ 0.9 , 0.0256, 0.7761 , 'beta_pdf(0.9)' , .00000001 , .99999999999};\npriors.rho_q ={ 0.9 , 0.0256, 0.7761 , 'beta_pdf(0.9)' , .00000001 , .99999999999};\npriors.rho_mu ={ 0.9 , 0.0256, 0.7761 , 'beta_pdf(0.9)' , .00000001 , .99999999999};\npriors.rho_phi ={ 0.9 , 0.0256, 0.7761 , 'beta_pdf(0.9)' , .00000001 , .99999999999};\npriors.rho_psi ={ 0.9 , 0.0256, 0.7761 , 'beta_pdf(0.9)' , .00000001 , .99999999999};\npriors.rho_xitheta ={ 0.9 , 0.0256, 0.7761 , 'beta_pdf(0.9)' , .00000001 , .99999999999};\npriors.sig_Eps_a ={ 0.01 , 0.0001, 2 , 'inv_gamma_pdf(0.9)', 0.000000000001, 100 };\npriors.sig_Eps_z ={ 0.01 , 0.0001, 2 , 'inv_gamma_pdf(0.9)', 0.000000000001, 100 };\npriors.sig_Eps_v ={ 0.01 , 0.0001, 2 , 'inv_gamma_pdf(0.9)', 0.000000000001, 100 };\npriors.sig_Eps_q ={ 0.01 , 0.0001, 2 , 'inv_gamma_pdf(0.9)', 0.000000000001, 100 };\npriors.sig_Eps_mu ={ 0.01 , 0.0001, 2 , 'inv_gamma_pdf(0.9)', 0.000000000001, 100 };\npriors.sig_Eps_phi ={ 0.01 , 0.0001, 2 , 'inv_gamma_pdf(0.9)', 0.000000000001, 100 };\npriors.sig_Eps_psi ={ 0.01 , 0.0001, 2 , 'inv_gamma_pdf(0.9)', 0.000000000001, 100 };\npriors.sig_Eps_xitheta ={ 0.01 , 0.0001, 2 , 'inv_gamma_pdf(0.9)', 0.000000000001, 100 };\n\nif start_from_mode\n priors.gamma_e{1}= 0.658435028;\n priors.gamma_h{1}= 0.497555761;\n priors.omega{1}= 0.175347074;\n priors.g_trans{1}= 0.422109209;\n priors.lambda_qbar_trans{1}= 1.21261837;\n priors.rho_a{1}= 0.905471687;\n priors.rho_v{1}= 0.00947706131;\t%rho_{nu_z}\n priors.rho_mu{1}= 0.294889827;\t %rho_{nu_q}\n priors.rho_psi{1}= 0.982918278;\n priors.rho_q{1}= 0.561965864;\n priors.rho_xitheta{1}= 0.980427788;\n priors.rho_phi{1}= 0.999758433;\n priors.rho_z{1}= 0.426298781;\t %rho_z\n priors.sig_Eps_z{1}= 0.00418908791;\n priors.sig_Eps_v{1}= 0.00365910563;\n priors.sig_Eps_q{1}= 0.00415238812;\n priors.sig_Eps_mu{1}= 0.00288990925;\n priors.sig_Eps_a{1}= 0.101281626;\n priors.sig_Eps_phi{1}= 0.0462334747;\n priors.sig_Eps_psi{1}= 0.00731583619;\n priors.sig_Eps_xitheta{1}= 0.0111777605;\nend\n\n% add the initial conditions of the priors to the parameters\n%------------------------------------------------------------\nfields=fieldnames(priors);\nfor ip=1:numel(fields)\n name=fields{ip};\n p.(name)=priors.(name){1};\nend\n\nend", "meta": {"author": "jmaih", "repo": "RISE_toolbox", "sha": "1b2edfa27830c6d522f9d7d2335d33c3e4d84285", "save_path": "github-repos/MATLAB/jmaih-RISE_toolbox", "path": "github-repos/MATLAB/jmaih-RISE_toolbox/RISE_toolbox-1b2edfa27830c6d522f9d7d2335d33c3e4d84285/examples/VariousModels/TaoZha/LWZ_Econometrica2013/create_parameters.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.4493926344647597, "lm_q1q2_score": 0.3067436087240036}} {"text": "classdef form_acc < mp.form_ac\n%MP.FORM_ACC MATPOWER Formulation class for AC cartesian voltage formulations\n% Each concrete Network Model Element class must inherit, at least\n% indirectly, from both MP.NM_ELEMENT and MP.FORM.\n%\n% Subclass of MP.FORM_AC.\n% MP.FORM provides properties and methods related to the specific\n% formulation (e.g. DC version, AC polar power version, etc.)\n%\n% Properties\n% (model parameters inherited from MP.FORM_AC)\n%\n% Methods\n% form_name() - returns string w/name of formulation ('AC-cartesian formulation')\n% form_tag() - returns string w/short label for formulation ('acc')\n\n% MATPOWER\n% Copyright (c) 2019-2021, Power Systems Engineering Research Center (PSERC)\n% by Ray Zimmerman, PSERC Cornell\n%\n% This file is part of MATPOWER.\n% Covered by the 3-clause BSD License (see LICENSE file for details).\n% See https://matpower.org for more info.\n\n% properties\n% end\n\n methods\n function name = form_name(obj)\n name = 'AC-cartesian';\n end\n\n function tag = form_tag(obj)\n tag = 'acc';\n end\n\n function vtypes = model_vvars(obj)\n vtypes = {'vr', 'vi'};\n end\n\n function [Iu, Iw] = port_inj_current_jac(obj, ...\n n, v_, Y, M, invdiagvic, diagSlincJ)\n % [Iu, Iw] = obj.port_inj_current_jac(...)\n\n %% intermediate terms\n E = invdiagvic * (conj(M) - invdiagvic * diagSlincJ);\n\n% %% linear current term\n% Iu = Y;\n% Iw = 1j * Y;\n% \n% %% + current from linear power term\n% Iu = Iu + E;\n% Iw = Iw - 1j * E;\n\n Iu = Y + E;\n Iw = 1j * (Y - E);\n end\n\n function [Iuu, Iuw, Iww] = port_inj_current_hess_v(obj, x_, lam, v_, z_, diaginvic, Y, M, diagSlincJ, dlamJ)\n % [Iuu, Iuw, Iww] = obj.port_inj_current_hess_v(x_, lam)\n % [Iuu, Iuw, Iww] = obj.port_inj_current_hess_v(x_, lam, sysx)\n % [Iuu, Iuw, Iww] = obj.port_inj_current_hess_v(x_, lam, sysx, idx)\n % [...] = obj.port_inj_current_hess_vz(x_, lam, v_, z_, diaginvic, Y, M, diagSlincJ, dlamJ)\n\n if nargin < 10\n sysx = v_;\n if nargin < 5\n idx = []\n else\n idx = z_;\n end\n [Y, M, N, s] = obj.get_params(idx, {'Y', 'M', 'N', 's'});\n [v_, z_, vi_] = obj.x2vz(x_, sysx, idx);\n\n %% compute linear power injections\n if isempty(z_)\n Slin = M*v_ + s;\n else\n Slin = M*v_ + N*z_ + s;\n end\n\n n = length(v_); %% number of all port voltages\n ni = length(vi_); %% number of selected port voltages\n diaginvic = sparse(1:ni, 1:ni, 1 ./ conj(vi_), ni, ni);\n if isempty(idx) %% all ports\n diagSlincJ = sparse(1:n, 1:n, conj(Slin), n, n);\n dlamJ = sparse(1:n, 1:n, lam, n, n);\n else %% selected ports\n diagSlincJ = sparse(1:ni, idx, conj(Slin), ni, n);\n dlamJ = sparse(1:ni, idx, lam, ni, n);\n end\n else\n n = length(v_); %% number of all port voltages\n ni = length(lam);\n end\n\n %% intermediate terms\n % A = diaginvic * conj(M);\n % B = diaginvic * conj(N);\n % C = diaginvic * diaginvic * diagSlincJ;\n D = (diaginvic * dlamJ).';\n E = diaginvic * (conj(M) - diaginvic * diagSlincJ);\n % E = A - C;\n F = D * E;\n G = -(F.' + F);\n % H = -D * B;\n\n %% linear current term\n %% second derivatives all zero\n\n %% current from linear power term\n Iuu = G;\n Iuw = -1j * G;\n Iww = -G;\n end\n\n function [Iuzr, Iuzi, Iwzr, Iwzi] = port_inj_current_hess_vz(obj, x_, lam, v_, z_, diaginvic, N, dlamJ)\n % [Iuzr, Iuzi, Iwzr, Iwzi] = obj.port_inj_current_hess_vz(x_, lam)\n % [...] = obj.port_inj_current_hess_vz(x_, lam, sysx)\n % [...] = obj.port_inj_current_hess_vz(x_, lam, sysx, idx)\n % [...] = obj.port_inj_current_hess_vz(x_, lam, v_, z_, diaginvic, N, dlamJ)\n\n if nargin < 8\n sysx = v_;\n if nargin < 5\n idx = []\n else\n idx = z_;\n end\n N = obj.get_params(idx, 'N');\n [v_, z_, vi_] = obj.x2vz(x_, sysx, idx);\n\n n = length(v_); %% number of all port voltages\n ni = length(vi_); %% number of selected port voltages\n diaginvic = sparse(1:ni, 1:ni, 1 ./ conj(vi_), ni, ni);\n if isempty(idx) %% all ports\n dlamJ = sparse(1:n, 1:n, lam, n, n);\n else %% selected ports\n dlamJ = sparse(1:ni, idx, lam, ni, n);\n end\n else\n n = length(v_); %% number of all port voltages\n ni = length(lam);\n end\n\n %% intermediate terms\n % A = diaginvic * conj(M);\n B = diaginvic * conj(N);\n % C = diaginvic * diaginvic * diagSlincJ;\n D = (diaginvic * dlamJ).';\n % E = diaginvic * (conj(M) - diaginvic * diagSlincJ);\n % E = A - C;\n % F = D * E;\n % G = -(F.' + F);\n H = -D * B;\n\n %% current from linear power term\n Iuzr = H;\n Iuzi = -1j * H;\n Iwzr = Iuzi;\n Iwzi = -H;\n end\n\n function [Su, Sw] = port_inj_power_jac(obj, ...\n n, v_, Y, M, diagv, diagvi, diagIlincJ)\n % [Su, Sw] = obj.port_inj_power_jac(...)\n\n %% intermediate terms\n% A = diagIlincJ;\n B = diagvi * conj(Y);\n\n% %% linear power term\n% Su = M;\n% Sw = 1j * M;\n% \n% %% + power from linear current term\n% Su = Su + A + B;\n% Sw = Sw + 1j * (A - B);\n\n A = M + diagIlincJ;\n Su = A + B;\n Sw = 1j * (A - B);\n end\n\n function [Suu, Suw, Sww] = port_inj_power_hess_v(obj, x_, lam, v_, z_, diagvi, Y, M, diagIlincJ, dlamJ)\n % [Suu, Suw, Sww] = obj.port_inj_power_hess_v(x_, lam)\n % [Suu, Suw, Sww] = obj.port_inj_power_hess_v(x_, lam, sysx)\n % [Suu, Suw, Sww] = obj.port_inj_power_hess_v(x_, lam, sysx, idx)\n % [...] = obj.port_inj_power_hess_v(x_, lam, v_, z_, diagvi, Y, M, diagIlincJ, dlamJ)\n\n if nargin < 10\n sysx = v_;\n if nargin < 5\n idx = []\n else\n idx = z_;\n end\n [Y, L, M, i] = obj.get_params(idx, {'Y', 'L', 'M', 'i'});\n [v_, z_, vi_] = obj.x2vz(x_, sysx, idx);\n\n %% compute linear current injections\n if isempty(z_)\n Ilin = Y*v_ + i;\n else\n Ilin = Y*v_ + L*z_ + i;\n end\n\n n = length(v_); %% number of all port voltages\n ni = length(vi_); %% number of selected port voltages\n diagvi = sparse(1:ni, 1:ni, vi_, ni, ni);\n if isempty(idx) %% all ports\n diagIlincJ = sparse(1:n, 1:n, conj(Ilin), n, n);\n dlamJ = sparse(1:n, 1:n, lam, n, n);\n else %% selected ports\n diagIlincJ = sparse(1:ni, idx, conj(Ilin), ni, n);\n dlamJ = sparse(1:ni, idx, lam, ni, n);\n end\n else\n n = length(v_); %% number of all port voltages\n ni = length(lam);\n end\n\n %% intermediate terms\n % D = dlamJ.';\n E = dlamJ.' * conj(Y); %% D * conj(Y);\n % F = E + E.';\n % G = 1j * (E - E.');\n\n %% linear power term\n %% second derivatives all zero\n\n %% power from linear current term\n Suu = E + E.'; %% F\n Suw = 1j * (E.' - E); %% G.'\n Sww = Suu;\n end\n\n function [Suzr, Suzi, Swzr, Swzi] = port_inj_power_hess_vz(obj, x_, lam, v_, z_, diagvi, L, dlamJ)\n % [Suzr, Suzi, Swzr, Swzi] = obj.port_inj_power_hess_vz(x_, lam)\n % [...] = obj.port_inj_power_hess_vz(x_, lam, sysx)\n % [...] = obj.port_inj_power_hess_vz(x_, lam, sysx, idx)\n % [...] = obj.port_inj_power_hess_vz(x_, lam, v_, z_, diagvi, L, dlamJ)\n\n if nargin < 8\n sysx = v_;\n if nargin < 5\n idx = []\n else\n idx = z_;\n end\n L = obj.get_params(idx, 'L');\n [v_, z_, vi_] = obj.x2vz(x_, sysx, idx);\n\n n = length(v_); %% number of all port voltages\n ni = length(vi_); %% number of selected port voltages\n diagvi = sparse(1:ni, 1:ni, vi_, ni, ni);\n if isempty(idx) %% all ports\n dlamJ = sparse(1:n, 1:n, lam, n, n);\n else %% selected ports\n dlamJ = sparse(1:ni, idx, lam, ni, n);\n end\n else\n n = length(v_); %% number of all port voltages\n ni = length(lam);\n end\n\n %% intermediate terms\n D = dlamJ.';\n H = D * conj(L);\n\n %% power from linear current term\n Suzr = H;\n Suzi = -1j * H;\n Swzr = 1j * H;\n Swzi = H;\n end\n\n function [va, vm] = aux_data_va_vm(obj, ad)\n v_ = ad.vr + 1j * ad.vi;\n va = angle(v_);\n vm = abs(v_);\n end\n\n function [g, dg] = va_fcn(obj, xx, idx, lim)\n %% lim can be a vector value for equality constraint or\n %% upper bound on va, or a cell array with {vamin, vamax}\n %% for double bounds\n\n %% unpack data\n [vr, vi] = deal(xx{:});\n\n %% compute voltage angle mismatch\n if isempty(idx)\n va = angle(vr + 1j * vi);\n else\n va = angle(vr(idx) + 1j * vi(idx));\n end\n if iscell(lim)\n g = [ lim{1} - va;\n va - lim{2} ];\n else\n g = va - lim;\n end\n\n if nargout > 1\n %% compute partials of voltage angle w.r.t vr and vi\n nn = length(vr);\n if isempty(idx)\n idx = 1:nn;\n end\n n = length(idx);\n vm2 = vr(idx).^2 + vi(idx).^2;\n dva_dvr = sparse(1:n, idx, -vi(idx) ./ vm2, n, nn);\n dva_dvi = sparse(1:n, idx, vr(idx) ./ vm2, n, nn);\n if iscell(lim)\n dg = [ -dva_dvr -dva_dvi; %% va w.r.t vr, vi\n dva_dvr dva_dvi ]; %% va w.r.t vr, vi\n else\n dg = [dva_dvr dva_dvi]; %% va w.r.t vr, vi\n end\n end\n end\n\n function d2G = va_hess(obj, xx, lam, idx)\n %% unpack data\n [vr, vi] = deal(xx{:});\n nn = length(vr);\n\n %% evaluate Hessian of voltage angle function\n if isempty(idx)\n vvr = vr;\n vvi = vi;\n idx = 1:nn;\n else\n vvr = vr(idx);\n vvi = vi(idx);\n end\n vvr2 = vvr.^2;\n vvi2 = vvi.^2;\n vvm4 = (vvr2 + vvi2).^2;\n n = length(idx);\n if length(lam) == n %% upper bound or equality\n lamvm4 = lam ./ vvm4;\n else %% doubly bounded (use lam_ub-lam_lb)\n lamvm4 = (lam(n+1:2*n) - lam(1:n)) ./ vvm4;\n end\n d2vref_rr = sparse(idx, idx, 2 * lamvm4 .* vvr .* vvi, nn, nn);\n d2vref_ri = sparse(idx, idx, lamvm4 .* (vvi2 - vvr2), nn, nn);\n\n %% construct Hessian\n d2G = [ d2vref_rr d2vref_ri;\n d2vref_ri -d2vref_rr ];\n end\n\n function [g, dg] = vm2_fcn(obj, xx, idx, lim)\n %% lim can be a scalar value for equality constraint or\n %% upper bound on vm^2, or a cell array with {vm2min, vm2max}\n %% for double bounds\n\n %% unpack data\n [vr, vi] = deal(xx{:});\n\n %% compute voltage magnitude^2 mismatch\n if isempty(idx)\n vm2 = vr.^2 + vi.^2;\n else\n vm2 = vr(idx).^2 + vi(idx).^2;\n end\n if iscell(lim)\n g = [ lim{1} - vm2;\n vm2 - lim{2} ];\n else\n g = vm2 - lim;\n end\n\n if nargout > 1\n %% compute partials of voltage magnitude^2 w.r.t vr and vi\n nn = length(vr);\n if isempty(idx)\n idx = 1:nn;\n end\n n = length(idx);\n dvm_dvr = sparse(1:n, idx, 2 * vr(idx), n, nn);\n dvm_dvi = sparse(1:n, idx, 2 * vi(idx), n, nn);\n if iscell(lim)\n dg = [ -dvm_dvr -dvm_dvi;\n dvm_dvr dvm_dvi ]; %% vm2 w.r.t vr, vi\n else\n dg = [ dvm_dvr dvm_dvi ]; %% vm2 w.r.t vr, vi\n end\n end\n end\n\n function d2G = vm2_hess(obj, xx, lam, idx)\n %% unpack data\n [vr, vi] = deal(xx{:});\n nn = length(vr);\n\n %% evaluate Hessian of voltage magnitude^2 function\n if isempty(idx)\n idx = 1:nn;\n end\n n = length(idx);\n if length(lam) == n %% upper bound or equality\n dlam = sparse(idx, idx, 2*lam, nn, nn);\n else %% doubly bounded (use lam_ub-lam_lb)\n dlam = sparse(idx, idx, 2*(lam(n+1:2*n) - lam(1:n)), nn, nn);\n end\n\n %% construct Hessian\n zz = sparse(nn, nn);\n d2G = [dlam zz; zz dlam];\n end\n end %% methods\nend %% classdef\n", "meta": {"author": "MATPOWER", "repo": "matpower", "sha": "7da926d978824bf675a71e0a5cb91f8967f97007", "save_path": "github-repos/MATLAB/MATPOWER-matpower", "path": "github-repos/MATLAB/MATPOWER-matpower/matpower-7da926d978824bf675a71e0a5cb91f8967f97007/lib/+mp/form_acc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.3060993306308653}} {"text": "function [Phase_3, Phase_2, Phase_1, UPhase_3] = learn_struct_bnpc(data,node_sizes,epsilon,star)\n% G = learn_struct_bnpc(Data,node_sizes,epsilon,star)\n%\n% Data(i,m) is node i in case m.\n% node_sizes and epsilon are optionnals.\n% star = 0 to use try_to_separate_B instead of try_to_separate_B_star\n%\n% see \"Learning bayesian Networks from Data: A Efficient Approach Based on Information Theorie\"\n% Jie Cheng, David Bell and Weird Liu.\n%\n% Things to do : rewrite function orient_edges !\n% ! sometimes it causes crashes !\n%\n% V0.91 : 18 sept 2003 (olivier.francois@insa-rouen.fr)\n\nverbose=1;\n%if nargin < 5, mwst=0; end\nif nargin < 4, star=1; end\nif nargin < 3, epsilon=0.05; end\nif nargin < 2, node_sizes=max(data'); end\n\nif verbose\n fprintf('================== phase I : \\n');\nend\ntmp1=cputime;\n[Phase_1 II JJ score_mat score_mat2] = phaseI(data, node_sizes, epsilon);\ntmp1=cputime-tmp1;\n\nif verbose\n fprintf('Execution time : %2.5f\\n',tmp1);\n fprintf('\\n================== phase II : \\n');\nend\ntmp1=cputime;\nPhase_2 = phaseII(Phase_1, data, node_sizes, epsilon, II, JJ, score_mat);\ntmp1=cputime-tmp1;\n\nif verbose\n fprintf('Execution time : %2.5f\\n',tmp1);\n fprintf('\\n================== phase III : \\n');\nend\ntmp1=cputime;\n[Phase_3 UPhase_3] = phaseIII(Phase_2, data, node_sizes, epsilon, score_mat2, star);\ntmp1=cputime-tmp1;\nif verbose\n fprintf('Execution time : %2.5f\\n',tmp1);\nend\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [G, II, JJ, score_mat, sc2] = phaseI(data,node_sizes,alpha)\n% [G, II , JJ, score_mat, s2] = phaseI(data,node_sizes,epsilon)\n%\n% G is an acyclic graph\n% [II JJ] is the list of important edges not processed in phase I (for phase II)\n% score_mat is the mutual information score matrix\n%\n% data(i,m) is node i in case m.\n% alpha is the significant level for CI tests ( default=0.05 ).\n% node_sizes is the vector of sizes ( default=max(data') ).\n%\n% see \"Learning bayesian Networks from Data: A Efficient Approach Based on Information Theorie\"\n% Jie Cheng, David Bell and Weird Liu.\n\n% 0.\nif nargin < 3, alpha=0.05; end\nif nargin < 2, node_sizes=max(data'); end\n[N m] = size(data);\nscore_mat = zeros(N);\nedges=0;\n\n% 1.\nG = zeros(N);\nL=[];\n\n% 2. Use of Chi2 instead of MI ... allow using a confidence level alpha instead of an arbitrary epsilon\nfor i=1:(N-1)\n for j=(i+1):N\n [I score_mat(i,j)] = cond_indep_chisquare(i,j,[],data,'LRT',alpha,node_sizes);\n end\nend\nsc2=score_mat;\n\n\n[tmp ordre]=sort(-score_mat(:));\nordre2=ordre(find(-tmp>alpha));\n[II JJ]=ind2sub([N N],ordre2);\n\npointer=1 ;\nfini=length(II);\n\n% 3.\nedges=2;\nfor pointer=1:min(2,fini),\n %fprintf('%d-%d\\n',II(pointer),JJ(pointer));\n G(II(pointer),JJ(pointer))=1;\n G(JJ(pointer),II(pointer))=1;\n score_mat(II(pointer),JJ(pointer))=-inf;\nend\n\npointer=min(2,fini);\narret=0;\n\nwhile pointeralpha));\n[II JJ]=ind2sub([N N],ordre2);\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction G = phaseII(G1,data,node_sizes,alpha,II, JJ, score_mat)\n% G = phaseII(G1,data,node_sizes,epsilon,II,JJ, score_mat)\n%\n% G1, II, JJ,score_mat are given by phaseI.\n% data(i,m) is node i in case m.\n% node_sizes is the vector of sizes ( default=max(data') ).\n% alpha is the significant level for CI tests ( default=0.05 ).\n%\n% see \"Learning bayesian Networks from Data: A Efficient Approach Based on Information Theorie\"\n% Jie Cheng, David Bell and Weird Liu.\n\nst{1}='added';\nst{2}='';\n% 0.\n[N m] = size(data);\n\nG=G1;\n\n% 6.\nII=II(end:-1:1);\nJJ=JJ(end:-1:1);\n\npointer=length(II);\n\nwhile pointer>0\n % 7.\n trysep = try_to_separate_A(G,II(pointer),JJ(pointer),data,alpha,node_sizes);\n %fprintf('Try to separate %d and %d : %s\\n',II(pointer),JJ(pointer),st{trysep+1});\n if ~trysep\n G(II(pointer),JJ(pointer))=1;\n G(JJ(pointer),II(pointer))=1;\n %fprintf('%d-%d\\n',II(pointer),JJ(pointer));\n end\n % 8.\n pointer=pointer-1;\nend\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [G,U] = phaseIII(G1,data,node_sizes,alpha,s2,star)\n% [G] = phaseIII(G1,data,node_sizes,alpha,s2,star)\n%\n% data(i,m) is node i in case m.\n% if star~=0, use try_to_separate_B_star instead of try_to_separate_B (default star=1).\n% G is the non-oriented graph and G1 the oriented result.\n%\n% see \"Learning bayesian Networks from Data: A Efficient Approach Based on Information Theorie\"\n% Jie Cheng, David Bell and Weird Liu.\n\n% 0.\nif nargin < 2, disp('Not enough arguments');return; end\nif nargin < 3, node_sizes=max(data'); end\nif nargin < 4, alpha = 0.05; end\nif nargin < 5, star=1; end\nG=G1;\nN=length(G);\n% reachability_matrix of G\nM = expm(full(G)) - eye(length(G)); M = (M>0);\n\n% 9.\nfprintf('Thinning - separateA\\n');\n\n% Edges are examined in the inverse order of their Chi2 (or MI) score\ns2(find(~G))=0;\n[tmp ordre]=sort(s2(:));\nordre2=ordre(find(tmp>0));\n[I J]=ind2sub([N N],ordre2);\nii=1:length(I);\nfor i=ii,\n %fprintf('%d-%d : ',I(i),J(i));\n G(I(i),J(i))=0;\n G(J(i),I(i))=0;\n trysep = try_to_separate_A(G,I(i),J(i),data,alpha,node_sizes);\n\n if ~trysep,\n G(I(i),J(i))=1;\n G(J(i),I(i))=1;\n %fprintf(' keep\\n');\n %else\n %fprintf('delete\\n');\n end\nend\n\n% 10.\nfprintf('Thinning - separateB'); if star; fprintf('star'); end; fprintf('\\n');\ns2(find(~G))=0;\n[tmp ordre]=sort(s2(:));\nordre2=ordre(find(tmp>0));\n[I J]=ind2sub([N N],ordre2);\nii=1:length(I);\nfor i=ii,\n %fprintf('%d-%d : ',I(i),J(i));\n G(I(i),J(i))=0; G(J(i),I(i))=0;\n if star==0\n trysep = try_to_separate_B(G,I(i),J(i),data,node_sizes,alpha);\n else\n trysep = try_to_separate_B_star(G,I(i),J(i),data,node_sizes,alpha);\n end\n if ~trysep,\n G(I(i),J(i))=1; G(J(i),I(i))=1;\n %fprintf(' keep\\n');\n %else\n %fprintf('delete\\n');\n end\nend\n\n%11.\nfprintf('Thinning - orient_edges\\n');\nU=G;\nG=orient_edges(U,data,node_sizes,alpha);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [I, N1, N2] = try_to_separate_A(G,node1,node2,data,alpha,node_sizes)\n% [I, N1, N2] = try_to_separate_A(G,node1,node2,data,alpha,node_sizess)\n%\n% G is the current partially directed graph.\n% I is a boolean : I=1 <==> separated.\n% N1 : neighbors of node1 that are on an adjacency path between node1 and node2 (ditto for N2).\n%\n% see \"Learning bayesian Networks from Data: A Efficient Approach Based on Information Theorie\"\n% Jie Cheng, David Bell and Weird Liu.\n\n% 0.\nif node1==node2 | length(G)<2\n disp('Error: Check your arguments in try_to_separate_A.');I=0; return\nend\nN=size(data,1);\nif nargin==4, alpha=0.05; node_sizes=max(data'); end\nif nargin==5, node_sizes=max(data'); end\n\n% 1.\nN1=find(G(node1,:)==1);N01=N1;\nGG1=G(setdiff(1:N,node1),setdiff(1:N,node1));\nnode22=node2-(node2>node1);\n% reachability_matrix of GG1\nM = expm(full(GG1)) - eye(length(GG1)); M = (M>0);\n% N1 is the neighbors of node1 that are on the adjacency between node1 and node2\nfor i=N1\n j=i-(i>node1);\n if M(j,node22)~=1, N01=setdiff(N01,i); N1=setdiff(N1,i); end\n % 2.\n if ~G(node1,i), N1=setdiff(N1,i); end\nend\n\nN2=find(G(node2,:)==1);N02=N2;\nGG2=G(setdiff(1:N,node2),setdiff(1:N,node2));\nnode12=node1-(node20);\n% N2 is the neighbors of node2 that are on the adjacency between node1 and node2\nfor i=N2\n j=i-(i>node2);\n if M(node12,j)~=1, N02=setdiff(N02,i); N2=setdiff(N2,i); end\n % 2.\n if ~G(node2,i), N2=setdiff(N2,i); end\nend\n\n%fprintf('%d : N1=',node1); fprintf('%d',N1); fprintf('\\n');\n%fprintf('%d : N2=',node2); fprintf('%d',N2); fprintf('\\n');\n% 3.\nif length(N1)>length(N2), tmp=N1; N1=N2; N2=tmp; clear tmp, end\n% 4.\nC=N1;\nfor test=1:2\n if test==2, C=N2; end\n % 5.\n [I v1] = cond_indep_chisquare(node1,node2,C,data,'LRT',alpha,node_sizes);\n if I, %fprintf('%d-%d separated (%2.5f) by C=',node1,node2,v1); fprintf('%d',C); fprintf('\\n');\n return,\n %else\n %fprintf('%d-%d not separated (%2.5f) by C=',node1,node2,v1); fprintf('%d',C); fprintf('\\n');\n end;\n\n\n % 6.\n step6=1;\n while step6\n step6=0;\n if length(C)>=1\n v=[];\n for i=C\n\tCi = setdiff(C,i);\n\t[I(i) v(i)] = cond_indep_chisquare(node1,node2,Ci,data,'LRT',alpha,node_sizes);\n end\n [vm ind] = min(v);\n\n % 7.\n if I(ind)\n\tI = 1; return\n else\n\tif vm < v1\n\t v1 = vm;\n\t C = setdiff(C,ind);\n\t % goto step 6.\n\t step6 = 1;\n\tend\n end\n end\n\n % 8.\n if test==2, I=0; return, end\n end\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction I = try_to_separate_B(G,node1,node2,data,node_sizes,alpha,N1,N2)\n% I = try_to_separate_B(G,node1,node2,data,node_sizes,epsilon,N1,N2)\n%\n% G is the current partially directed graph.\n% data(i,m), node i in case m.\n% node_sizes is the vector of size of the attributs in data ( default max(data') )\n% N1 (optionnal) is the neighbors of node1 that are on an adjacency path between node1 and node2 (ditto for N2).\n% I is a boolean : I+1 <==> separated.\n%\n% see \"Learning bayesian Networks from Data: A Efficient Approach Based on Information Theorie\"\n% Jie Cheng, David Bell and Weird Liu.\n\n% 0.\nif node1==node2 | length(G)<2\n disp('Error: Verify your arguments in try_to_separate_B.');I=0; return\nend\nif nargin < 4,\n disp('Error : not enougth arguments'); I=0; return;\nend\nN=size(data,1);\n\n% 1.\nif nargin < 8\n N1=find(G(node1,:)==1);\n GG1=G(setdiff(1:N,node1),setdiff(1:N,node1));\n node22=node2-(node2>node1);\n M = expm(full(GG1)) - eye(length(GG1)); M = (M>0);\n for i=N1\n j=i-(i>node1);\n if M(j,node22)~=1, N1=setdiff(N1,i); end\n end\n N2=find(G(node2,:)==1);\n GG2=G(setdiff(1:N,node2),setdiff(1:N,node2));\n node12=node1-(node20);\n for i=N2\n j=i-(i>node2);\n if M(node12,j)~=1, N2=setdiff(N2,i); end\n end\nend\nif nargin < 6, alpha=0.05; end\nif nargin < 5, node_sizes=max(data'); end\nM = expm(full(G)) - eye(length(G)); M = (M>0);\n\n% 2.\nN1b=[];\nfor i=N1\n NN1=find(G(i,:)==1);\n for j=NN1\n if M(i,j)~=1 & ~ismember(j,N1), N1b=union(N1b,j); end\n end\nend\n\n% 3.\nN2b=[];\nfor i=N2\n NN2=find(G(i,:)==1);\n for j=NN2\n if M(i,j)~=1 & ~ismember(j,N2), N2b=union(N2b,j); end\n end\nend\n\n% 4.\nif length(union(N1,N1b)) < length(union(N2,N2b))\n C=union(N1,N1b);\nelse\n C=union(N2,N2b);\nend\n\n% 5.\ncontinu=1;\nwhile continu\n l=length(C);\n %fprintf('%d',continu);\n [I v] = cond_indep_chisquare(node1,node2,C,data,'LRT',alpha,node_sizes);\n if I==1; return, elseif l<2, I=0; return, end\n\n % 6.\n Cb=C;\n for i=1:l\n Ci=setdiff(C,C(i));\n [I vi] = cond_indep_chisquare(node1,node2,Ci,data,'LRT',alpha,node_sizes);\n e = (v+1)/3; % e is a small value...\n\tif I==1,return, elseif vinode1);\n M = expm(full(GG1)) - eye(length(GG1)); M = (M>0);\n for i=N1\n j=i-(i>node1);\n if M(j,node22)~=1, N1=setdiff(N1,i); end\n % 2.\n if ~G(node1,i), N1=setdiff(N1,i); end\n end\n N2=find(G(node2,:)==1);\n GG2=G(setdiff(1:N,node2),setdiff(1:N,node2));\n node12=node1-(node20);\n for i=N2\n j=i-(i>node2);\n if M(node12,j)~=1, N2=setdiff(N2,i); end\n % 2.\n if ~G(node2,i), N2=setdiff(N2,i); end\n end\nend\nif nargin < 6, alpha=0.05; end\nif nargin < 5, node_sizes=max(data'); end\n\n% 3.\nif length(N1)>length(N2), tmp=N1; N1=N2; N2=tmp; end\n\n% 4.\nC=N1;\nl=length(C);\nI=0;\n\n% 5.\nfor test=1:2\n continu=1;\n %test\n if test==2 & ~isempty(N2)\n C=N2; l=length(C); IsInCi=zeros(1,l); IsInCi(l)=1;\n else IsInCi=zeros(1,l);\n end\n s=ones(1,l);\n % Pour tous les sous-ensemble Ci de C :\n while continu & ~isempty(C)\n Ci = setdiff(C.*IsInCi,0);\n [I vi] = cond_indep_chisquare(node1,node2,Ci,data,'LRT',alpha,node_sizes);\n if I, %fprintf('%d-%d separated (%2.5f) by C=',node1,node2,vi); fprintf('%d',Ci); fprintf('\\n');\n return,\n %else\n %fprintf('%d-%d not separated (%2.5f) by C=',node1,node2,vi); fprintf('%d',Ci); fprintf('\\n');\n end;\n % if I, return, end\n\n if IsInCi==s, continu=0;\n else\n IsInCi(l)=IsInCi(l)+1;\n\n notOK=1; i=l;\n while notOK & i>1\n\tif IsInCi(i)>s(i), IsInCi(i)=0; IsInCi(i-1)=IsInCi(i-1)+1; else notOK=0; end\n\ti=i-1;\n end\n end\n end\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction G1 = orient_edges(G,data,node_sizes,alpha)\n% G1 = orient_edges(G,data,node_sizes)\n%\n% G is the partially directed graph.\n% data(i,m), node i in case m.\n% node_sizes is the vector of size of the attributs in data ( default max(data') )\n%\n% see \"Learning bayesian Networks from Data: A Efficient Approach Based on Information Theorie\"\n% Jie Cheng, David Bell and Weird Liu.\n\n% 0.\nif nargin < 4, alpha=0.05; end\nif nargin < 3, node_sizes=max(data'); end\nif nargin < 2, disp(' Require at least two arguments.'); return, end\nN=length(G);\nG1=G;\n\n% 1.\n[Lnode1 Lnode2]=find(triu(1-triu(G),1)); %[Lnode1 Lnode2]=ind2sub([N N],find(triu(1-triu(G),1)));\nfor ii = 1:length(Lnode1),\n node1=Lnode1(ii);\n node2=Lnode2(ii);\n %fprintf('%d %d\\n',node1,node2);\n N1 = find(G(node1,:)==1);\n N2 = find(G(node2,:)==1);\n if ~isempty(intersect(N1,N2))\n %fprintf('V1='); fprintf('%d ',N1); fprintf('\\n');\n %fprintf('V2='); fprintf('%d ',N2); fprintf('\\n');\n GG1 = G(setdiff(1:N,node1),setdiff(1:N,node1));\n node22 = node2-(node2>node1);\n % reachability_matrix of GG1\n M = expm(full(GG1)) - eye(length(GG1)); M = (M>0);\n % N1 is the neighbors of node1 that are on the adjacency between node1 and node2\n for i = N1\n j = i-(i>node1);\n if M(j,node22)~=1, N1=setdiff(N1,i);\n end\n end\n GG2 = G(setdiff(1:N,node2),setdiff(1:N,node2));\n node12 = node1-(node20);\n % N2 is the neighbors of node2 that are on the adjacency between node1 and node2\n for i=N2\n j = i-(i>node2);\n if M(node12,j)~=1, N2=setdiff(N2,i); end\n end\n %fprintf('%d %d\\n',node1,node2);\n %fprintf('N1='); fprintf('%d ',N1); fprintf('\\n');\n %fprintf('N2='); fprintf('%d ',N2); fprintf('\\n');\n\n % 2.\n M = expm(full(G)) - eye(length(G)); M = (M>0);\n N1b=N1;\n for i=N1\n NN1 = find(G(i,:)==1);\n for j=NN1\n\tif M(i,j)~=1 & ~ismember(j,N1), N1b=union(N1b,j); end\n end\n end\n %fprintf('N1''='); fprintf('%d ',N1b); fprintf('\\n');\n\n % 3.\n N2b=N2;\n for i=N2\n NN2 = find(G(i,:)==1);\n for j=NN2\n\tif M(i,j)~=1 & ~ismember(j,N2), N2b=union(N2b,j); end\n end\n end\n %fprintf('N2''='); fprintf('%d ',N2b); fprintf('\\n');\n\n % 4.\n if length(N1b) < length(N2b)\n C = N1b;\n else\n C = N2b;\n end\n %l=length(C);\n %fprintf('C='); fprintf('%d ',C); fprintf('\\n');\n\n % 7.\n step5=1;\n while step5\n step5=0;\n %fprintf('.');\n % 5.\n l=length(C);\n [I v] = cond_indep_chisquare(node1,node2,C,data,'LRT',alpha,node_sizes);\n %fprintf('C='); fprintf('%d ',C);\n %fprintf(': %d %2.5f\\n',I,v);\n\n step8=0;\n if I==1 & v~=0 % v < epsilon\n\tstep8=1;\n else\n\tif l==1\n\t G1(C,node1)=0; G1(C,node2)=0;\n\t fprintf('%d -> %d <- %d\\n',node1,C,node2);\n\t step8=1;\n\tend\n end\n %fprintf('%d\\n',step8);\n\n % 6.\n if ~step8\n\tCb=C;\n\tfor i=1:l\n\t Ci=setdiff(C,C(i));\n\t [I vi] = cond_indep_chisquare(node1,node2,Ci,data,'LRT',alpha,node_sizes);\n\t % e = (v+1)/3; % e is a small value...\n\t if I==1 % vi < v+e\n\t Cb=setdiff(Cb,C(i));\n\t if ismember(C(i),N1) & ismember(C(i),N2)\n\t G1(C(i),node1)=0; G1(C(i),node2)=0;\n\t fprintf('%d -> %d <- %d\\n',node1,C(i),node2);\n\t end\n\t if I==1 % vi < epsilon\n\t step8=1;\n\t end\n\t end\n\tend % for\n end % if\n\n % 7.\n if ~step8\n\tif length(Cb) < length(C), C=Cb; end\n\tif length(C) > 0, step5==1; end\n end\n end % while step5\n % step8 : passer � la paire de noeud suivant\n %fprintf('\\n');\n %else\n %fprintf(' No common neighbor\\n');\n end % if\nend % for\n\n% 11.\nstep9=0;\nfprintf('Infering directions ');\ntest = pdag_to_dag(G1);\nwhile ~isdag(test) %& step9 %d ... \\n',a,b);\n\t if G1(b,c)==1 & G1(c,b)==1\n\t\tif G1(a,c)+G1(c,a)==0,\n\t\t G1(c,b)=0;\n\t\t fprintf('%d -> %d (9)\\n',b,c);\n\t\tend\n\t end\n\t end\n\t end\n end, end, end\n\n % 10.\n for a=1:N-1, for b=a+1:N\n\tif G1(a,b)==1 & G1(b,a)==1\n\t GGG1=xor(G1,G1'); % matrice des arcs orient�s de G1\n\t M = expm(full(GGG1)) - eye(length(GGG1)); M = (M>0);\n\t if M(a,b)==1,\n\t G1(b,a)=0;\n\t fprintf('%d -> %d (10)\\n',a,b);\n\t end\n\tend\n end, end\n\n test = pdag_to_dag(G1);\n if isempty(test), G1=return_one_edge(G1); end\n %else\n % G1, return,\n %end\nend % while 11.\nG1 = pdag_to_dag(G1);\nfprintf('%d boucles\\n',step9);\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction b = isdag(G)\nb = sum(sum(G.*G')); % How many undirected arcs ? (x2)\nb=~b & ~isempty(G);\nif b\n M = expm(full(G)) - eye(length(G)); M = (M>0);\n b = b & find(sum(sum(eye(length(G)).*M))); % is there no cycle ?\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction G=return_one_edge(G)\nN=length(G); fam=[]; node2=[];\npermnode = randperm(5); i=0; %fprintf('rev\\n');\nwhile isempty(fam) | isempty(node2) | i==N\n i=i+1;\n node = permnode(i); %node = ceil(rand(1)*N);\n fam=find(G(node,:)==1);\n par=find(G(:,node)==1);\n fam = myunion(fam, par);\n if ~isempty(fam)\n node2 = fam(ceil(rand(1)*length(fam)));\n par2=find(G(:,node)==1);\n if ~isempty(intersect(par2, node)), node2=[]; end\n end\nend\nif isempty(myintersect(node, par2)),\n G(node, node2)=0;\n G(node2, node)=1;\n fprintf('%d -> %d (Rev)\\n',node, node2);\nelse\n G(node, node2)=1;\n G(node2, node)=0;\n fprintf('%d -> %d (Rev)\\n',node2, node);\nend\n", "meta": {"author": "bayesnet", "repo": "bnt", "sha": "bebba5f437b4e1e29169f0f3669df59fb5392e62", "save_path": "github-repos/MATLAB/bayesnet-bnt", "path": "github-repos/MATLAB/bayesnet-bnt/bnt-bebba5f437b4e1e29169f0f3669df59fb5392e62/SLP/learning/learn_struct_bnpc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6688802735722128, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.3057697322114779}} {"text": "%-------------------------------------------------------------------------------------------------------------------%\n%\n% IB2d is an Immersed Boundary Code (IB) for solving fully coupled non-linear \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: nick.battista@unc.edu\n% Date Created: May 27th, 2015\n% Institution: UNC-CH\n%\n% This code is capable of creating Lagrangian Structures using:\n% \t1. Springs\n% \t2. Beams (*torsional springs)\n% \t3. Target Points\n%\t4. Muscle-Model (combined Force-Length-Velocity model, \"HIll+(Length-Tension)\")\n%\n% One is able to update those Lagrangian Structure parameters, e.g., spring constants, resting %%\tlengths, 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 (nick.battista@unc.edu) know.\n%\n%--------------------------------------------------------------------------------------------------------------------%\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: Plots the Lagrangian structure with:\n% (1): the background velocity field\n% (2): the Lagrangian structure itself\n% (3): the vorticity field in a colormap\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [loc, diffy] = please_Plot_Results(ds,X,Y,U,V,vort,uMag,p,C,chiX,chiY,lagPlot,velPlot,vortPlot,pressPlot,uMagPlot,conPlot,firstPrint,loc,diffy,spacing)\n\n%X,Y: (x,y) values\n%U,V: x-directed, y-directed velocities respectively\n%vort: vorticity\n%uMag: magnitude of velocity\n%p: pressure\n\n%FLAGS FOR PLOTTING:\n%pressPlot - if you want pressure plot = 1\n%uMagPlot - if you want mag. velocity plot = 1\n%vortPlot - if you want vorticity plot = 1\n%velPlot - if you want velocity plot = 1\n%lagPlot - if you want lag. point ONLY plot = 1\n%conPlot - if you want concentration plot =1\n%\n% Assumption: Assuming chiX and chiY are column vectors\n% Assumption: Assuming chiX(i+1)-chiX(i) < .5 and chiY(i+1)-chiY(i) < .5, for all points that don't cross the boundary\n%\n% This script has been adapted from the Mat-IB code by Hiens and Stockie, 2014.\n%\n\nLx = X(1,end)+X(1,2);\nLy = Y(end,1)+Y(2,1);\n\n%Shift so inside of interval [0,Lx] or [0,Ly]\nchiX = mod(chiX,Lx);\nchiY = mod(chiY,Ly);\n\n%Connect Geometry Appropriately At Beginning Of Simulation then Store it!\nif firstPrint == 1\n diffX = abs([chiX(2:end);chiX(1)]-chiX);\n diffY = abs([chiY(2:end);chiY(1)]-chiY);\n\n locX = find(diffX > spacing ); % assuming x value can't change more than Lx/2 (without crossing boundary)\n locY = find(diffY > spacing ); % assuming y value can't change more than Ly/2 (without crossing boundary)\n loc = sort(unique([locX;locY]));\n\n diffy = sqrt( (chiX(end)-chiX(1) )^2 + ( chiY(end)-chiY(1) )^2 );\nend\n\nclf; %Clear previous plots :)\n\n\n\n[N1,N2,num_con]=size(C);\nfigure(1) \nnumPlots = lagPlot+velPlot+vortPlot+pressPlot+uMagPlot+conPlot+(num_con-1);\n\nct = 1;\n\n% % % % % PLOTS LAGRANGIAN POINTS ONLY (if selected) % % % % %\n\nif lagPlot == 1\n subplot(1,numPlots,ct)\n axis([0 Lx 0 Ly]);\n title('LAGRANGIAN PTS');\n xlabel('x'); ylabel('y');\n hold all;\n\n loc = [0;loc;length(chiX)];\n for i=2:length(loc)\n plot(chiX(loc(i-1)+1:loc(i)),chiY(loc(i-1)+1:loc(i)),'m','LineWidth',3);\n end\n if diffy < 5*ds\n xTemp = [chiX(1) chiX(end)];\n yTemp = [chiY(1) chiY(end)];\n plot(xTemp(1:2),yTemp(1:2),'m','LineWidth',3);\n end\n\n axis square;\n\n ct=ct+1;\nend\n\n% % % % % PLOTS VORTICITY + LAG Pts. (if selected) % % % % %\n\nif vortPlot == 1\n \n subplot(1,numPlots,ct)\n %\n axis([0 Lx 0 Ly]);\n title('VORTICITY');\n xlabel('x'); ylabel('y'); \n hold all;\n\n %Compute Vorticity and Plot It against Lagrangian Grid!\n x = X(1,:); y = Y(:,1);\n contourf(x,y,flipud(rot90(vort)),10); hold on;\n\n loc = [0;loc;length(chiX)];\n for i=2:length(loc)\n plot(chiX(loc(i-1)+1:loc(i)),chiY(loc(i-1)+1:loc(i)),'m','LineWidth',3);\n end\n if diffy < 5*ds\n xTemp = [chiX(1) chiX(end)];\n yTemp = [chiY(1) chiY(end)];\n plot(xTemp(1:2),yTemp(1:2),'m','LineWidth',3);\n end\n \n axis square;\n\n ct=ct+1;\nend\n\n% % % % % PLOTS PRESSURE + LAG Pts. (if selected) % % % % %\n\nif pressPlot == 1\n \n subplot(1,numPlots,ct)\n %\n axis([0 Lx 0 Ly]);\n title('PRESSURE');\n xlabel('x'); ylabel('y'); \n hold all;\n\n %Use Pressure and Plot It against Lagrangian Grid!\n x = X(1,:); y = Y(:,1);\n contourf(x,y,p,6); hold on;\n\n loc = [0;loc;length(chiX)];\n for i=2:length(loc)\n plot(chiX(loc(i-1)+1:loc(i)),chiY(loc(i-1)+1:loc(i)),'m','LineWidth',3);\n end\n if diffy < 5*ds\n xTemp = [chiX(1) chiX(end)];\n yTemp = [chiY(1) chiY(end)];\n plot(xTemp(1:2),yTemp(1:2),'m','LineWidth',3);\n end\n\n axis square;\n \n ct=ct+1;\nend\n\n% % % % % PLOTS MAGNITUDE OF VELOCITY + LAG Pts. (if selected) % % % % %\n\nif uMagPlot == 1\n \n subplot(1,numPlots,ct)\n %\n axis([0 Lx 0 Ly]);\n title('MAGNITUDE OF VELOCITY');\n xlabel('x'); ylabel('y'); \n hold all;\n\n %Use Mag. Velocity and Plot It against Lagrangian Grid!\n x = X(1,:); y = Y(:,1);\n contourf(x,y,uMag,6); hold on;\n\n loc = [0;loc;length(chiX)];\n for i=2:length(loc)\n plot(chiX(loc(i-1)+1:loc(i)),chiY(loc(i-1)+1:loc(i)),'m','LineWidth',3);\n end\n if diffy < 5*ds\n xTemp = [chiX(1) chiX(end)];\n yTemp = [chiY(1) chiY(end)];\n plot(xTemp(1:2),yTemp(1:2),'m','LineWidth',3);\n end\n\n axis square;\n \n ct=ct+1;\nend\n\n% % % % % PLOTS VELOCITY FIELD + LAG Pts. (if selected) % % % % %\n\nif velPlot == 1\n \n subplot(1,numPlots,ct)\n %\n axis([0 Lx 0 Ly]);\n title('VELOCITY');\n xlabel('x'); ylabel('y');\n hold all;\n \n \n quiver(X,Y,U,V); %Print Velocity Field\n \n \n loc = [0;loc;length(chiX)];\n for i=2:length(loc)\n plot(chiX(loc(i-1)+1:loc(i)),chiY(loc(i-1)+1:loc(i)),'m','LineWidth',3);\n end\n if diffy < 5*ds\n xTemp = [chiX(1) chiX(end)];\n yTemp = [chiY(1) chiY(end)];\n plot(xTemp(1:2),yTemp(1:2),'m','LineWidth',3);\n end\n\n axis square;\n \n ct=ct+1;\nend\n\nif conPlot == 1\n % plotting all concentrations\n for ic=1:num_con \n subplot(1,numPlots,ct)\n %\n axis([0 Lx 0 Ly]);\n title(sprintf('Concentration%g',ic));\n xlabel('x'); ylabel('y'); \n hold all;\n\n x = X(1,:); y = Y(:,1);\n pcolor(X,Y,C(:,:,ic));\n shading interp;\n\n loc = [0;loc;length(chiX)];\n for i=2:length(loc)\n plot(chiX(loc(i-1)+1:loc(i)),chiY(loc(i-1)+1:loc(i)),'m','LineWidth',3);\n end\n if diffy < 5*ds\n xTemp = [chiX(1) chiX(end)];\n yTemp = [chiY(1) chiY(end)];\n plot(xTemp(1:2),yTemp(1:2),'m','LineWidth',3);\n end\n \n axis square;\n\n ct=ct+1;\n end\nend\n\ndrawnow;\n\nhold off;\nset(gca,'Box','on');\n", "meta": {"author": "nickabattista", "repo": "IB2d", "sha": "392d99c228cc801ff65766889c72e2e1492fe747", "save_path": "github-repos/MATLAB/nickabattista-IB2d", "path": "github-repos/MATLAB/nickabattista-IB2d/IB2d-392d99c228cc801ff65766889c72e2e1492fe747/matIB2d/IBM_Blackbox/please_Plot_Results.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6113819591324416, "lm_q2_score": 0.5, "lm_q1q2_score": 0.3056909795662208}} {"text": "function [new_nbrs, new_ops, new_nodes, new_topos] = mk_nbrs_of_dag_topo(G0)\n% MK_NBRS_OF_DAG_TOPO Make all DAGs that differ from G0 by a single edge deletion, addition or reversal\n% [new_nbrs, new_ops, new_nodes, new_topos] = mk_nbrs_of_dag_topo(G0)\n%\n% new_nbrs{i} is the i'th neighbor of G0.\n% new_ops{i} = 'add', 'del', or 'rev' is the operation used to create the i'th neighbor.\n% new_nodes(i,1:2) are the head and tail of the operated-on arc.\n% new_topos are topological orders of the neighbours.\n%\n% We implement the fast acyclicity check described by P. Giudici and R. Castelo,\n% \"Improving MCMC model search for data mining\", submitted to J. Machine Learning, 2001.\n%\n% Written by Qian Diao on 19 Nov 01\n% Reference are ..\\BNT\\graph\\mk_nbrs_of_dag.m, ..\\BNT\\learning\\learn_struct_mcmc.m and \n% ..\\BNT\\graph\\topological_sort.m\n% Copyright Intel 2001\n%\nnew_nbrs = {};\nnew_ops = {};\nnew_nodes = [];\nnew_topos = {};\ncs = {};\n\nn = length(G0);\nindeg = zeros(1,n);\nzero_indeg = []; % a stack of nodes with no parents\nfor i=1:n\n indeg(i) = length(parents(G0,i));\n cs{i} = children(G0, i); \n if indeg(i)==0\n zero_indeg = [i zero_indeg];\n end\nend\n\ndag = G0;\n[nbrs, ops, nodes] = mk_nbrs_of_digraph(dag);\nA = init_ancestor_matrix(dag);\n%assert(acyclic(new_dag));\n\nd1 = 1;\nfor d = 1:length(ops)\n i = nodes(d, 1); j = nodes(d, 2);\n legal = 0;\n switch ops{d}\n case 'add',\n if A(i,j)==0\n legal = 1;\n end\n case 'del',\n legal = 1;\n case 'rev',\n ps = mysetdiff(parents(dag, j), i);\n % if any(A(ps,i)) then there is a path i -> parent of j -> j\n % so reversing i->j would create a cycle\n legal = ~any(A(ps, i));\n end\n\n if legal \n tmp = nbrs(:,:,d);\n new_nbrs{d1} = tmp;\n new_ops{d1} = ops{d};\n new_nodes(d1,1:2) = nodes(d,1:2);\n\n % obtain the topological orders of neighbour dags\n zero_indeg_nbr = [];\n indeg_nbr = [];\n cs_nbr = [];\n\n switch ops{d}\n case 'add' % i is a new parent of j \n zero_indeg_nbr = zero_indeg;\n indeg_nbr = indeg; \n if ~isempty(find(zero_indeg == j)) % j is not a root anymore \n zero_indeg_nbr = mysetdiff(zero_indeg, j); \n end \n indeg_nbr(j) = indeg(j)+1;\n\n t_nbr=1;\n order_nbr = zeros(1,n);\n while ~isempty(zero_indeg_nbr)\n v_nbr = zero_indeg_nbr(1); % pop v\n zero_indeg_nbr = zero_indeg_nbr(2:end);\n order_nbr(t_nbr) = v_nbr;\n t_nbr = t_nbr + 1;\n if v_nbr == i % j is a new child of i\n cs_nbr = sort([j cs{i}]);\n else\n cs_nbr = cs{v_nbr};\n end \n for k = 1:length(cs_nbr)\n c_nbr = cs_nbr(k);\n indeg_nbr(c_nbr) = indeg_nbr(c_nbr) - 1;\n if indeg_nbr(c_nbr) == 0\n zero_indeg_nbr = [c_nbr zero_indeg_nbr]; % push c \n end\n end\n end\n\n case 'del' % i is not a parent of j anymore\n zero_indeg_nbr = zero_indeg; \n indeg_nbr = indeg; \n if length(parents(tmp, j))==0 \n zero_indeg_nbr = -sort(-[zero_indeg, j]); % descending order\n end \n indeg_nbr(j) = indeg(j) - 1;\n\n t_nbr=1;\n order_nbr = zeros(1,n);\n while ~isempty(zero_indeg_nbr)\n v_nbr = zero_indeg_nbr(1); % pop v\n zero_indeg_nbr = zero_indeg_nbr(2:end);\n order_nbr(t_nbr) = v_nbr;\n t_nbr = t_nbr + 1;\n if v_nbr == i % j is not a child of i anymore\n cs_nbr = mysetdiff(cs{i}, j);\n else\n cs_nbr = cs{v_nbr};\n end \n for k = 1:length(cs_nbr)\n c_nbr = cs_nbr(k);\n indeg_nbr(c_nbr) = indeg_nbr(c_nbr) - 1;\n if indeg_nbr(c_nbr) == 0\n zero_indeg_nbr = [c_nbr zero_indeg_nbr]; % push c \n end\n end\n end\n\n case 'rev' %i is a new child of j and j is a new parent of i\n zero_indeg_nbr = zero_indeg; \n indeg_nbr = indeg;\n if ~isempty(find(zero_indeg == i)) \n zero_indeg_nbr = mysetdiff(zero_indeg_nbr, i); \n end \n if length(parents(tmp, j))==0 \n zero_indeg_nbr = -sort(-[zero_indeg_nbr, j]); % decending order\n end \n indeg_nbr(i) = indeg(i)+1;\n indeg_nbr(j) = indeg(j)-1;\n\n t_nbr=1;\n order_nbr = zeros(1,n);\n while ~isempty(zero_indeg_nbr)\n v_nbr = zero_indeg_nbr(1); % pop v\n zero_indeg_nbr = zero_indeg_nbr(2:end);\n order_nbr(t_nbr) = v_nbr;\n t_nbr = t_nbr + 1;\n cs_nbr = cs{v_nbr};\n if v_nbr == i % j is not a child of i anymore\n cs_nbr = mysetdiff(cs{i}, j);\n end\n if v_nbr == j % i is a new child of j \n cs_nbr = sort([i cs{j}]); \n end \n for k = 1:length(cs_nbr)\n c_nbr = cs_nbr(k);\n indeg_nbr(c_nbr) = indeg_nbr(c_nbr) - 1;\n if indeg_nbr(c_nbr) == 0\n zero_indeg_nbr = [c_nbr zero_indeg_nbr]; % push c \n end\n end\n end\n end \n\n new_topos{d1} = order_nbr; \n d1 = d1+1;\n end \nend\n\nclear nbrs ops nodes;\n\n\n\n%%%%%%%%%\nfunction A = update_row(A, j, dag)\n% We compute row j of A\nA(j, :) = 0;\nps = parents(dag, j);\nif ~isempty(ps)\n A(j, ps) = 1;\nend\nfor k=ps(:)'\n anck = find(A(k,:));\n if ~isempty(anck)\n A(j, anck) = 1;\n end\nend\n\n%%%%%%%%\nfunction A = init_ancestor_matrix(dag)\norder = topological_sort(dag);\nA = zeros(length(dag));\nfor j=order(:)'\n A = update_row(A, j, dag);\nend\n\n ", "meta": {"author": "bayesnet", "repo": "bnt", "sha": "bebba5f437b4e1e29169f0f3669df59fb5392e62", "save_path": "github-repos/MATLAB/bayesnet-bnt", "path": "github-repos/MATLAB/bayesnet-bnt/bnt-bebba5f437b4e1e29169f0f3669df59fb5392e62/SLP/misc/mk_nbrs_of_dag_topo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926665855647394, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.30559069490073837}} {"text": "% testRadiomicsFeaturesWithPyRadiomics.m\n%\n% Script to compare CERR and pyRadiomics features\n%\n% APA, 2/22/2018\n\nglobal planC\nindexS = planC{end};\n\n% Wavelet decomposition flag\nwavDecompFlg = 1; % 0: original image, 1: wavelet pre-processing\n\n% Specify discretization\nfixedMinMaxGrLevFlag = 0; % 1: to input fixed min/max/grLevels, 0: min/max \n % calculated for the structure and bin width of binWidth.\nbinWidth = 25;\nstructNum = 1;\nscanNum = 1;\npyradScanType = 'original';\n\nparamS.firstOrderParamS.offsetForEnergy = planC{indexS.scan}(scanNum).scanInfo(1).CTOffset;\nparamS.firstOrderParamS.binWidth = binWidth;\n\n% Get structure\n[rasterSegments, planC, isError] = getRasterSegments(structNum,planC);\n[mask3M, uniqueSlices] = rasterToMask(rasterSegments, scanNum, planC);\nscanArray3M = getScanArray(planC{indexS.scan}(scanNum));\nscanArray3M = double(scanArray3M) - ...\n planC{indexS.scan}(scanNum).scanInfo(1).CTOffset;\n% Wavelet decomposition\nif wavDecompFlg == 1\n dirString = 'HHL';\n wavType = 'coif1';\n scanArray3M = flip(scanArray3M,3);\n if mod(size(scanArray3M,3),2) > 0\n scanArray3M(:,:,end+1) = 0*scanArray3M(:,:,1);\n end\n scanArray3M = wavDecom3D(double(scanArray3M),dirString,wavType);\n if mod(size(scanArray3M,3),2) > 0\n scanArray3M = scanArray3M(:,:,1:end-1);\n end\n scanArray3M = flip(scanArray3M,3);\nend\n\nSUVvals3M = mask3M.*double(scanArray3M(:,:,uniqueSlices));\n[minr, maxr, minc, maxc, mins, maxs] = compute_boundingbox(mask3M);\nmaskBoundingBox3M = mask3M(minr:maxr,minc:maxc,mins:maxs);\n\n% Assign NaN to image outside mask\nvolToEval = SUVvals3M(minr:maxr,minc:maxc,mins:maxs);\nvolToEval(~maskBoundingBox3M) = NaN;\n\n% Get x,y,z grid for the shape features (flip y to make it monotically\n% increasing)\n[xValsV, yValsV, zValsV] = getUniformScanXYZVals(planC{indexS.scan}(scanNum));\nyValsV = fliplr(yValsV);\nxValsV = xValsV(minc:maxc);\nyValsV = yValsV(minr:maxr);\nzValsV = zValsV(mins:maxs);\nPixelSpacingX = abs(xValsV(2)-xValsV(1));\nPixelSpacingY = abs(yValsV(2)-yValsV(1));\nPixelSpacingZ = abs(zValsV(2)-zValsV(1));\nVoxelVol = PixelSpacingX*PixelSpacingY*PixelSpacingZ*1000; % convert cm to mm\n\nif fixedMinMaxGrLevFlag\n numGrLevels = paramS.higherOrderParamS.numGrLevels;\n minIntensity = paramS.higherOrderParamS.minIntensity;\n maxIntensity = paramS.higherOrderParamS.maxIntensity;\n % Quantize using the number of bins\n quantizedM = imquantize_cerr(volToEval,numGrLevels,...\n minIntensity,maxIntensity);\n\nelse % Quantize using the binwidth\n minIntensity = [];\n maxIntensity = [];\n numGrLevels = []; \n quantizedM = imquantize_cerr(volToEval,numGrLevels,...\n minIntensity,maxIntensity,binwidth); \n numGrLevels = max(quantizedM(:));\n paramS.higherOrderParamS.numGrLevels = numGrLevels;\nend\n\nparamS.higherOrderParamS.numGrLevels = numGrLevels;\nparamS.higherOrderParamS.patchRadius3dV = [1 1 1];\nparamS.higherOrderParamS.imgDiffThresh = 0; \n\n% Number of voxels (used in run percentage calculation)\nnumVoxels = sum(~isnan(quantizedM(:)));\n\n\n%% First order features\nfeatureS.firstOrderS = radiomics_first_order_stats...\n (volToEval(logical(maskBoundingBox3M)), VoxelVol, ...\n paramS.firstOrderParamS.offsetForEnergy, paramS.firstOrderParamS.binWidth);\nfirstOrderS = featureS.firstOrderS;\ncerrFirstOrderV = [firstOrderS.energy, firstOrderS.totalEnergy, firstOrderS.interQuartileRange, ...\n firstOrderS.kurtosis+3, firstOrderS.max, firstOrderS.mean, firstOrderS.meanAbsDev, ...\n firstOrderS.median, firstOrderS.medianAbsDev, firstOrderS.min, ...\n firstOrderS.P10, firstOrderS.P90, firstOrderS.interQuartileRange, ...\n firstOrderS.robustMeanAbsDev, firstOrderS.rms, firstOrderS.skewness, ...\n firstOrderS.std, firstOrderS.var, firstOrderS.entropy];\npyradFirstorderNamC = {'Energy', 'TotalEnergy','InterquartileRange','Kurtosis',...\n 'Maximum', 'Mean','MeanAbsoluteDeviation','Median','medianAbsDev',...\n 'Minimum','10Percentile','90Percentile','InterquartileRange',...\n 'RobustMeanAbsoluteDeviation','RootMeanSquared','Skewness',...\n 'StandardDeviation','Variance','Entropy'};\npyradFirstorderNamC = strcat([pyradScanType,'_firstorder_'],pyradFirstorderNamC);\npyRadFirstOrderV = [];\nfor i = 1:length(pyradFirstorderNamC)\n if isfield(teststruct,pyradFirstorderNamC{i})\n pyRadFirstOrderV(i) = teststruct.(pyradFirstorderNamC{i});\n else\n pyRadFirstOrderV(i) = NaN;\n end\nend\n\ndiffFirstOrderV = (cerrFirstOrderV - pyRadFirstOrderV) ./ cerrFirstOrderV * 100\n\n\n\n%% Shape features\nfeatureS.shapeS = getShapeParams(maskBoundingBox3M, ...\n {xValsV, yValsV, zValsV});\nshapeS = featureS.shapeS;\ncerrShapeV = [shapeS.majorAxis, shapeS.minorAxis, shapeS.leastAxis, ...\n shapeS.flatness, shapeS.elongation, shapeS.max3dDiameter, shapeS.max2dDiameterAxialPlane,...\n shapeS.max2dDiameterSagittalPlane', shapeS.max2dDiameterCoronalPlane, ...\n shapeS.Compactness1, shapeS.Compactness2, shapeS.spherDisprop, ...\n shapeS.sphericity, shapeS.surfToVolRatio/10,...\n shapeS.surfArea*100, shapeS.volume*1000];\npyradShapeNamC = {'MajorAxis', 'MinorAxis', 'LeastAxis', 'Flatness', 'Elongation', ...\n 'Maximum3DDiameter', 'Maximum2DDiameterSlice', 'Maximum2DDiameterRow', ...\n 'Maximum2DDiameterColumn', 'Compactness1','Compactness2','spherDisprop','Sphericity', ...\n 'SurfaceVolumeRatio','SurfaceArea','Volume'};\npyradShapeNamC = strcat([pyradScanType,'_shape_'],pyradShapeNamC);\npyRadShapeV = [];\nfor i = 1:length(pyradShapeNamC)\n if isfield(teststruct,pyradShapeNamC{i})\n pyRadShapeV(i) = teststruct.(pyradShapeNamC{i});\n else\n pyRadShapeV(i) = NaN;\n end\nend\nshapeDiffV = (cerrShapeV - pyRadShapeV) ./ cerrShapeV * 100\n\n%% GLCM features\n\n% Define flags\nglcmFlagS.energy = 1;\nglcmFlagS.jointEntropy = 1;\nglcmFlagS.jointMax = 1;\nglcmFlagS.jointAvg = 1;\nglcmFlagS.jointVar = 1;\nglcmFlagS.contrast = 1;\nglcmFlagS.invDiffMoment = 1;\nglcmFlagS.sumAvg = 1;\nglcmFlagS.corr = 1;\nglcmFlagS.clustShade = 1;\nglcmFlagS.clustProm = 1;\nglcmFlagS.haralickCorr = 1;\nglcmFlagS.invDiffMomNorm = 1;\nglcmFlagS.invDiff = 1;\nglcmFlagS.invDiffNorm = 1;\nglcmFlagS.invVar = 1;\nglcmFlagS.dissimilarity = 1;\nglcmFlagS.diffEntropy = 1;\nglcmFlagS.diffVar = 1;\nglcmFlagS.diffAvg = 1;\nglcmFlagS.sumVar = 1;\nglcmFlagS.sumEntropy = 1;\nglcmFlagS.clustTendency = 1;\nglcmFlagS.autoCorr = 1;\nglcmFlagS.invDiffMomNorm = 1;\nglcmFlagS.firstInfCorr = 1;\nglcmFlagS.secondInfCorr = 1;\n\ndirctn = 1;\ncooccurType = 2;\nfeatureS.harFeat3DdirS = get_haralick(dirctn, cooccurType, quantizedM, ...\nnumGrLevels, glcmFlagS);\n\n% harlCombS = featureS.harFeat3DcombS.CombS;\nharlCombS = featureS.harFeat3DdirS.AvgS;\ncerrGlcmV = [harlCombS.autoCorr, harlCombS.jointAvg, harlCombS.clustPromin, harlCombS.clustShade, harlCombS.clustTendency, ...\nharlCombS.contrast, harlCombS.corr, harlCombS.diffAvg, harlCombS.diffEntropy, harlCombS.diffVar, harlCombS.dissimilarity, ...\nharlCombS.energy, harlCombS.jointEntropy, harlCombS.invDiff, harlCombS.invDiffMom, harlCombS.firstInfCorr, ...\nharlCombS.secondInfCorr, harlCombS.invDiffMomNorm, harlCombS.invDiffNorm, harlCombS.invVar, ...\nharlCombS.sumAvg, harlCombS.sumEntropy, harlCombS.sumVar];\n\npyradGlcmNamC = {'Autocorrelation', 'JointAverage', 'ClusterProminence', 'ClusterShade', 'ClusterTendency', ...\n 'Contrast', 'Correlation', 'DifferenceAverage', 'DifferenceEntropy', 'DifferenceVariance', 'Dissimilarity', ...\n 'JointEnergy', 'JointEntropy','Id','Idm', 'Imc1' , ...\n 'Imc2', 'Idmn','Idn','InverseVariance', 'sumAverage', 'SumEntropy', 'sumVariance'};\n\npyradGlcmNamC = strcat([pyradScanType,'_glcm_'],pyradGlcmNamC);\npyRadGlcmV = [];\nfor i = 1:length(pyradGlcmNamC)\n if isfield(teststruct,pyradGlcmNamC{i})\n pyRadGlcmV(i) = teststruct.(pyradGlcmNamC{i});\n else\n pyRadGlcmV(i) = NaN;\n end\nend\n\nglcmDiffV = (cerrGlcmV - pyRadGlcmV) ./ cerrGlcmV * 100\n\n\n%% RLM features\n\nrlmFlagS.sre = 1;\nrlmFlagS.lre = 1;\nrlmFlagS.gln = 1;\nrlmFlagS.glnNorm = 1;\nrlmFlagS.rln = 1;\nrlmFlagS.rlnNorm = 1;\nrlmFlagS.rp = 1;\nrlmFlagS.lglre = 1;\nrlmFlagS.hglre = 1;\nrlmFlagS.srlgle = 1;\nrlmFlagS.srhgle = 1;\nrlmFlagS.lrlgle = 1;\nrlmFlagS.lrhgle = 1;\nrlmFlagS.glv = 1;\nrlmFlagS.rlv = 1;\nrlmFlagS.re = 1;\n\nnumGrLevels = paramS.higherOrderParamS.numGrLevels;\n\n% 3D Run-Length features from combined run length matrix\ndirctn = 1;\nrlmType = 2;\nfeatureS.rlmFeat3DdirS = get_rlm(dirctn, rlmType, quantizedM, ...\n numGrLevels, numVoxels, rlmFlagS);\n\nrlmCombS = featureS.rlmFeat3DdirS.AvgS;\ncerrRlmV = [rlmCombS.gln, rlmCombS.glnNorm, rlmCombS.glv, rlmCombS.hglre, rlmCombS.lglre, rlmCombS.lre, rlmCombS.lrhgle, ...\n rlmCombS.lrlgle, rlmCombS.rln, rlmCombS.rlnNorm, rlmCombS.rlv, rlmCombS.rp, ...\n rlmCombS.sre, rlmCombS.srhgle, rlmCombS.srlgle, rlmCombS.re];\n\npyradRlmNamC = {'GrayLevelNonUniformity', 'GrayLevelNonUniformityNormalized',...\n 'GrayLevelVariance', 'HighGrayLevelRunEmphasis', 'LowGrayLevelRunEmphasis', ...\n 'LongRunEmphasis', 'LongRunHighGrayLevelEmphasis', 'LongRunLowGrayLevelEmphasis',...\n 'RunLengthNonUniformity', 'RunLengthNonUniformityNormalized', 'RunVariance', ...\n 'RunPercentage', 'ShortRunEmphasis','ShortRunHighGrayLevelEmphasis', ...\n 'ShortRunLowGrayLevelEmphasis','RunEntropy'};\n\npyradRlmNamC = strcat([pyradScanType,'_glrlm_'],pyradRlmNamC);\npyRadRlmV = [];\nfor i = 1:length(pyradRlmNamC)\n if isfield(teststruct,pyradRlmNamC{i})\n pyRadRlmV(i) = teststruct.(pyradRlmNamC{i});\n else\n pyRadRlmV(i) = NaN;\n end\nend\n\nrlmDiffV = (cerrRlmV - pyRadRlmV) ./ cerrRlmV * 100\n\n\n\n%% Size Zone features in 3d\n\nflagS.sae = 1;\nflagS.lae = 1;\nflagS.gln = 1;\nflagS.glv = 1;\nflagS.szv = 1;\nflagS.glnNorm = 1;\nflagS.szn = 1;\nflagS.sznNorm = 1;\nflagS.zp = 1;\nflagS.lglze = 1;\nflagS.hglze = 1;\nflagS.salgle = 1;\nflagS.sahgle = 1;\nflagS.lalgle = 1;\nflagS.larhgle = 1;\nflagS.ze = 1;\n\nszmType = 1; % 1: 3d, 2: 2d\nszmM = calcSZM(quantizedM, numGrLevels, szmType);\nnumVoxels = sum(~isnan(quantizedM(:)));\nfeatureS.szmFeature3dS = szmToScalarFeatures(szmM,numVoxels, szmFlagS);\nszmS = featureS.szmFeature3dS;\n% cerrSzmV = [szmS.gln, szmS.glnNorm, szmS.glv, szmS.hglre, szmS.lglre, szmS.lre, szmS.lrhgle, ...\n% szmS.lrlgle, szmS.rln, szmS.rlnNorm, szmS.rlv, szmS.rp, ...\n% szmS.sre, szmS.srhgle, szmS.srlgle];\ncerrSzmV = [szmS.gln, szmS.glnNorm, szmS.glv, szmS.hglze, szmS.lglze, szmS.lae, szmS.lahgle, ...\n szmS.lalgle, szmS.szn, szmS.sznNorm, szmS.szv, szmS.zp, ...\n szmS.sae, szmS.sahgle, szmS.salgle, szmS.ze];\n\npyradSzmNamC = {'GrayLevelNonUniformity', 'GrayLevelNonUniformityNormalized',...\n 'GrayLevelVariance', 'HighGrayLevelZoneEmphasis', 'LowGrayLevelZoneEmphasis', ...\n 'LargeAreaEmphasis', 'LargeAreaHighGrayLevelEmphasis', 'LargeAreaLowGrayLevelEmphasis',...\n 'SizeZoneNonUniformity', 'SizeZoneNonUniformityNormalized', 'ZoneVariance', ...\n 'ZonePercentage', 'SmallAreaEmphasis','SmallAreaHighGrayLevelEmphasis', ...\n 'SmallAreaLowGrayLevelEmphasis','ZoneEntropy'};\n\npyradSzmNamC = strcat([pyradScanType,'_glszm_'],pyradSzmNamC);\npyRadSzmV = [];\nfor i = 1:length(pyradSzmNamC)\n if isfield(teststruct,pyradSzmNamC{i})\n pyRadSzmV(i) = teststruct.(pyradSzmNamC{i});\n else\n pyRadSzmV(i) = NaN;\n end\nend\nszmDiffV = (cerrSzmV - pyRadSzmV) ./ cerrSzmV * 100\n\n%% NGLDM features\n\npatchRadius3dV = paramS.higherOrderParamS.patchRadius3dV;\nimgDiffThresh = paramS.higherOrderParamS.imgDiffThresh;\n% 3d\nngldmM = calcNGLDM(quantizedM, patchRadius3dV, ...\n numGrLevels, imgDiffThresh);\nfeatureS.ngldmFeatures3dS = ngldmToScalarFeatures(ngldmM,numVoxels);\n\nngldmS = featureS.ngldmFeatures3dS;\ncerrNgldmV = [ngldmS.lde, ngldmS.hde, ngldmS.lgce, ngldmS.hgce, ...\n ngldmS.ldlge, ngldmS.ldhge, ngldmS.hdlge, ngldmS.hdhge, ...\n ngldmS.gln, ngldmS.glnNorm, ngldmS.dcn, ngldmS.dcnNorm,...\n ngldmS.dcp, ngldmS.glv, ngldmS.dcv, ngldmS.entropy, ngldmS.energy];\n\npyradNgldmNamC = {'SmallDependenceEmphasis', 'LargeDependenceEmphasis',...\n 'LowGrayLevelCountEmphasis', 'HighGrayLevelCountEmphasis', 'SmallDependenceLowGrayLevelEmphasis', ...\n 'SmallDependenceHighGrayLevelEmphasis', 'LargeDependenceLowGrayLevelEmphasis', ...\n 'LargeDependenceHighGrayLevelEmphasis', 'GrayLevelNonUniformity', 'GrayLevelNonUniformityNorm', ...\n 'DependenceNonUniformity', 'DependenceNonUniformityNormalized', ...\n 'DependencePercentage', 'GrayLevelVariance', 'DependenceVariance', ...\n 'DependenceEntropy', 'DependenceEnergy'};\n\npyradNgldmNamC = strcat([pyradScanType,'_gldm_'],pyradNgldmNamC);\npyRadNgldmV = [];\nfor i = 1:length(pyradNgldmNamC)\n if isfield(teststruct,pyradNgldmNamC{i})\n pyRadNgldmV(i) = teststruct.(pyradNgldmNamC{i});\n else\n pyRadNgldmV(i) = NaN;\n end\nend\n\nngldmDiffV = (cerrNgldmV - pyRadNgldmV) ./ cerrNgldmV * 100\n\n\n\n%% NGTDM features\nnumGrLevels = paramS.higherOrderParamS.numGrLevels;\npatchRadius3dV = paramS.higherOrderParamS.patchRadius3dV;\n% 3d\n[s,p] = calcNGTDM(quantizedM, patchRadius3dV, numGrLevels);\nfeatureS.ngtdmFeatures3dS = ngtdmToScalarFeatures(s,p,numVoxels);\n\nngtdmS = featureS.ngtdmFeatures3dS;\ncerrNgtdmV = [ngtdmS.busyness ngtdmS.coarseness ngtdmS.complexity ngtdmS.contrast ngtdmS.strength];\n\n\n\n ", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/Unit_Testing/tests_for_cerr/testRadiomicsFeaturesWithPyRadiomics.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6513548646660542, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.30534905516285177}} {"text": "function [y]=tt_mvk4(A, x, tol, varargin)\n\n% step_dpow = 0.1; % stepsize for d-power in truncations\n% min_dpow = 1; % Minimal d-power for truncation\n%\n% bot_conv = 0.1; % bottom convergence factor - if better, we can decrease dpow and drank\n% top_conv = 0.99; % top convergence factor - if worse, we have to increase dpow and drank\n\n\nnswp=10;\n\nals_tol_low = 5;\nals_iters = 4;\n\nrmax=1000;\n\nverb=1;\nkickrank = 10;\n kicktype = 'mr';\n% kicktype = 'rand';\n\n% pcatype = 'svd';\npcatype = 'uchol';\n\ny=[];\nblock_order = [];\n\nfor i=1:2:length(varargin)-1\n switch lower(varargin{i})\n case 'nswp'\n nswp=varargin{i+1};\n case 'rmax'\n rmax=varargin{i+1};\n case 'kicktype'\n kicktype=lower(varargin{i+1});\n case 'pcatype'\n pcatype=lower(varargin{i+1}); \n case 'y0'\n y=varargin{i+1};\n case 'verb'\n verb=varargin{i+1};\n case 'kickrank'\n kickrank=varargin{i+1};\n case 'step_dpow'\n step_dpow=varargin{i+1};\n case 'min_dpow'\n min_dpow=varargin{i+1};\n case 'bot_conv'\n bot_conv=varargin{i+1};\n case 'top_conv'\n top_conv=varargin{i+1};\n case 'block_order'\n block_order=varargin{i+1};\n case 'als_tol_low'\n als_tol_low=varargin{i+1};\n case 'als_iters'\n als_iters=varargin{i+1};\n\n otherwise\n error('Unrecognized option: %s\\n',varargin{i});\n end\nend\n\nrx = x.r;\nd = x.d;\ntailranks = [false,false];\nif (rx(1)~=1)\n e1 = tt_tensor;\n e1.d=1;\n e1.n = [rx(1)];\n e1.r = [1; rx(1)];\n e1.ps = [1; rx(1)^2+1];\n e1.core = reshape(eye(rx(1)), rx(1)^2, 1);\n x = kron(e1, x);\n \n A = kron(tt_matrix(eye(rx(1))), A);\n tailranks(1)=true;\nend;\nif (rx(d+1)~=1)\n e1 = tt_tensor;\n e1.d=1;\n e1.n = [rx(d+1)];\n e1.r = [rx(d+1); 1];\n e1.ps = [1; rx(d+1)^2+1];\n e1.core = reshape(eye(rx(d+1)), rx(d+1)^2, 1);\n x = kron(x, e1);\n \n A = kron(A, tt_matrix(eye(rx(d+1))));\n tailranks(2)=true;\nend;\n\nd = x.d;\nrx = x.r;\nra = A.r;\nn = A.n;\nm = A.m;\nif (isempty(y))\n% y = tt_rand(n, A.d, kickrank);\n y = tt_ones(n, A.d);\nend;\n\nif (isempty(block_order))\n block_order = [+(d), -(d)];\nend;\n\nry = y.r;\n\ncry = core2cell(y);\ncrA = core2cell(A);\ncrx = core2cell(x);\n\nphia = cell(d+1,1); phia{1}=1; phia{d+1}=1;\n\n\n% Orthogonalization\nfor i=d:-1:2\n cr = cry{i};\n cr = reshape(cr, ry(i), n(i)*ry(i+1));\n [cr, rv]=qr(cr.', 0);\n cr2 = cry{i-1};\n cr2 = reshape(cr2, ry(i-1)*n(i-1), ry(i));\n cr2 = cr2*(rv.');\n ry(i) = size(cr, 2);\n cr = reshape(cr.', ry(i), n(i), ry(i+1));\n% psy(i) = psy(i+1)-ry(i)*n(i)*ry(i+1);\n% cry(psy(i):(psy(i+1)-1))=cr(:);\n% psyo(i) = psyo(i-1)+ry(i-1)*n(i-1)*ry(i);\n% cry(psyo(i-1):(psyo(i)-1)) = cr2(:);\n cry{i-1} = reshape(cr2, ry(i-1), n(i-1), ry(i));\n cry{i} = cr;\n\n phia{i} = compute_next_Phi(phia{i+1}, cr, crA{i}, crx{i}, 'rl');\n% phia{i} = compute_next_Phi(phia{i+1}, cr, reshape(cra(psa(i):(psa(i+1)-1)), ra(i), n(i), n(i), ra(i+1)), reshape(crx(psx(i):(psx(i+1)-1)), rx(i), n(i), rx(i+1)), 'rl');\n\nend;\n% cry = cry(psy(1):(psy(d+1)-1));\n\nlast_sweep = false;\nswp = 1;\ni = 1;\n\n% dy_old = ones(d,1);\ndy = zeros(d,1);\nmax_dy = 0;\n% For extra-rank addition\n% dpows = ones(d,1)*min_dpow;\n% dranks = zeros(d,1);\n\ncur_order = block_order;\norder_index = 1;\ndir = sign(cur_order(order_index));\n\n% DMRG sweeps\nwhile (swp<=nswp)\n\n % Extract elements - matrix\n Phi1 = phia{i}; Phi2 = phia{i+1};\n% A1 = reshape(cra(psa(i):(psa(i+1)-1)), ra(i), n(i), n(i), ra(i+1));\n% x1 = reshape(crx(psx(i):(psx(i+1)-1)), rx(i), n(i), rx(i+1));\n x1 = crx{i};\n A1 = crA{i};\n\n newy = reshape(Phi1, ry(i)*ra(i), rx(i));\n newy = newy*reshape(x1, rx(i), m(i)*rx(i+1));\n newy = reshape(newy, ry(i), ra(i)*m(i), rx(i+1));\n newy = permute(newy, [2, 1, 3]);\n newy = reshape(newy, ra(i)*m(i), ry(i)*rx(i+1));\n A1 = permute(A1, [2, 4, 1, 3]);\n A1 = reshape(A1, n(i)*ra(i+1), ra(i)*m(i));\n newy = A1*newy;\n newy = reshape(newy, n(i), ra(i+1), ry(i), rx(i+1));\n newy = permute(newy, [3, 1, 2, 4]);\n newy = reshape(newy, ry(i)*n(i), ra(i+1)*rx(i+1));\n if (dir>0)&&(strcmp(kicktype, 'mr'))\n newy_save = newy;\n end;\n newy = newy*(reshape(Phi2, ry(i+1), ra(i+1)*rx(i+1)).');\n newy = reshape(newy, ry(i)*n(i)*ry(i+1), 1);\n\n oldy = reshape(cry{i}, ry(i)*n(i)*ry(i+1), 1);\n\n dy(i) = norm(newy-oldy)/norm(newy);\n max_dy = max(max_dy, dy(i));\n%\n% % The new core does not converge - increase rank\n% if (dy(i)/dy_old(i)>top_conv)&&(dy(i)>tol)\n% dranks(i)=dranks(i)+1;\n% dpows(i)=dpows(i)+step_dpow;\n% end;\n% % The new core converges well - try to decrease rank\n% if (dy(i)/dy_old(i)0) % left-to-right\n newy = reshape(newy, ry(i)*n(i), ry(i+1));\n else\n newy = reshape(newy, ry(i), n(i)*ry(i+1));\n end;\n\n if (kickrank>=0)\n [u,s,v]=svd(newy, 'econ');\n s = diag(s);\n r = my_chop2(s, tol/sqrt(d)*norm(s));\n% % Artificial rank increasing\n% r = r+dranks(i);\n r = min(r, numel(s));\n r = min(r, rmax);\n else\n if (dir>0)\n [u,v]=qr(newy, 0);\n v=v';\n r = size(u,2);\n s = ones(r,1);\n else\n [v,u]=qr(newy.', 0);\n v=conj(v);\n u=u.';\n r = size(u,2);\n s = ones(r,1);\n end;\n end;\n\n if (verb>1)\n\tfprintf('=mvk4= block %d{%d}, dy: %3.3e, r: %d\\n', i, dir, dy(i), r);\n% elseif (verb>0)\n% fprintf(' \\r')\n% fprintf('=mvk4= block %d{%d}, dy: %3.3e, r: %d\\r', i, dir, dy(i), r);\n end;\n\n if (dir>0)&&(i0)\n% newy = reshape(Phi1, ry(i)*ra(i), rx(i));\n% newy = newy*reshape(crx{i}, rx(i), n(i)*rx(i+1));\n% newy = reshape(newy, ry(i), ra(i)*n(i), rx(i+1));\n% newy = permute(newy, [2, 1, 3]);\n% newy = reshape(newy, ra(i)*n(i), ry(i)*rx(i+1));\n% A1 = permute(crA{i}, [2, 4, 1, 3]);\n% A1 = reshape(A1, n(i)*ra(i+1), ra(i)*n(i));\n% newy = A1*newy;\n% newy = reshape(newy, n(i), ra(i+1), ry(i), rx(i+1));\n% newy = permute(newy, [3, 1, 2, 4]);\n% newy = reshape(newy, ry(i)*n(i), ra(i+1)*rx(i+1));\n if (strcmp(kicktype, 'mr'))\n leftresid = [reshape(u*v', ry(i)*n(i), ry(i+1)), -newy_save];\n if (strcmp(pcatype, 'svd'))\n [uk,sk,vk]=svd(leftresid, 'econ');\n uk = uk(:,1:min(kickrank, size(uk,2)));\n else\n uk = uchol(leftresid.', kickrank*2);\n uk = uk(:,size(uk,2):-1:max(size(uk,2)-kickrank+1,1));\n end;\n\n% if (i+10) % update phi\n% addbas = reshape(newbas2(:, ry(i+1)+1), ry(i), n(i), 1);\n% newphia = zeros(ry(i+1)+1, ra(i+1), rx(i+1));\n% newphia(1:ry(i+1),:,:)=phia{i+1};\n% newphia(ry(i+1)+1,:,:) = compute_next_Phi(phia{i}, addbas, A{i}, x{i}, 'lr');\n% phia{i+1} = newphia;\n% end;\n% end;\n%\n% Rr = [1;1];\n% for j=d:-1:i+2\n% addbas = rescomp{i};\n% addbas = addbas/norm(addbas);\n% newbas = zeros(ry(i)+1, n(i), ry(i+1)+1);\n% newbas(1:ry(i), :, 1:ry(i+1))=y{i};\n% newbas(ry(i)+1, :, ry(i+1)+1)=addbas;\n% newbas = reshape(newbas, (ry(i)+1)*n(i), (ry(i+1)+1));\n% newbas = newbas*Rr;\n% ry(i+1) = size(Rr, 2);\n% newbas = reshape(newbas, ry(i)+1, n(i)*ry(i+1));\n% newbas = newbas.';\n% % We have to orthogonalize it. approximately, if j0) % update phi\n% addbas = reshape(newbas2(:, ry(i)+1).', 1, n(i), ry(i+1));\n% newphia = zeros(ry(i)+1, ra(i), rx(i));\n% newphia(1:ry(i),:,:)=phia{i};\n% newphia(ry(i)+1,:,:) = compute_next_Phi(phia{i+1}, addbas, A{i}, x{i}, 'lr');\n% phia{i} = newphia;\n% end;\n% end;\n\n u = reshape(u, ry(i), n(i), r);\n v = reshape(v, r, n(i+1), ry(i+2));\n\n % Recompute phi. Left ones, so permute them appropriately\n phia{i+1} = compute_next_Phi(phia{i}, u, crA{i}, crx{i}, 'lr');\n\n % Stuff back\n\n cry{i} = u;\n cry{i+1} = v;\n elseif (dir<0)&&(i>1) % right-to-left\n u = u(:,1:r)*diag(s(1:r));\n v = conj(v(:,1:r));\n % kick\n radd = 0; rv = 1;\n% if (~last_sweep)&&(strcmp(kicktype, 'rand'))&&(kickrank>0)\n% % newy = reshape(Phi2, ry(i+1)*ra(i+1), rx(i+1));\n% % newy = newy*reshape(crx{i}, rx(i)*n(i), rx(i+1)).';\n% % newy = reshape(newy, ry(i+1), ra(i+1), rx(i), n(i));\n% % newy = permute(newy, [2, 4, 1, 3]);\n% % newy = reshape(newy, ra(i+1)*n(i), ry(i+1)*rx(i));\n% % A1 = permute(crA{i}, [1, 2, 4, 3]);\n% % A1 = reshape(A1, ra(i)*n(i), ra(i+1)*n(i));\n% % newy = A1*newy;\n% % newy = reshape(newy, ra(i), n(i), ry(i+1), rx(i));\n% % newy = permute(newy, [1, 4, 2, 3]);\n% % newy = reshape(newy, ra(i)*rx(i), n(i)*ry(i+1));\n% % resid = [reshape(u*v', ry(i), n(i)*ry(i+1)); -newy];\n% % uk = uchol(resid, kickrank+1);\n% % uk = uk(:,end:-1:max(end-kickrank+1,1));\n% uk = randn(n(i)*ry(i+1), kickrank);\n% [v,rv]=qr([v,uk], 0);\n% radd = size(uk,2);\n% % v = reort(v, uk);\n% end;\n\n% % radd = size(v, 2)+size(uk,2)-r;\n u = [u, zeros(ry(i), radd)];\n u = u*(rv.');\n cr2 = cry{i-1};\n cr2 = reshape(cr2, ry(i-1)*n(i-1), ry(i));\n u = cr2*u;\n\n% r = r+radd;\n r = size(v,2);\n\n u = reshape(u, ry(i-1), n(i-1), r);\n v = reshape(v.', r, n(i), ry(i+1));\n\n % Recompute phi. Here are right phis\n phia{i} = compute_next_Phi(phia{i+1}, v, crA{i}, crx{i}, 'rl');\n\n % Stuff back\n ry(i) = r;\n cry{i-1} = u;\n cry{i} = v;\n elseif ((dir>0)&&(i==d))||((dir<0)&&(i==1))\n % Just stuff back the last core\n newy = u(:,1:r)*diag(s(1:r))*(v(:,1:r)');\n newy = reshape(newy, ry(i), n(i), ry(i+1));\n cry{i} = newy;\n end;\n\n\n i = i+dir;\n\n % Reversing, residue check, etc\n cur_order(order_index) = cur_order(order_index) - dir;\n % New direction\n if (cur_order(order_index)==0)\n order_index = order_index+1;\n\n if (verb>0)\n% \t fprintf(' \\r')\n fprintf('=mvk4= sweep %d{%d}, max_dy: %3.3e, erank: %g\\n', swp, order_index-1, max_dy, sqrt(ry(1:d)'*(n.*ry(2:d+1))/sum(n)));\n end;\n\n if (last_sweep)\n break;\n end;\n\n if (kickrank<0)\n kickrank=kickrank-1;\n end;\n\n if (max_dy=0)\n kickrank=-1;\n end;\n\n if (max_dynumel(cur_order)) % New global sweep\n cur_order = block_order;\n order_index = 1;\n %residue\n if (last_sweep)\n cur_order = d-1;\n end;\n\n max_dy = 0;\n\n% dy_old = dy;\n swp = swp+1;\n end;\n\n dir = sign(cur_order(order_index));\n i = i+dir;\n end;\nend\n\nif (tailranks(1))\n cry{2} = reshape(cry{1}, n(1), ry(2))*reshape(cry{2}, ry(2), n(2)*ry(3));\n cry{2} = reshape(cry{2}, n(1), n(2), ry(3)); \nend;\nif (tailranks(2))\n cry{d-1} = reshape(cry{d-1}, ry(d-1)*n(d-1), ry(d))*reshape(cry{d}, ry(d), n(d));\n cry{d-1} = reshape(cry{d-1}, ry(d-1), n(d-1), n(d));\n cry = cry(1:d-1);\nend;\nif (tailranks(1))\n cry = cry(2:end);\nend;\ny = cell2core(y, cry);\n\nend\n\n\nfunction [Phi] = compute_next_Phi(Phi_prev, x, A, y, direction)\n% Performs the recurrent Phi (or Psi) matrix computation\n% Phi = Phi_prev * (x'Ay).\n% If direction is 'lr', computes Psi\n% if direction is 'rl', computes Phi\n% A can be empty, then only x'y is computed.\n\nif (strcmp(direction, 'rl'))\n % Revert ranks to perform the right-to-left recursion\n x = permute(x, [3, 2, 1]);\n y = permute(y, [3, 2, 1]);\n if (~isempty(A))\n A = permute(A, [4, 2, 3, 1]);\n end\nend\n\nrx1 = size(x,1); n = size(x,2); rx2 = size(x,3);\nry1 = size(y,1); m = size(y,2); ry2 = size(y,3);\nif (~isempty(A))\n ra1 = size(A,1); ra2 = size(A,4);\nelse\n ra1 = 1; ra2 = 1;\nend\n\nPhi = reshape(Phi_prev, [rx1*ra1, ry1]);\ny = reshape(y, [ry1, m*ry2]);\nPhi = Phi*y;\t% complexity §\\mcommentfont$\\mathcal{O}(n r_x r_A r_y^2)$§\nPhi = reshape(Phi, [rx1, ra1, m, ry2]);\nPhi = permute(Phi, [2, 3, 1, 4]);\nif (~isempty(A))\n Phi = reshape(Phi, [ra1*m, rx1*ry2]);\n A = permute(A, [4, 2, 1, 3]);\n A = reshape(A, [ra2*n, ra1*m]);\n Phi = A*Phi;\t% complexity §\\mcommentfont$\\mathcal{O}(n^2 r_x r_A^2 r_y)$§\n Phi = reshape(Phi, [ra2, n, rx1, ry2]);\nend\nPhi = permute(Phi, [3, 2, 1, 4]);\nPhi = reshape(Phi, [rx1*n, ra2*ry2]);\nx = reshape(x, [rx1*n, rx2]);\nPhi = (x')*Phi;\t% complexity §\\mcommentfont$\\mathcal{O}(n r_x^2 r_A r_y)$§\nif (~isempty(A))\n Phi = reshape(Phi, [rx2, ra2, ry2]);\nend\nend\n", "meta": {"author": "oseledets", "repo": "TT-Toolbox", "sha": "1b87616b1e84de89699697fe196eba814aabe954", "save_path": "github-repos/MATLAB/oseledets-TT-Toolbox", "path": "github-repos/MATLAB/oseledets-TT-Toolbox/TT-Toolbox-1b87616b1e84de89699697fe196eba814aabe954/core/tt_mvk4.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.30515755237751024}} {"text": "classdef prtClassRvmSequential < prtClassRvm\n % prtClassRvmSequential Relevance vector machine classifier using sequential training\n % \n % CLASSIFIER = prtClassRvmSequential returns a relevance vector\n % machine classifier based using sequential training.\n %\n % CLASSIFIER = prtClassRvmSequential(PROPERTY1, VALUE1, ...)\n % constructs a prtClassRvmSequential object CLASSIFIER with properties as\n % specified by PROPERTY/VALUE pairs.\n %\n % A prtClassRvmSequential object inherits all properties from the abstract class\n % prtClass. In addition is has the following properties:\n %\n % kernels - A cell array of prtKernel objects specifying\n % the kernels to use\n % verbosePlot - Flag indicating whether or not to plot during\n % training\n % verboseText - Flag indicating whether or not to output\n % verbose updates during training\n % learningMaxIterations - The maximum number of iterations\n %\n % A prtClassRvmSequential also has the following read-only properties:\n %\n % learningConverged - Flag indicating if the training converged\n % beta - The regression weights, estimated during training\n % sparseBeta - The sparse regression weights, estimated during\n % training\n % sparseKernels - The sparse regression kernels, estimated during\n % training\n %\n % For more information on the algorithm and the above properties, see\n % the following reference:\n %\n % Tipping, M. E. and A. C. Faul (2003). Fast marginal likelihood\n % maximisation for sparse Bayesian models. In C. M. Bishop and B. J.\n % Frey (Eds.), Proceedings of the Ninth International Workshop on\n % Artificial Intelligence and Statistics, Key West, FL, Jan 3-6.\n %\n % prtClassRvmSequential is most useful for datasets with a large\n % number of observations for which the gram matrix can not be held in\n % memory. The sequential RVM training algorithm is capable of\n % operating by generating necessary portions of the gram matrix when\n % needed. The size of the generated portion of the gram matrix is\n % determined by the property, largestNumberOfGramColumns. Sequential\n % RVM training will attempt to generate portions of the gram matrix\n % that are TraingData.nObservations x largesNumberofGramColums in\n % size. If the entire gram matrix is this size or smaller it need\n % only be generated once. Therefore if the entire gram matrix can be\n % stored in memory, training is much faster. For quickest operation,\n % largestNumberOfGramColumns should be set as large as possible\n % without exceeding RAM limitations.\n %\n % Example:\n %\n % TestDataSet = prtDataGenUnimodal; % Create some test and\n % TrainingDataSet = prtDataGenUnimodal; % training data classifier\n % classifier = prtClassRvmSequential('verbosePlot',true); % Create a classifier\n % classifier = classifier.train(TrainingDataSet); % Train\n % classified = run(classifier, TestDataSet); % Test\n % % Plot\n % subplot(2,1,1); classifier.plot;\n % subplot(2,1,2); [pf,pd] = prtScoreRoc(classified,TestDataSet);\n % h = plot(pf,pd,'linewidth',3);\n % title('ROC'); xlabel('Pf'); ylabel('Pd');\n %\n % See also prtClass, prtClassRvm, prtClassRvnFiguerido,\n % prtRegressRvmSequential\n\n\n\n\n\n properties\n\n learningPoorlyScaledLikelihoodThreshold = 1e4;\n learningLikelihoodIncreaseThreshold = 1e-6;\n largestNumberOfGramColumns = 5000;\n learningCorrelationRemovalThreshold = 0.99;\n learningFactorRemove = true; % Remove kernels during train?\n learningRepeatedActionLimit = 25;\n end\n \n properties(Hidden = true)\n learningResults\n end\n \n properties (Hidden = true)\n Sigma = [];\n end\n \n methods\n function Obj = prtClassRvmSequential(varargin)\n Obj = prtUtilAssignStringValuePairs(Obj,varargin{:});\n end\n \n function Obj = set.learningPoorlyScaledLikelihoodThreshold(Obj,val)\n assert(prtUtilIsPositiveScalar(val),'prt:prtClassRvmSequential:learningPoorlyScaledLikelihoodThreshold','learningPoorlyScaledLikelihoodThreshold must be a positive scalar');\n Obj.learningPoorlyScaledLikelihoodThreshold = val;\n end\n function Obj = set.learningLikelihoodIncreaseThreshold(Obj,val)\n assert(prtUtilIsPositiveScalar(val),'prt:prtClassRvmSequential:learningLikelihoodIncreaseThreshold','learningLikelihoodIncreaseThreshold must be a positive scalar');\n Obj.learningLikelihoodIncreaseThreshold = val;\n end\n function Obj = set.largestNumberOfGramColumns(Obj,val)\n assert(prtUtilIsPositiveScalarInteger(val),'prt:prtClassRvmSequential:largestNumberOfGramColumns','largestNumberOfGramColumns must be a positive integer scalar');\n Obj.largestNumberOfGramColumns = val;\n end\n function Obj = set.learningCorrelationRemovalThreshold(Obj,val)\n assert(prtUtilIsPositiveScalar(val),'prt:prtClassRvmSequential:learningCorrelationRemovalThreshold','learningCorrelationRemovalThreshold must be a positive scalar');\n Obj.learningCorrelationRemovalThreshold = val;\n end\n function Obj = set.learningFactorRemove(Obj,val)\n assert(prtUtilIsLogicalScalar(val),'prt:prtClassRvmSequential:learningFactorRemove','learningFactorRemove must be a logical scalar');\n Obj.learningFactorRemove = val;\n end\n function Obj = set.learningRepeatedActionLimit(Obj,val)\n assert(prtUtilIsPositiveScalarInteger(val),'prt:prtClassRvmSequential:learningRepeatedActionLimit','learningRepeatedActionLimit must be a positive integer scalar');\n Obj.learningRepeatedActionLimit = val;\n end\n end\n \n methods (Access=protected, Hidden = true)\n function Obj = trainAction(Obj,DataSet)\n %Rvm = trainAction(Rvm,DataSet) (Private; see prtClass\\train)\n \n warningState = warning;\n %warning off MATLAB:nearlySingularMatrix\n \n y = Obj.getMinusOneOneTargets(DataSet);\n \n localKernels = Obj.kernels.train(DataSet);\n nBasis = localKernels.nDimensions;\n \n if false && nBasis <= Obj.largestNumberOfGramColumns\n Obj = trainActionSequentialInMemory(Obj, DataSet, y);\n return\n end\n \n if Obj.verboseText\n fprintf('Sequential RVM training with %d possible vectors.\\n', nBasis);\n end\n \n % The sometimes we want y [-1 1] but mostly not\n ym11 = y;\n y(y ==-1) = 0;\n \n Obj.beta = zeros(nBasis,1);\n \n relevantIndices = false(nBasis,1); % Nobody!\n alpha = inf(nBasis,1); % Nobody!\n forbidden = zeros(nBasis,1); % Will hold who is forbidding you from joining\n \n % Find first kernel\n kernelCorrs = zeros(nBasis,1);\n nBlocks = ceil(nBasis./ Obj.largestNumberOfGramColumns);\n for iBlock = 1:nBlocks\n cInds = ((iBlock-1)*Obj.largestNumberOfGramColumns+1):min([iBlock*Obj.largestNumberOfGramColumns nBasis]);\n \n trainedKernelDownSelected = localKernels.retainKernelDimensions(cInds);\n blockPhi = trainedKernelDownSelected.run_OutputDoubleArray(DataSet);\n blockPhiNormalized = bsxfun(@rdivide,blockPhi,sqrt(sum(blockPhi.*blockPhi))); % We have to normalize here\n \n kernelCorrs(cInds) = abs(blockPhiNormalized'*ym11);\n end\n [maxVal, maxInd] = max(kernelCorrs); %#ok\n \n \n % Make this ind relevant\n relevantIndices(maxInd) = true;\n selectedInds = maxInd;\n \n % Add things to forbidden list\n initLogical = false(nBasis,1);\n initLogical(maxInd) = true;\n firstKernel = localKernels.retainKernelDimensions(initLogical);\n firstPhiNormalized = firstKernel.run_OutputDoubleArray(DataSet);\n firstPhiNormalized = firstPhiNormalized - mean(firstPhiNormalized);\n firstPhiNormalized = firstPhiNormalized./sqrt(sum(firstPhiNormalized.^2));\n phiCorrs = zeros(nBasis,1);\n for iBlock = 1:nBlocks\n cInds = ((iBlock-1)*Obj.largestNumberOfGramColumns+1):min([iBlock*Obj.largestNumberOfGramColumns nBasis]);\n \n trainedKernelDownSelected = localKernels.retainKernelDimensions(cInds);\n if nBlocks > 1 % If there is only one block we can keep the one from before\n blockPhi = trainedKernelDownSelected.run_OutputDoubleArray(DataSet);\n end\n blockPhiDemeanedNormalized = bsxfun(@minus,blockPhi,mean(blockPhi));\n blockPhiDemeanedNormalized = bsxfun(@rdivide,blockPhiDemeanedNormalized,sqrt(sum(blockPhiDemeanedNormalized.*blockPhiDemeanedNormalized))); % We have to normalize here\n \n phiCorrs(cInds) = blockPhiDemeanedNormalized'*firstPhiNormalized;\n end\n forbidden(phiCorrs > Obj.learningCorrelationRemovalThreshold) = maxInd;\n \n % Start the actual Process\n if Obj.verboseText\n fprintf('\\t Iteration 0: Intialized with vector %d.\\n', maxInd);\n \n nVectorsStringLength = ceil(log10(length(nBasis)))+1;\n end\n \n if nBlocks == 1\n % If we have only 1 block we only need to do this once.\n trainedKernelDownSelected = localKernels.retainKernelDimensions(true(nBasis,1));\n PhiM = trainedKernelDownSelected.run_OutputDoubleArray(DataSet);\n end\n \n % Get the first relevant kernel matrix\n trainedKernelDownSelected = localKernels.retainKernelDimensions(relevantIndices);\n cPhi = trainedKernelDownSelected.run_OutputDoubleArray(DataSet);\n \n repeatedActionCounter = 0;\n for iteration = 1:Obj.learningMaxIterations\n \n % Store old log Alpha\n logAlphaOld = log(alpha);\n \n if iteration == 1\n % Initial estimates\n % Estimate Sigma, mu etc.\n \n logOut = (ym11*0.9+1)/2;\n mu = cPhi \\ log(logOut./(1-logOut));\n \n alpha(relevantIndices) = 1./mu.^2;\n \n % Laplacian approx. IRLS\n A = diag(alpha(relevantIndices));\n \n [mu, SigmaInvChol, obsNoiseVar] = prtUtilPenalizedIrls(y,cPhi,mu,A);\n \n SigmaChol = inv(SigmaInvChol);\n Obj.Sigma = SigmaChol*SigmaChol'; %#ok\n \n yHat = 1 ./ (1+exp(-cPhi*mu));\n end\n \n % Eval additions and subtractions\n Sm = zeros(nBasis,1);\n Qm = zeros(nBasis,1);\n cError = y-yHat;\n \n cPhiProduct = bsxfun(@times,cPhi,obsNoiseVar);\n for iBlock = 1:nBlocks\n cInds = ((iBlock-1)*Obj.largestNumberOfGramColumns+1):min([iBlock*Obj.largestNumberOfGramColumns nBasis]);\n \n\n if nBlocks > 1 % If there is only one block we can keep the on from before\n trainedKernelDownSelected = localKernels.retainKernelDimensions(cInds);\n PhiM = trainedKernelDownSelected.run_OutputDoubleArray(DataSet);\n end\n \n Sm(cInds) = (obsNoiseVar'*(PhiM.^2)).' - sum((PhiM.'*cPhiProduct*SigmaChol).^2,2);\n Qm(cInds) = PhiM.'*cError;\n end\n \n % Find little sm and qm (these are different for relevant vectors)\n sm = Sm;\n qm = Qm;\n \n cDenom = (alpha(relevantIndices)-Sm(relevantIndices));\n sm(relevantIndices) = alpha(relevantIndices) .* Sm(relevantIndices) ./ cDenom;\n qm(relevantIndices) = alpha(relevantIndices) .* Qm(relevantIndices) ./ cDenom;\n \n theta = qm.^2 - sm;\n cantBeRelevent = theta < 0;\n \n % Addition\n addLogLikelihoodChanges = 0.5*( theta./Sm + log(Sm ./ Qm.^2) ); % Eq (27)\n addLogLikelihoodChanges(cantBeRelevent) = 0; % Can't add things that are disallowed by theta\n addLogLikelihoodChanges(relevantIndices) = 0; % Can't add things already in\n addLogLikelihoodChanges(forbidden > 0) = 0; % Can't add things that are forbidden\n \n % Removal\n removeLogLikelihoodChanges = -0.5*( qm.^2./(sm + alpha) - log(1 + sm./alpha) ); % Eq (37) (I think this is wrong in the paper. The one in the paper uses Si and Qi, I got this based on si and qi (or S and Q in their code), from corrected from analyzing code from http://www.vectoranomaly.com/downloads/downloads.htm)\n removeLogLikelihoodChanges(~relevantIndices) = 0; % Can't remove things not in\n removeLogLikelihoodChanges(imag(removeLogLikelihoodChanges) > 0) = inf;\n \n % Modify\n updatedAlpha = sm.^2 ./ theta;\n updatedAlphaDiff = 1./updatedAlpha - 1./alpha;\n modifyLogLikelihoodChanges = 0.5*( updatedAlphaDiff.*(Qm.^2) ./ (updatedAlphaDiff.*Sm + 1) - log(1 + Sm.*updatedAlphaDiff) );\n \n modifyLogLikelihoodChanges(~relevantIndices) = 0; % Can't modify things not in\n modifyLogLikelihoodChanges(cantBeRelevent) = 0; % Can't modify things that technically shouldn't be in (they would get dropped)\n \n \n [addChange, bestAddInd] = max(addLogLikelihoodChanges);\n [remChange, bestRemInd] = max(removeLogLikelihoodChanges);\n [modChange, bestModInd] = max(modifyLogLikelihoodChanges);\n \n if iteration == 1\n % On the first iteration we don't allow removal\n [maxChangeVal, actionInd] = max([addChange, nan, modChange]);\n else\n if remChange > 0 && Obj.learningFactorRemove\n % Removing is top priority.\n % If removing increases the likelihood, we have two\n % options, actually remove that sample or modify that\n % sample if that is better\n [maxChangeVal, actionInd] = max([nan remChange, modifyLogLikelihoodChanges(bestRemInd)]);\n else\n % Not going to remove, so we would be allowed to modify\n [maxChangeVal, actionInd] = max([addChange, remChange, modChange]);\n end\n end\n \n if maxChangeVal > Obj.learningPoorlyScaledLikelihoodThreshold\n warning('prtClassRvm:BadKernelMatrix','Kernel matrix is poorly conditioned. Consider modifying your kernels. Optimization Exiting...' );\n break\n end\n \n if maxChangeVal < Obj.learningLikelihoodIncreaseThreshold\n % There are no good options right now. Therefore we\n % should exit with the previous iteration stats.\n Obj.learningConverged = true;\n Obj.learningResults.exitReason = 'No Good Actions';\n Obj.learningResults.exitValue = maxChangeVal;\n if Obj.verboseText\n fprintf('Convergence criterion met, no necessary actions remaining, maximal change in log-likelihood %g\\n\\n',maxChangeVal);\n end\n \n break;\n end\n \n switch actionInd\n case 1\n cBestInd = bestAddInd;\n case 2\n cBestInd = bestRemInd;\n case 3\n cBestInd = bestModInd;\n end\n if iteration > 1 && lastAction == actionInd && cBestInd == lastInd\n repeatedActionCounter = repeatedActionCounter + 1;\n else\n repeatedActionCounter = 0;\n end\n \n if repeatedActionCounter >= Obj.learningRepeatedActionLimit\n if Obj.verboseText\n fprintf('Exiting... repeating action limit has been reached.\\n\\n');\n end\n return\n end\n \n if Obj.verboseText\n actionStrings = {sprintf('Addition: Vector %s has been added. ', sprintf(sprintf('%%%dd',nVectorsStringLength),bestAddInd));\n sprintf('Removal: Vector %s has been removed.', sprintf(sprintf('%%%dd',nVectorsStringLength), bestRemInd));\n sprintf('Update: Vector %s has been updated.', sprintf(sprintf('%%%dd',nVectorsStringLength), bestModInd));};\n fprintf('\\t Iteration %d: %s Change in log-likelihood %g.\\n',iteration, actionStrings{actionInd}, maxChangeVal);\n end\n \n lastAction = actionInd;\n switch actionInd\n case 1 % Add\n \n relevantIndices(bestAddInd) = true;\n selectedInds = cat(1,selectedInds,bestAddInd);\n \n alpha(bestAddInd) = updatedAlpha(bestAddInd);\n % Modify Mu\n % (Penalized IRLS will fix it soon but we need good initialization)\n \n trainedKernelDownSelected = localKernels.retainKernelDimensions(bestAddInd);\n newPhi = trainedKernelDownSelected.run_OutputDoubleArray(DataSet);\n \n cFactor = (Obj.Sigma*(cPhi)'*(newPhi.*obsNoiseVar));\n Sigmaii = 1./(updatedAlpha(bestAddInd) + Sm(bestAddInd));\n newMu = Sigmaii*Qm(bestAddInd);\n \n updatedOldMu = mu - newMu*cFactor;\n sortedSelected = sort(selectedInds);\n newMuLocation = find(sortedSelected==bestAddInd);\n \n mu = zeros(length(mu)+1,1);\n mu(setdiff(1:length(mu),newMuLocation)) = updatedOldMu;\n mu(newMuLocation) = newMu;\n \n \n % Add things to forbidden list\n newPhiDemeanedNormalized = newPhi - mean(newPhi);\n newPhiDemeanedNormalized = newPhiDemeanedNormalized./sqrt(sum(newPhiDemeanedNormalized.^2));\n phiCorrs = zeros(nBasis,1);\n for iBlock = 1:nBlocks\n cInds = ((iBlock-1)*Obj.largestNumberOfGramColumns+1):min([iBlock*Obj.largestNumberOfGramColumns nBasis]);\n \n if nBlocks > 1\n trainedKernelDownSelected = localKernels.retainKernelDimensions(cInds);\n blockPhiDemeanedNormalized = trainedKernelDownSelected.run_OutputDoubleArray(DataSet);\n \n blockPhiDemeanedNormalized = bsxfun(@minus,blockPhiDemeanedNormalized,mean(blockPhiDemeanedNormalized));\n blockPhiDemeanedNormalized = bsxfun(@rdivide,blockPhiDemeanedNormalized,sqrt(sum(blockPhiDemeanedNormalized.*blockPhiDemeanedNormalized))); % We have to normalize here\n \n %else we have this from before\n end\n \n phiCorrs(cInds) = blockPhiDemeanedNormalized'*newPhiDemeanedNormalized;\n end\n forbidden(phiCorrs > Obj.learningCorrelationRemovalThreshold) = bestAddInd;\n \n lastInd = bestAddInd;\n case 2 % Remove\n \n removingInd = sort(selectedInds)==bestRemInd;\n \n mu = mu + mu(removingInd) .* Obj.Sigma(:,removingInd) ./ Obj.Sigma(removingInd,removingInd);\n mu(removingInd) = [];\n \n relevantIndices(bestRemInd) = false;\n selectedInds(selectedInds==bestRemInd) = [];\n alpha(bestRemInd) = inf;\n \n % Anything this guy said is forbidden is now\n % allowed.\n forbidden(forbidden == bestRemInd) = 0;\n \n lastInd = bestRemInd;\n \n case 3 % Modify\n modifyInd = sort(selectedInds)==bestModInd;\n \n alphaChangeInv = 1/(updatedAlpha(bestModInd) - alpha(bestModInd));\n kappa = 1/(Obj.Sigma(modifyInd,modifyInd) + alphaChangeInv);\n mu = mu - mu(modifyInd)*kappa*Obj.Sigma(:,modifyInd);\n \n alpha(bestModInd) = updatedAlpha(bestModInd);\n \n lastInd = bestModInd;\n end\n \n % At this point relevantIndices and alpha have changes.\n % Now we re-estimate Sigma, mu, and sigma2\n if nBlocks > 1\n trainedKernelDownSelected = localKernels.retainKernelDimensions(relevantIndices);\n cPhi = trainedKernelDownSelected.run_OutputDoubleArray(DataSet);\n else\n cPhi = PhiM(:,relevantIndices);\n end\n \n % Laplacian approx. IRLS\n A = diag(alpha(relevantIndices));\n \n if isempty(cPhi)\n yHat = 0.5*ones(size(y));\n else\n [mu, SigmaInvChol, obsNoiseVar] = prtUtilPenalizedIrls(y,cPhi,mu,A);\n \n SigmaChol = inv(SigmaInvChol);\n Obj.Sigma = SigmaChol*SigmaChol'; %#ok\n \n yHat = 1 ./ (1+exp(-cPhi*mu)); % We use a logistic here. \n end\n \n % Store beta\n Obj.beta = zeros(nBasis,1);\n Obj.beta(relevantIndices) = mu;\n \n if ~mod(iteration,Obj.verbosePlot)\n if DataSet.nFeatures == 2\n Obj.verboseIterationPlot(DataSet,relevantIndices);\n elseif iteration == 1\n warning('prt:prtClassRvmSequential','Learning iteration plot can only be produced for training Datasets with 2 features');\n end\n end\n \n % Check tolerance\n changeVal = abs(log(alpha)-logAlphaOld);\n changeVal(isnan(changeVal)) = 0; % inf-inf = nan\n if all(changeVal < Obj.learningConvergedTolerance) && iteration > 1\n Obj.learningConverged = true;\n Obj.learningResults.exitReason = 'Alpha Not Changing';\n Obj.learningResults.exitValue = TOL;\n if Obj.verboseText\n fprintf('Exiting...Precisions no longer changing appreciably.\\n\\n');\n end\n break;\n end\n end\n \n if Obj.verboseText && iteration == Obj.learningMaxIterations\n fprintf('Exiting...Convergence not reached before the maximum allowed iterations was reached.\\n\\n');\n end\n \n % Make sparse represenation\n Obj.sparseBeta = Obj.beta(relevantIndices,1);\n Obj.sparseKernels = localKernels.retainKernelDimensions(relevantIndices);\n \n % Very bad training\n if isempty(Obj.sparseBeta)\n warning('prt:prtClassRvm:NoRelevantFeatures','No relevant features were found during training.');\n end\n \n % Reset warning\n warning(warningState);\n \n end\n end\nend\n", "meta": {"author": "covartech", "repo": "PRT", "sha": "4305e612af048e7dbf3d9392efc7436db125b1fc", "save_path": "github-repos/MATLAB/covartech-PRT", "path": "github-repos/MATLAB/covartech-PRT/PRT-4305e612af048e7dbf3d9392efc7436db125b1fc/class/prtClassRvmSequential.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6150878414043816, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.30514128270330126}} {"text": "function [units, data_description] = segtype2units(unitCode)\n %segtype2units retrieves unit and description based on the segtype code\n %'segtype' in antelope datasets indicate the natural units of the detector\n persistent codeKey\n if isempty(codeKey)\n codeKey = createCodeKey();\n end\n if codeKey.isKey(unitCode)\n details = codeKey(unitCode);\n units = details{1};\n data_description = details{2};\n else\n [units, data_description] = deal('null');\n end\n \n function SU = createCodeKey()\n %createSegUnits creates a map where SU(char) = {units, data_description}\n SU = containers.Map;\n SU('A') = {'nm / sec / sec','acceleration'};\n SU('B') = {'25 mw / m / m','UV (sunburn) index(NOAA)'};\n SU('D') = {'nm', 'displacement'};\n SU('H') = {'Pa','hydroacoustic'};\n SU('I') = {'Pa','infrasound'};\n SU('J') = {'watts','power (Joulses/sec) (UCSD)'};\n SU('K') = {'kPa','generic pressure (UCSB)'};\n SU('M') = {'mm','Wood-Anderson drum recorder'};\n SU('P') = {'mb','barometric pressure'};\n SU('R') = {'mm','rain fall (UCSD)'};\n SU('S') = {'nm / m','strain'};\n SU('T') = {'sec','time'};\n SU('V') = {'nm / sec','velocity'};\n SU('W') = {'watts / m / m', 'insolation'};\n SU('a') = {'deg', 'azimuth'};\n SU('b') = {'bits/ sec', 'bit rate'};\n SU('c') = {'counts', 'dimensionless integer'};\n SU('d') = {'m', 'depth or height (e.g., water)'};\n SU('f') = {'micromoles / sec / m /m', 'photoactive radiation flux'};\n SU('h') = {'pH','hydrogen ion concentration'};\n SU('i') = {'amp','electric curent'};\n SU('m') = {'bitmap','dimensionless bitmap'};\n SU('n') = {'nanoradians','angle (tilt)'};\n SU('o') = {'mg/l','diliution of oxygen (Mark VanScoy)'};\n SU('p') = {'percent','percentage'};\n SU('r') = {'in','rainfall (UCSD)'};\n SU('s') = {'m / sec', 'speed (e.g., wind)'};\n SU('t') = {'C','temperature'};\n SU('u') = {'microsiemens/cm','conductivity'};\n SU('v') = {'volts','electric potential'};\n SU('w') = {'rad / sec', 'rotation rate'};\n SU('-') = {'null','null'};\n end\nend\n ", "meta": {"author": "geoscience-community-codes", "repo": "GISMO", "sha": "a4eafca9d2ac85079253510005ef00aa9998d030", "save_path": "github-repos/MATLAB/geoscience-community-codes-GISMO", "path": "github-repos/MATLAB/geoscience-community-codes-GISMO/GISMO-a4eafca9d2ac85079253510005ef00aa9998d030/core/dev/+dataretrieval/@antelopesource/segtype2units.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.5312093733737562, "lm_q1q2_score": 0.304743347340902}} {"text": "function [model, metProduction, essentialRxnsForTasks, addedRxnsForTasks, deletedDeadEndRxns, deletedRxnsInINIT, taskReport]=getINITModel(refModel, tissue, celltype, hpaData, arrayData, metabolomicsData, taskFile, useScoresForTasks, printReport, taskStructure, params, paramsFT)\n% getINITModel_legacy\n% Generates a model using the INIT algorithm, based on proteomics and/or\n% transcriptomics and/or metabolomics and/or metabolic tasks. This is the original \n% implementation of tINIT, which is replaced by ftINIT.\n%\n% Input:\n% refModel a model structure. The model should be in the\n% closed form (no exchange reactions open). Import\n% using import(filename,false). If the model is not\n% loaded using importModel, it might be that there\n% is no \"unconstrained\" field. In that case,\n% manually add the field like:\n% model.unconstrained=false(numel(model.mets),1);\n% tissue tissue to score for. Should exist in either\n% hpaData.tissues or arrayData.tissues\n% celltype cell type to score for. Should exist in either\n% hpaData.celltypes or arrayData.celltypes for this\n% tissue (opt, default is to use the best values\n% among all the cell types for the tissue. Use [] if\n% you want to supply more arguments)\n% hpaData HPA data structure from parseHPA (opt if arrayData is\n% supplied, default [])\n% arrayData gene expression data structure (opt if hpaData is\n% supplied, default [])\n% genes cell array with the unique gene names\n% tissues cell array with the tissue names. The list may not be\n% unique, as there can be multiple cell types per tissue\n% celltypes cell array with the cell type names for each tissue\n% levels GENESxTISSUES array with the expression level for\n% each gene in each tissue/celltype. NaN should be\n% used when no measurement was performed\n% threshold a single value or a vector of gene expression \n% thresholds, above which genes are considered to be\n% \"expressed\". (opt, by default, the mean expression\n% levels of each gene across all tissues in arrayData\n% will be used as the threshold values)\n% singleCells binary value selecting whether to use the\n% single-cell algorithm to identify expressed genes.\n% If used, specify cell subpopulations in CELLTYPES\n% (opt, default [])\n% plotResults true if single cell probability distributions\n% should be plotted (opt, default = False)\n% metabolomicsData cell array with metabolite names that the model\n% should produce (opt, default [])\n% taskFile a task list in Excel format. See parseTaskList for\n% details (opt, default [])\n% useScoresForTasks true if the calculated reaction scored should be used as\n% weights in the fitting to tasks (opt, default true)\n% printReport true if a report should be printed to the screen\n% (opt, default true)\n% taskStructure task structure as from parseTaskList. Can be used\n% as an alternative way to define tasks when Excel\n% sheets are not suitable. Overrides taskFile (opt,\n% default [])\n% params parameter structure as used by getMILPParams. This is\n% for the INIT algorithm. For the the MILP problems\n% solved to fit tasks, see paramsFT (opt, default [])\n% paramsFT parameter structure as used by getMILPParams. This is\n% for the fitTasks step. For the INIT algorithm, see\n% params (opt, default [])\n%\n%\n% Output:\n% model the resulting model structure\n% metProduction array that indicates which of the\n% metabolites in metabolomicsData that could be\n% produced. Note that this is before the\n% gap-filling process to enable defined tasks. To\n% see which metabolites that can be produced in\n% the final model, use canProduce.\n% -2: metabolite name not found in model\n% -1: metabolite found, but it could not be produced\n% 1: metabolite could be produced\n% essentialRxnsForTasks cell array of the reactions which were\n% essential to perform the tasks\n% addedRxnsForTasks cell array of the reactions which were added in\n% order to perform the tasks\n% deletedDeadEndRxns cell array of reactions deleted because they\n% could not carry flux (INIT requires a\n% functional input model)\n% deletedRxnsInINIT cell array of the reactions which were deleted by\n% the INIT algorithm\n% taskReport structure with the results for each task\n% \tid cell array with the id of the task\n% description cell array with the description of the task\n% ok boolean array with true if the task was successful\n% essential cell array with cell arrays of essential\n% reactions for the task\n% gapfill cell array of cell arrays of reactions included\n% in the gap-filling for the task\n%\n% This is the main function for automatic reconstruction of models based\n% on the (t)INIT algorithm (PLoS Comput Biol. 2012;8(5):e1002518, \n% Mol Syst Biol. 2014;10:721). Not all settings are possible using this\n% function, and you may want to call the functions scoreModel, runINIT\n% and fitTasks individually instead.\n%\n% NOTE: Exchange metabolites should normally not be removed from the model\n% when using this approach, since checkTasks/fitTasks rely on putting specific\n% constraints for each task. The INIT algorithm will remove exchange metabolites\n% if any are present. Use importModel(file,false) to import a model with\n% exchange metabolites remaining.\n%\n% Usage: [model, metProduction, essentialRxnsForTasks, addedRxnsForTasks,...\n% deletedDeadEndRxns, deletedRxnsInINIT, taskReport]=...\n% getINITModel(refModel, tissue, celltype, hpaData, arrayData,...\n% metabolomicsData, taskFile, useScoresForTasks, printReport,...\n% taskStructure, params, paramsFT)\n\nif nargin<3\n celltype=[];\nelse\n celltype=char(celltype);\nend\nif nargin<4\n hpaData=[];\nend\nif nargin<5\n arrayData=[];\nend\nif nargin<6\n metabolomicsData=[];\nend\nif nargin<7\n taskFile=[];\nelse\n taskFile=char(taskFile);\nend\nif nargin<8 || isempty(useScoresForTasks)\n useScoresForTasks=true;\nend\nif nargin<9 || isempty(printReport)\n printReport=true;\nend\nif nargin<10\n taskStructure=[];\nend\nif nargin<11\n params=[];\nend\nif nargin<12\n paramsFT=[];\nend\n\n%Check that the model is in the closed form\nif ~isfield(refModel,'unconstrained')\n EM='Exchange metabolites should normally not be removed from the model when using getINITModel. Use importModel(file,false) to import a model with exchange metabolites remaining (see the documentation for details)';\n dispEM(EM);\nend\n\n%Create the task structure if not supplied\nif any(taskFile) && isempty(taskStructure)\n taskStructure=parseTaskList(taskFile);\nend\n\n\n% sc-tINIT to identify confidence levels of gene expression\nif ~isempty(arrayData) && isfield(arrayData,'singleCells')\n if arrayData.singleCells == 1\n % Check to ensure cell type is defined\n if ~isfield(arrayData,'celltypes')\n dispEM('arrayData must contain cell type information if sc-tINIT is to be used','false'); \n end\n if ~ismember(upper(celltype),upper(arrayData.celltypes))\n dispEM('The cell type name does not match'); \n end\n \n % Analyze only cell type of interest\n J= strcmpi(arrayData.celltypes,celltype);\n \n % Analyze only genes included in the reference model\n I=ismember(arrayData.genes,refModel.genes);\n \n % Convert expression data to population fractions\n binary_levels = arrayData.levels(I,J)~=0; % Classify each gene as detected (1) or not (0) in each cell\n cell_count_levels = sum(binary_levels,2); % Number of cells expressing each transcript\n cell_frac_levels = cell_count_levels/size(binary_levels,2); % Number of cells expressing each transcript\n\n % Bin cell_frac_counts manually\n x = 0:.01:1;\n for(i = 1:length(x))\n cell_frac_count(i) = sum(round(cell_frac_levels,2)==x(i));\n end\n \n % Fit four beta distributions\n cell_frac_count(cell_frac_count==0) = NaN; % Remove zeros from optimization\n cell_frac_count(1) = NaN; % Remove non-expressed genes from optimization\n x_lim = 1; % Somewhat arbitrary parameter to fit left tail of distr.\n myfun = @(par) nansum((cell_frac_count(1:find(x>=x_lim,1)) - ...\n abs(par(1))*betapdf(x(1:find(x>=x_lim,1)),abs(par(2)),abs(par(3))) - ...\n abs(par(4))*betapdf(x(1:find(x>=x_lim,1)),abs(par(5)),abs(par(6))) - ...\n abs(par(7))*betapdf(x(1:find(x>=x_lim,1)),abs(par(8)),abs(par(9))) - ...\n abs(par(10))*betapdf(x(1:find(x>=x_lim,1)),abs(par(11)),abs(par(12)))).^2);\n \n par0 = [4,2,100,7,2,30,7,5,20,5,15,20];\n opts = optimset('Display','off');\n [par,f_val] = fminsearch(myfun,par0,opts);\n par = abs(par);\n \n % Plot results\n if (isfield(arrayData,'plotResults'))\n if arrayData.plotResults == true\n figure(); hold on; plot(x,cell_frac_count,'ko','MarkerSize',5);\n plot(x,abs(par(1))*betapdf(x,abs(par(2)),abs(par(3))),'b-','LineWidth',1)\n plot(x,abs(par(4))*betapdf(x,abs(par(5)),abs(par(6))),'b-','LineWidth',1)\n plot(x,abs(par(7))*betapdf(x,abs(par(8)),abs(par(9))),'b-','LineWidth',1)\n plot(x,abs(par(10))*betapdf(x,abs(par(11)),abs(par(12))),'b-','LineWidth',1)\n plot(x,abs(par(1))*betapdf(x,abs(par(2)),abs(par(3))) + ...\n abs(par(4))*betapdf(x,abs(par(5)),abs(par(6))) + ...\n abs(par(7))*betapdf(x,abs(par(8)),abs(par(9))) + ...\n abs(par(10))*betapdf(x,abs(par(11)),abs(par(12))),'-','Color',[.5 .5 .5],'LineWidth',2)\n xlabel('Expression Probability');ylabel('# of genes');set(gca,'FontSize',14,'LineWidth',1.25);\n title('Expression prediction','FontSize',18,'FontWeight','bold')\n end\n end\n \n % Score genes based on population expression (p = .05)\n exprs_cutoff_1 = find(cdf('beta',x,par(2),par(3)) >.95,1)-1; % Find index of no confidence genes\n exprs_cutoff_2 = find(cdf('beta',x,par(5),par(6)) >.95,1)-1; % Find index of low confidence genes\n exprs_cutoff_3 = find(cdf('beta',x,par(8),par(9)) >.95,1)-1; % Find index of low confidence genes\n exprs_cutoffs = sort([exprs_cutoff_1,exprs_cutoff_2,exprs_cutoff_3]);\n gene_scores = cell_frac_levels*0;\n gene_scores(cell_frac_levels <= x(exprs_cutoffs(1))) = 4; % Not detected\n gene_scores(logical((cell_frac_levels >= x(exprs_cutoffs(1))).*(cell_frac_levels < x(exprs_cutoffs(2))))) = 3; % Low detection\n gene_scores(logical((cell_frac_levels >= x(exprs_cutoffs(2))).*(cell_frac_levels < x(exprs_cutoffs(3))))) = 2; % Medium detection\n gene_scores(cell_frac_levels > x(exprs_cutoffs(3))) = 1; % High detection\n\n % Replace hpaData with singleCellData\n if printReport==true\n dispEM('Single cell data is not currently compatible with HPA data. \\n Replacing hpaData with single cell-based scoring.',false);\n end\n hpaData.genes = arrayData.genes;\n hpaData.tissues = arrayData.tissues;\n hpaData.celltypes = arrayData.celltypes;\n hpaData.levels = [{'High'},{'Medium'},{'Low'},{'None'}];\n hpaData.gene2Level = zeros(length(arrayData.genes),length(arrayData.celltypes));\n for i = 1:length(find(J))\n find_var = find(J,i);\n hpaData.gene2Level(I,find_var(end)) = gene_scores;\n end\n \n % Remove arrayData from the analysis (Might be a bad idea)\n clear arrayData\n arrayData=[];\n end\nend\n\n\nif printReport==true\n if any(celltype)\n fprintf(['***Generating model for: ' tissue ' - ' celltype '\\n']);\n else\n fprintf(['***Generating model for: ' tissue '\\n']);\n end\n if ~isempty(hpaData)\n fprintf('-Using HPA data\\n');\n end\n if ~isempty(arrayData)\n fprintf('-Using array data\\n');\n end\n if ~isempty(metabolomicsData)\n fprintf('-Using metabolomics data\\n');\n end\n if ~isempty(taskFile) || ~isempty(taskStructure)\n fprintf('-Using metabolic tasks\\n');\n end\n fprintf('\\n');\n \n printScores(refModel,'Reference model statistics',hpaData,arrayData,tissue,celltype);\nend\n\n%Remove dead-end reactions to speed up the optimization and to\n%differentiate between reactions removed by INIT and those that are\n%dead-end\n[~, deletedDeadEndRxns]=simplifyModel(refModel,true,false,true,true,true);\ncModel=removeReactions(refModel,deletedDeadEndRxns,false,true);\n\n%Store the connected model like this to keep track of stuff\nif printReport==true\n printScores(cModel,'Pruned model statistics',hpaData,arrayData,tissue,celltype);\nend\n\n%If tasks have been defined, then go through them and get essential\n%reactions\nif ~isempty(taskStructure)\n [taskReport, essentialRxnMat]=checkTasks(cModel,[],printReport,true,true,taskStructure);\n \n essentialRxnsForTasks=cModel.rxns(any(essentialRxnMat,2));\n \n %Remove tasks that cannot be performed\n taskStructure(taskReport.ok==false)=[];\n if printReport==true\n printScores(removeReactions(cModel,setdiff(cModel.rxns,essentialRxnsForTasks),true,true),'Reactions essential for tasks',hpaData,arrayData,tissue,celltype);\n end\nelse\n essentialRxnsForTasks={};\nend\n\n%Score the connected model\n[rxnScores, geneScores]=scoreModel(cModel,hpaData,arrayData,tissue,celltype);\n\n%Run the INIT algorithm. The exchange reactions that are used in the final\n%reactions will be open, which doesn't fit with the last step. Therefore\n%delete reactions from the original model instead of taking the output. The\n%default implementation does not constrain reversible reactions to only\n%carry flux in one direction. Runs without the constraints on reversibility\n%and with all output allowed. This is to reduce the complexity of the\n%problem.\n[~, deletedRxnsInINIT, metProduction]=runINIT(simplifyModel(cModel),rxnScores,metabolomicsData,essentialRxnsForTasks,0,true,false,params);\ninitModel=removeReactions(cModel,deletedRxnsInINIT,true,true);\nif printReport==true\n printScores(initModel,'INIT model statistics',hpaData,arrayData,tissue,celltype);\n printScores(removeReactions(cModel,setdiff(cModel.rxns,deletedRxnsInINIT),true,true),'Reactions deleted by INIT',hpaData,arrayData,tissue,celltype);\nend\n\n%The full model has exchange reactions in it. fitTasks calls on fillGaps,\n%which automatically removes exchange metabolites (because it assumes that\n%the reactions are constrained when appropriate). In this case the\n%uptakes/outputs are retrieved from the task sheet instead. To prevent\n%exchange reactions being used to fill gaps, they are delete from the\n%reference model here.\ninitModel.id='INITModel';\n\n%If gaps in the model should be filled using a task list\nif ~isempty(taskStructure)\n %Remove exchange reactions and reactions already included in the INIT\n %model\n refModelNoExc=removeReactions(refModel,union(initModel.rxns,getExchangeRxns(refModel)),true,true);\n \n %At this stage the model is fully connected and most of the genes with\n %good scores should have been included. The final gap-filling should\n %take the scores of the genes into account, so that \"rather bad\"\n %reactions are preferred to \"very bad\" reactions. However, reactions\n %with positive scores will be included even if they are not connected\n %in the current formulation. Therefore, such reactions will have to be\n %assigned a small negative score instead.\n if useScoresForTasks==true\n refRxnScores=scoreModel(refModelNoExc,hpaData,arrayData,tissue,celltype);\n [outModel, addedRxnMat]=fitTasks(initModel,refModelNoExc,[],true,min(refRxnScores,-0.1),taskStructure,paramsFT);\n else\n [outModel, addedRxnMat]=fitTasks(initModel,refModelNoExc,[],true,[],taskStructure,paramsFT);\n end\n if printReport==true\n printScores(outModel,'Functional model statistics',hpaData,arrayData,tissue,celltype);\n printScores(removeReactions(outModel,intersect(outModel.rxns,initModel.rxns),true,true),'Reactions added to perform the tasks',hpaData,arrayData,tissue,celltype);\n end\n \n addedRxnsForTasks=refModelNoExc.rxns(any(addedRxnMat,2));\nelse\n outModel=initModel;\n addedRxnMat=[];\n addedRxnsForTasks={};\nend\n\n%The model can now perform all the tasks defined in the task list. The\n%algorithm cannot deal with gene-complexes at the moment. It is therefore\n%ok to remove bad genes from a reaction (as long as at least one gene is\n%kept)\nmodel=outModel;\n\n[~, I]=ismember(model.genes,cModel.genes); %All should be found\n%This is a little weird way to make sure that only one bad gene is included\n%if there are no good ones (since all -Inf==max(-Inf))\ngeneScores(isinf(geneScores))=-1000+rand(sum(isinf(geneScores)),1);\n\nmodel.grRules(:)={''};\nfor i=1:numel(model.rxns)\n ids=find(model.rxnGeneMat(i,:));\n if numel(ids)>1\n scores=geneScores(I(ids));\n %Only keep the positive ones if possible\n model.rxnGeneMat(i,ids(~(scores>0 | scores==max(scores))))=0;\n end\n %Rewrite the grRules to be only OR\n if isfield(model,'grRules')\n J=find(model.rxnGeneMat(i,:));\n for j=1:numel(J)\n model.grRules{i}=[model.grRules{i} '(' model.genes{J(j)} ')'];\n if j0)/numel(a)) '%%\\n\\n']);\nend\n", "meta": {"author": "SysBioChalmers", "repo": "RAVEN", "sha": "cf4d3e0be954fde96a1a09ae3353dd2ee46552ed", "save_path": "github-repos/MATLAB/SysBioChalmers-RAVEN", "path": "github-repos/MATLAB/SysBioChalmers-RAVEN/RAVEN-cf4d3e0be954fde96a1a09ae3353dd2ee46552ed/INIT/getINITModel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6723317123102955, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.3047423144011135}} {"text": "function [struct_irf_record D_record gamma_record]=mairfres(beta_gibbs,sigma_gibbs,It,Bu,IRFperiods,n,p,k1,signrestable,signresperiods)\n\n\n\n% function [struct_irf_record D_record gamma_record Qdraw Qsuccess]=mairfres(beta_gibbs,sigma_gibbs,It,Bu,IRFperiods,n,p,k1,signrestable,signresperiods)\n% runs the gibbs sampler to obtain draws from the posterior distribution of IRFs, orthogonalised with a sign restriction setting\n% inputs: - matrix 'beta_gibbs': record of the gibbs sampler draws for the beta vector\n% - matrix 'sigma_gibbs': record of the gibbs sampler draws for the sigma matrix (vectorised)\n% - integer 'It': total number of iterations of the Gibbs sampler (defined p 28 of technical guide)\n% - integer 'Bu': number of burn-in iterations of the Gibbs sampler (defined p 28 of technical guide)\n% - integer 'IRFperiods': number of periods for IRFs\n% - integer 'n': the number of endogenous variables in the model\n% - integer 'p': number of lags included in the model (defined p 7 of technical guide)\n% - integer 'k1': the number of coefficients related to the endogenous variables for each equation in the model\n% - cell 'signrestable': table recording the sign restriction input from the user\n% - cell 'signresperiods': table containing the periods corresponding to each restriction\n% outputs: - cell 'struct_irf_record': record of the gibbs sampler draws for the orthogonalised IRFs\n% - matrix 'D_record': record of the gibbs sampler draws for the structural matrix D\n% - matrix 'gamma_record': record of the gibbs sampler draws for the structural disturbances variance-covariance matrix gamma\n% - integer 'Qdraw': total number of draws of the Q matrix \n% - integer 'Qsuccess': number of successful draws of the Q matrix \n\n\n\n\n\n\n% preliminary tasks\n% create first the cell that will store the results from the simulations\nstruct_irf_record=cell(n,n);\n% storage cell\nstorage1=cell(It-Bu,1);\nstorage2=cell(It-Bu,1);\n\n\n% now identify all the periods concerned with restrictions\n% first expand the non-empty entries in signresperiods since they are only expressed in intervals: transform into list\n% for instance, translate [1 4] into [1 2 3 4]; I don't think this can done without a loop\ntemp=cell2mat(signresperiods(~cellfun(@isempty,signresperiods)));\nperiods=[];\nfor ii=1:size(temp,1)\nperiods=[periods temp(ii,1):temp(ii,2)];\nend\n% suppress duplicates and sort\nperiods=sort(unique(periods))';\n% count the total number of restriction periods (required for IRF matrix)\nnperiods=size(periods,1);\n\n\n% Identify the restriction matrices\n% create five cells, corresponding to the three possible restrictions:\n% one cell for sign restrictions, three cells for magnitude restrictions, one cell for zero restrictions\nScell=cell(1,n);\nMcell=cell(1,n);\nMlcell=cell(1,n);\nMucell=cell(1,n);\nZcell=cell(1,n);\n\n% Check if value and periods restrictions correspond to each other\nif sum(sum(~cellfun(@isempty,signresperiods) == ~cellfun(@isempty,signrestable))) == n^2\n % All cells with sign restrictions also specify the horizon over which\n % these are applied\nelse\n disp('Warning: Value restrictions do not correspond to period restrictions one to one')\n pause(1)\nend\n\n% loop over rows and columns of the period matrix\nfor ii=1:n\n for jj=1:n\n % if entry (ii,jj) of the period matrix is not empty...\n if ~isempty(signresperiods{ii,jj}) && ~isempty(signrestable{ii,jj})\n % ... then there is a restriction over one (or several) periods\n % loop overt those periods\n for kk=signresperiods{ii,jj}(1,1):signresperiods{ii,jj}(1,2)\n % identify the position of the considered period within the list of all periods (required to build the matrix)\n position=find(periods==kk);\n % now create the restriction matrix: this will depend on the type of restriction\n % if it is a positive sign restriction...\n if strcmp(signrestable{ii,jj},'+')\n % ... then input a 1 entry in the corresponding S matrix\n Scell{1,jj}=[Scell{1,jj};zeros(1,n*nperiods)];\n Scell{1,jj}(end,(position-1)*n+ii)=1;\n % if it is a negative sign restriction...\n elseif strcmp(signrestable{ii,jj},'-')\n % ... then input a -1 entry in the corresponding S matrix\n Scell{1,jj}=[Scell{1,jj};zeros(1,n*nperiods)];\n Scell{1,jj}(end,(position-1)*n+ii)=-1;\n % if it is a zero restriction...\n elseif strcmp(signrestable{ii,jj},'0')\n % ... then input a 1 entry in the corresponding Z matrix\n Zcell{1,jj}=[Zcell{1,jj};zeros(1,n*nperiods)];\n Zcell{1,jj}(end,(position-1)*n+ii)=1;\n % else, a non-empty entry being neither a sign nor a zero restriction has to be a magnitude restriction\n else\n % fill the corresponding M matrices:\n % input a 1 in M\n Mcell{1,jj}=[Mcell{1,jj};zeros(1,n*nperiods)];\n Mcell{1,jj}(end,(position-1)*n+ii)=1;\n % input the lower value of the interval in Ml\n temp=str2num(signrestable{ii,jj});\n Mlcell{1,jj}=[Mlcell{1,jj};temp(1,1)];\n % input the upper value of the interval in Mu\n Mucell{1,jj}=[Mucell{1,jj};temp(1,2)];\n end\n end\n end\n end\nend\n\n\n% now check what kind of restrictions apply among sign, zero and magnitude restrictions\n% check for sign restrictions: if there are any, at least one entry in the cell Scell is non-empty\nif sum(~cellfun(@isempty,Scell))~=0\nsignres=1;\nelse\nsignres=0;\nend\n% similarly check for zero restrictions\nif sum(~cellfun(@isempty,Zcell))~=0\nzerores=1;\nelse\nzerores=0;\nend\n% and finally, check for magnitude restrictions\nif sum(~cellfun(@isempty,Mcell))~=0\nmagnres=1;\nelse\nmagnres=0;\nend\n\nnot_successful = 0;\nhbar = bear.parfor_progressbar(It-Bu,'Progress of Sign Restriction Draws'); %create the progress bar\n\n% initiate Gibbs algorithm\nparfor ii=1:It-Bu\n% initiate the variable 'success'; this variable will be used to check whether the restrictions are satisfied\nsuccess=0;\n\n\n while success==0\n not_successful = not_successful+1;\n % switch 'success' to 1; it will be turned back to zero if at any time Q is detected as a candidate not satisfying the restrictions\n success=1;\n\n\n % draw the vector of VAR coefficients\n % select first a draw index randomly\n index=floor(rand*(It-Bu))+1;\n % then draw a random set of beta and sigma corresponding to this index (this is done to make it possible to draw, if required, an infinite number of values from the gibbs sampler record, with equal probability on each value)\n B=reshape(beta_gibbs(:,ii),k1,n);\n sigma=reshape(sigma_gibbs(:,ii),n,n);\n hsigma=chol(bear.nspd(sigma),'lower');\n % obtain orthogonalised IRFs\n [irfmatrix ortirfmatrix]=bear.mairfsim(B,hsigma,p,n,max(IRFperiods,max(periods)));\n\n\n \n % generate the stacked IRF matrix\n stackedirfmat=[];\n for jj=1:numel(periods)\n stackedirfmat=[stackedirfmat;ortirfmatrix(:,:,periods(jj,1)+1)];\n end\n % draw an entire random matrix Q satisfying the zero restrictions\n [Q]=bear.qzerores(n,Zcell,stackedirfmat);\n\n\n % generate the candidate matrix of structural IRFs\n candidate=stackedirfmat*Q;\n\n\n % verify the restrictions in turn (sign, magnitude, or both)\n % the zero restrictions don't have to be verified, there are satisfied by construction\n % consider first the case of pure sign restrictions\n if signres==1 && magnres==0\n % loop over structural shocks; stop as soon as the draw is detected as a fail\n jj=1;\n while success==1 && jj<=n\n % if the corresponding entry in Scell is not empty, it contains a restriction to be checked\n if ~isempty(Scell{1,jj})\n % check if the restrictions hold\n if all(Scell{1,jj}*candidate(:,jj)>=0)\n % if the restrictions do not hold, there may still be a possibility by switching the sign of the Q column\n elseif all(Scell{1,jj}*((-1)*candidate(:,jj))>=0)\n Q(:,jj)=-Q(:,jj);\n % else, if there is no way to have Q succesful, count it as a fail and switch the variable success to 0\n else\n success=0;\n end\n end\n jj=jj+1;\n end\n % consider now the case of pure magnitude restrictions\n elseif signres==0 && magnres==1\n % loop over structural shocks\n jj=1;\n while success==1 && jj<=n\n % if the corresponding entry is not empty, it contains a restriction to be checked\n if ~isempty(Mcell{1,jj})\n % check if the restriction holds\n if all((Mcell{1,jj}*candidate(:,jj)-Mlcell{1,jj}).*(Mucell{1,jj}-Mcell{1,jj}*candidate(:,jj))>=0)\n % if they do not hold, there may still be a possibility by switching the sign of the Q column\n elseif all((Mcell{1,jj}*(-1)*candidate(:,jj)-Mlcell{1,jj}).*(Mucell{1,jj}-Mcell{1,jj}*(-1)*candidate(:,jj))>=0)\n Q(:,jj)=-Q(:,jj);\n % else, if there is no way to have Q succesful, count it as a fail and switch the variable success to 0\n else\n success=0;\n end\n end\n jj=jj+1;\n end\n % consider then the case of mixed sign and magnitude restrictions\n elseif signres==1 && magnres==1\n % loop over structural shocks\n jj=1;\n while success==1 && jj<=n\n % for a given structural shock, there may be no restrictions, only one type, or both types\n % if both types\n if ~isempty(Scell{1,jj}) && ~isempty(Mcell{1,jj})\n % check both restrictions\n if all(Scell{1,jj}*candidate(:,jj)>=0) && all((Mcell{1,jj}*candidate(:,jj)-Mlcell{1,jj}).*(Mucell{1,jj}-Mcell{1,jj}*candidate(:,jj))>=0)\n % if not, try to switch the sign of the corresponding column in Q\n elseif all(Scell{1,jj}*((-1)*candidate(:,jj))>=0) && all((Mcell{1,jj}*(-1)*candidate(:,jj)-Mlcell{1,jj}).*(Mucell{1,jj}-Mcell{1,jj}*(-1)*candidate(:,jj))>=0)\n Q(:,jj)=-Q(:,jj);\n % else, if there is no way to have Q succesful, count it as a fail and switch the variable success to 0\n else\n success=0;\n end\n % if only sign restrictions\n elseif ~isempty(Scell{1,jj}) && isempty(Mcell{1,jj})\n % check if the restrictions hold\n if all(Scell{1,jj}*candidate(:,jj)>=0)\n % if the restrictions do not hold, there may still be a possibility by switching the sign of the Q column\n elseif all(Scell{1,jj}*((-1)*candidate(:,jj))>=0)\n Q(:,jj)=-Q(:,jj);\n % else, if there is no way to have Q succesful, count it as a fail and switch the variable success to 0\n else\n success=0;\n end\n % if only magnitude restrictions\n elseif isempty(Scell{1,jj}) && ~isempty(Mcell{1,jj})\n % check if the restriction holds\n if all((Mcell{1,jj}*candidate(:,jj)-Mlcell{1,jj}).*(Mucell{1,jj}-Mcell{1,jj}*candidate(:,jj))>=0)\n % if they do not hold, there may still be a possibility by switching the sign of the Q column\n elseif all((Mcell{1,jj}*(-1)*candidate(:,jj)-Mlcell{1,jj}).*(Mucell{1,jj}-Mcell{1,jj}*(-1)*candidate(:,jj))>=0)\n Q(:,jj)=-Q(:,jj);\n % else, if there is no way to have Q succesful, count it as a fail and switch the variable success to 0\n else\n success=0;\n end\n end\n jj=jj+1;\n end\n % finally, the only possible remaining case is that of pure zero restrictions, satisfied by construction: no need to check\n else\n end\n \n % now, if sucess is still equal to 1, it means that the draw was successful for all the restrictions: keep it\n % otherwise, if success has been switched to 0, there was at least one failure: discard the draw and try with a new draw\n end\n\n\n\n\n % store\n for jj=1:IRFperiods\n storage1{ii,1}(:,:,jj)=ortirfmatrix(:,:,jj)*Q;\n end\n storage2{ii,1}=hsigma*Q;\n \n hbar.iterate(1); % update progress by one iteration\n\nend\n\nclose(hbar); %close progress bar\n\n \n% reorganise storage\n% loop over iterations\nfor ii=1:It-Bu\n % loop over IRF periods\n for jj=1:IRFperiods\n % loop over variables\n for kk=1:n\n % loop over shocks\n for ll=1:n\n struct_irf_record{kk,ll}(ii,jj)=storage1{ii,1}(kk,ll,jj); \n end\n end\n end\nD_record(:,ii)=storage2{ii,1}(:);\ngamma_record(:,ii)=bear.vec(eye(n));\nend\n\n\nfprintf('Accepted Draws in Percent of Total Number of Draws: %f', 100*(It-Bu)/(not_successful + It-Bu))\n\n\n\n", "meta": {"author": "european-central-bank", "repo": "BEAR-toolbox", "sha": "f33aae80c40f7a2e78a54de99b2ce3663f59aa75", "save_path": "github-repos/MATLAB/european-central-bank-BEAR-toolbox", "path": "github-repos/MATLAB/european-central-bank-BEAR-toolbox/BEAR-toolbox-f33aae80c40f7a2e78a54de99b2ce3663f59aa75/tbx/bear/unreachableCode_ToRemove/mairfres.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.3047069091038052}} {"text": "function [varargout]=subEdge(varargin)\n\n%%\n\nswitch nargin\n case 2\n F=varargin{1};\n V=varargin{2};\n n=1;\n uniqueOpt=1;\n case 3\n F=varargin{1};\n V=varargin{2};\n n=varargin{3};\n uniqueOpt=1;\n case 4\n F=varargin{1};\n V=varargin{2};\n n=varargin{3};\n uniqueOpt=varargin{4};\nend\n\n%%\n\n%Check if n can be achieved through splitting\nnSplitIterations=log2(n+1); %Check for integer solution\nlogicInteger=abs(round(nSplitIterations)-nSplitIterations)\n% \n% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for\n% image segmentation, image-based modeling, meshing, and finite element\n% analysis.\n% \n% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n", "meta": {"author": "gibbonCode", "repo": "GIBBON", "sha": "8178520664a6148db939eaea87e75b3cba4f2b4f", "save_path": "github-repos/MATLAB/gibbonCode-GIBBON", "path": "github-repos/MATLAB/gibbonCode-GIBBON/GIBBON-8178520664a6148db939eaea87e75b3cba4f2b4f/lib/subEdge.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6442250928250375, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.3045145566026598}} {"text": "function [bnet, LL, engine] = learn_params_dbn_em(engine, evidence, varargin)\n% LEARN_PARAMS_DBN Set the parameters in a DBN to their ML/MAP values using batch EM.\n% [bnet, LLtrace, engine] = learn_params_dbn_em(engine, data, ...)\n%\n% data{l}{i,t} = value of node i in slice t of time-series l, or [] if hidden.\n% Suppose you have L time series, each of length T, in an O*T*L array D, \n% where O is the num of observed scalar nodes, and N is the total num nodes per slice.\n% Then you can create data as follows, where onodes is the index of the observable nodes:\n% data = cell(1,L);\n% for l=1:L\n% data{l} = cell(N, T);\n% data{l}(onodes,:) = num2cell(D(:,:,l));\n% end\n% Of course it is possible for different sets of nodes to be observed in\n% each slice/ sequence, and for each sequence to be a different length.\n%\n% LLtrace is the learning curve: the vector of log-likelihood scores at each iteration.\n%\n% Optional arguments [default]\n%\n% max_iter - specifies the maximum number of iterations [100]\n% thresh - specifies the thresold for stopping EM [1e-3]\n% We stop when |f(t) - f(t-1)| / avg < threshold,\n% where avg = (|f(t)| + |f(t-1)|)/2 and f is log lik.\n% verbose - display loglik at each iteration [1]\n% anneal - 1 means do deterministic annealing (only for entropic priors) [0]\n% anneal_rate - geometric cooling rate [0.8]\n% init_temp - initial annealing temperature [10]\n% final_temp - final annealing temperature [1e-3]\n%\n\nmax_iter = 100;\nthresh = 1e-3;\nanneal = 0;\nanneal_rate = 0.8;\ninit_temp = 10;\nfinal_temp = 1e-3;\nverbose = 1;\n\nfor i=1:2:length(varargin)\n switch varargin{i}\n case 'max_iter', max_iter = varargin{i+1}; \n case 'thresh', thresh = varargin{i+1}; \n case 'anneal', anneal = varargin{i+1}; \n case 'anneal_rate', anneal_rate = varargin{i+1}; \n case 'init_temp', init_temp = varargin{i+1}; \n case 'final_temp', final_temp = varargin{i+1}; \n otherwise, error(['unrecognized argument' varargin{i}])\n end\nend\n\n% take 1 EM step at each temperature value, then when temp=0, run to convergence\n% When using an entropic prior, Z = 1-T, so \n% T=2 => Z=-1 (max entropy)\n% T=1 => Z=0 (max likelihood)\n% T=0 => Z=1 (min entropy / max structure)\nnum_iter = 1;\nLL = [];\nif anneal\n temperature = init_temp;\n while temperature > final_temp\n [engine, loglik, logpost] = EM_step(engine, evidence, temperature);\n if verbose\n fprintf('EM iteration %d, loglik = %8.4f, logpost = %8.4f, temp=%8.4f\\n', ...\n\t num_iter, loglik, logpost, temperature);\n end\n num_iter = num_iter + 1;\n LL = [LL loglik];\n temperature = temperature * anneal_rate;\n end\n temperature = 0;\n previous_loglik = loglik;\n previous_logpost = logpost;\nelse\n temperature = 0;\n previous_loglik = -inf;\n previous_logpost = -inf;\nend\n\nconverged = 0;\nwhile ~converged & (num_iter <= max_iter)\n [engine, loglik, logpost] = EM_step(engine, evidence, temperature);\n if verbose\n %fprintf('EM iteration %d, loglik = %8.4f, logpost = %8.4f\\n', ...\n %\t num_iter, loglik, logpost);\n fprintf('EM iteration %d, loglik = %8.4f\\n', num_iter, loglik);\n end\n num_iter = num_iter + 1;\n [converged, decreased] = em_converged(loglik, previous_loglik, thresh);\n %[converged, decreased] = em_converged(logpost, previous_logpost, thresh);\n previous_loglik = loglik;\n previous_logpost = logpost;\n LL = [LL loglik];\nend\n\nbnet = bnet_from_engine(engine);\n\n%%%%%%%%%\n\nfunction [engine, loglik, logpost] = EM_step(engine, cases, temp)\n\nbnet = bnet_from_engine(engine); % engine contains the old params that are used for the E step\nss = length(bnet.intra);\nCPDs = bnet.CPD; % these are the new params that get maximized\nnum_CPDs = length(CPDs);\n\n% log P(theta|D) = (log P(D|theta) + log P(theta)) - log(P(D))\n% where log P(D|theta) = sum_cases log P(case|theta)\n% and log P(theta) = sum_CPDs log P(CPD) - only count once even if tied!\n% logpost = log P(theta,D) (un-normalized)\n% This should be negative, and increase at every step.\n\nadjustable = zeros(1,num_CPDs);\nlogprior = zeros(1, num_CPDs);\nfor e=1:num_CPDs\n adjustable(e) = adjustable_CPD(CPDs{e});\nend\nadj = find(adjustable);\n\nfor e=adj(:)'\n logprior(e) = log_prior(CPDs{e});\n CPDs{e} = reset_ess(CPDs{e});\nend\n\nloglik = 0;\nfor l=1:length(cases)\n evidence = cases{l};\n if ~iscell(evidence)\n error('training data must be a cell array of cell arrays')\n end\n [engine, ll] = enter_evidence(engine, evidence);\n assert(~isnan(ll))\n loglik = loglik + ll;\n T = size(evidence, 2);\n \n % We unroll ns etc because in update_ess, we refer to nodes by their unrolled number\n % so that they extract evidence from the right place.\n % (The CPD should really store its own version of ns and cnodes...)\n ns = repmat(bnet.node_sizes_slice(:), [1 T]);\n cnodes = unroll_set(bnet.cnodes_slice, ss, T);\n \n %hidden_bitv = repmat(bnet.hidden_bitv(1:ss), [1 T]);\n hidden_bitv = zeros(ss, T);\n hidden_bitv(isemptycell(evidence))=1;\n % hidden_bitv(i) = 1 means node i is hidden.\n % We pass this in, rather than using isemptycell(evidence(dom)), because\n % isemptycell is very slow.\n \n t = 1;\n for i=1:ss\n e = bnet.equiv_class(i,1);\n if adjustable(e)\n fmarg = marginal_family(engine, i, t);\n CPDs{e} = update_ess(CPDs{e}, fmarg, evidence, ns(:), cnodes(:), hidden_bitv(:)); \n end\n end\n \n for i=1:ss \n e = bnet.equiv_class(i,2);\n if adjustable(e)\n for t=2:T\n\tfmarg = marginal_family(engine, i, t);\n\tCPDs{e} = update_ess(CPDs{e}, fmarg, evidence, ns(:), cnodes(:), hidden_bitv(:));\n end\n end\n end\nend\n\nlogpost = loglik + sum(logprior(:));\n\nfor e=adj(:)'\n CPDs{e} = maximize_params(CPDs{e}, temp);\nend\n\nengine = update_engine(engine, CPDs);\n\n\n\n\n", "meta": {"author": "bayesnet", "repo": "bnt", "sha": "bebba5f437b4e1e29169f0f3669df59fb5392e62", "save_path": "github-repos/MATLAB/bayesnet-bnt", "path": "github-repos/MATLAB/bayesnet-bnt/bnt-bebba5f437b4e1e29169f0f3669df59fb5392e62/BNT/learning/learn_params_dbn_em.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6334102775181399, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.30434013280387384}} {"text": "classdef (InferiorClasses = {?rotation,?quaternion}) orientation < rotation\n%\n% The class *orientation* represents orientations and misorientations.\n%\n% Syntax\n% ori = orientation(rot)\n% ori = orientation.byEuler(phi1,Phi,phi2,cs,ss)\n% ori = orientation.byEuler(alpha,beta,gamma,'ZYZ',cs,ss)\n% ori = orientation.byMiller([h k l],[u v w],cs,ss)\n% ori = orientation.byAxisAngle(v,omega,cs,ss)\n% ori = orientation.byMatrix(A,cs)\n% ori = orientation.map(u1,v1,u2,v2,cs)\n% ori = orientation.goss(cs)\n% ori = orientation.cube(cs)\n%\n% Input\n% rot - @rotation\n% cs, ss - @crystalSymmetry / @specimenSymmetry\n%\n% Output\n% ori - @orientation\n%\n% Class Properties\n% CS, SS - @crystalSymmetry / @specimenSymmetry\n% antipodal - grain exchange symmetry for misorientations\n% phi1, Phi, phi2 - Euler angles\n% i - inversion\n% a, b, c, d - quaternion components\n%\n% See also\n% DefinitionAsCoordinateTransform CrystalOperations CrystalReferenceSystem\n\nproperties\n\n CS = crystalSymmetry('1'); % crystal symmetry\n SS = specimenSymmetry('1'); % specimen symmetry or crystal symmetry\n antipodal = false\n\nend\n\nmethods\n\n function o = orientation(varargin) \n\n % find and remove symmetries\n args = cellfun(@(s) isa(s,'symmetry'),varargin,'uniformoutput',true);\n sym = varargin(args);\n varargin(args) = [];\n\n % call rotation constructor\n o = o@rotation(varargin{:});\n\n if nargin == 0, return;end\n\n % set symmetry\n if ~isempty(varargin) && isa(varargin{1},'orientation')\n o.CS = varargin{1}.CS;\n o.SS = varargin{1}.SS;\n o.antipodal = varargin{1}.antipodal;\n elseif ~isempty(varargin) && ischar(varargin{1}) && strcmpi(varargin{1},'map')\n if isa(varargin{2},'Miller'), o.CS = varargin{2}.CS; end\n if isa(varargin{3},'Miller'), o.SS = varargin{3}.CS; end\n else\n try %#ok\n a = get_option(varargin,'axis');\n o.CS = a.CS;\n o.SS = a.CS;\n end\n end\n if ~isempty(sym), o.CS = sym{1};end\n if length(sym) > 1, o.SS = sym{2};end\n\n % empty constructor -> done\n if isempty(varargin), return; end\n\n % copy constructor\n switch class(varargin{1})\n\n case 'char'\n\n switch lower(varargin{1})\n\n case 'miller'\n\n o = orientation.byMiller(varargin{:});\n\n otherwise\n\n if exist([varargin{1},'Orientation'],'file')\n \n % there is a file defining this specific orientation\n o = eval([varargin{1},'Orientation(o.CS,o.SS)']);\n \n end\n end\n end\n o.antipodal = o.antipodal | check_option(varargin,'antipodal');\n if o.antipodal && o.CS ~= o.SS\n warning('antipodal symmetry is only meaningfull for misorientations between the same phase.')\n end\n end\nend\n\nmethods (Static = true)\n\n function ori = nan(varargin)\n s = varargin(cellfun(@isnumeric,varargin));\n q = quaternion.nan(s{:});\n ori = orientation(q,varargin{:});\n end\n\n function ori = id(varargin)\n id = find(~cellfun(@isnumeric,varargin),1)-1;\n q = quaternion.id(varargin{1:id});\n ori = orientation(q,varargin{id+1:end});\n end\n\n function ori = rand(varargin)\n q = quaternion.rand(varargin{:});\n ori = orientation(q,varargin{:});\n end\n\n\n ori = byMiller(m1,m2,varargin);\n ori = byEuler(phi1,Phi,phi2,varargin);\n ori = byAxisAngle(v,omega,varargin);\n ori = byMatrix(M,varargin);\n ori = map(varargin);\n ori = fit(varargin);\n [ori,interface,options] = load(fname,varargin);\n\n function ori = cube(varargin)\n ori = orientation.byEuler(0,0,0,varargin{:});\n end\n\n function ori = cubeND22(varargin)\n ori = orientation.byEuler(22*degree,0,0,varargin{:});\n end\n\n function ori = cubeND45(varargin)\n ori = orientation.byEuler(45*degree,0,0,varargin{:});\n end\n\n function ori = cubeRD(varargin)\n ori = orientation.byEuler(0,22*degree,0,varargin{:});\n end\n\n function ori = goss(varargin)\n ori = orientation.byEuler(0,45*degree,0,varargin{:});\n end\n\n function ori = copper(varargin)\n %ori = orientation.byEuler(90*degree,35*degree,45*degree,varargin{:});\n ori = orientation.byMiller([1 1 2],[-1 1 -1],varargin{:});\n end\n\n function ori = copper2(varargin)\n %ori = orientation.byEuler(270*degree,35*degree,45*degree,varargin{:});\n ori = orientation.byMiller([1 1 2],[1 -1 1],varargin{:});\n end\n\n function ori = SR(varargin)\n ori = orientation.byEuler(53*degree,35*degree,63*degree,varargin{:});\n end\n\n function ori = SR2(varargin)\n ori = orientation.byEuler(233*degree,35*degree,63*degree,varargin{:});\n end\n\n function ori = SR3(varargin)\n ori = orientation.byEuler(307*degree,35*degree,27*degree,varargin{:});\n end\n\n function ori = SR4(varargin)\n ori = orientation.byEuler(127*degree,35*degree,27*degree,varargin{:});\n end\n\n function ori = brass(varargin)\n ori = orientation.byEuler(35*degree,45*degree,0*degree,varargin{:});\n end\n\n function ori = brass2(varargin)\n ori = orientation.byEuler(325*degree,45*degree,0*degree,varargin{:});\n end\n\n function ori = PLage(varargin)\n ori = orientation.byEuler(65*degree,45*degree,0*degree,varargin{:});\n end\n\n function ori = PLage2(varargin)\n ori = orientation.byEuler(245*degree,45*degree,0*degree,varargin{:});\n end\n\n function ori = QLage(varargin)\n ori = orientation.byEuler(65*degree,20*degree,0*degree,varargin{:});\n end\n\n function ori = QLage2(varargin)\n ori = orientation.byEuler(245*degree,20*degree,0*degree,varargin{:});\n end\n\n function ori = QLage3(varargin)\n ori = orientation.byEuler(115*degree,160*degree,0*degree,varargin{:});\n end\n\n function ori = QLage4(varargin)\n ori = orientation.byEuler(295*degree,160*degree,0*degree,varargin{:});\n end\n\n function ori = invGoss(varargin)\n ori = orientation.byEuler(90*degree,45*degree,0*degree,varargin{:});\n end\n\n function mori = Bain(csGamma,csAlpha)\n %\n % Syntax:\n % mori = Bain(csGamma,csAlpha)\n %\n % Input\n % csGamma - parent @crystalSymmetry (cubic fcc)\n % csAlpha - child @crystalSymmetry (cubic bcc)\n %\n\n mori = orientation.map(Miller(1,0,0,csGamma),Miller(1,0,0,csAlpha),...\n Miller(0,1,0,csGamma,'uvw'),Miller(0,1,1,csAlpha,'uvw'));\n end\n\n function mori = KurdjumovSachs(csGamma,csAlpha)\n %\n % Syntax:\n % mori = KurdjumovSachs(csGamma,csAlpha)\n %\n % Input\n % csGamma - parent @crystalSymmetry (cubic fcc)\n % csAlpha - child @crystalSymmetry (cubic bcc)\n %\n\n mori = orientation.map(Miller(1,1,1,csGamma),Miller(0,1,1,csAlpha),...\n Miller(-1,0,1,csGamma,'uvw'),Miller(-1,-1,1,csAlpha,'uvw'));\n end\n\n function mori = NishiyamaWassermann(csGamma,csAlpha)\n %\n % Syntax:\n % mori = NishiyamaWassermann(csGamma,csAlpha)\n %\n % Input\n % csGamma - parent @crystalSymmetry (cubic fcc)\n % csAlpha - child @crystalSymmetry (cubic bcc)\n %\n\n mori = orientation.map(Miller(1,1,1,csGamma),Miller(0,1,1,csAlpha),...\n Miller(1,1,-2,csGamma,'uvw'),Miller(0,-1,1,csAlpha,'uvw'));\n end\n\n function mori = Pitsch(csGamma,csAlpha)\n %\n % Syntax:\n % mori = Pitch(csGamma,csAlpha)\n %\n % Input\n % csGamma - parent @crystalSymmetry (cubic fcc)\n % csAlpha - child @crystalSymmetry (cubic bcc)\n %\n\n mori = orientation.map(Miller(0,1,0,csGamma),Miller(1,0,1,csAlpha),...\n Miller(1,0,1,csGamma,'uvw'),Miller(-1,1,1,csAlpha,'uvw'));\n\n %mori = orientation.map(Miller(1,1,0,csGamma),Miller(1,1,1,csAlpha),...\n % Miller(0,0,1,csGamma,'uvw'),Miller(-1,1,0,csAlpha,'uvw'));\n\n end\n\n function mori = GreningerTrojano(csGamma,csAlpha)\n %\n % Syntax:\n % mori = orientation.GreningerTrojano(csGamma,csAlpha)\n %\n % Input\n % csGamma - parent @crystalSymmetry (cubic fcc)\n % csAlpha - child @crystalSymmetry (cubic bcc)\n %\n \n mori = inv(orientation.byEuler(2.7*degree,46.6*degree,7.5*degree,csAlpha,csGamma));\n\n %mori = orientation.map(Miller(1,1,1,csGamma),Miller(1,1,0,csAlpha),...\n % Miller(5,12,17,csGamma,'uvw'),Miller(17,17,7,csAlpha,'uvw'));\n\n end\n\n function mori = Burgers(csParent,csChild)\n %\n % Syntax:\n % mori = orientation.Burgers(csParent,csChild)\n %\n % Input\n % csParent - parent @crystalSymmetry\n % csChild - child @crystalSymmetry\n %\n \n if csParent.lattice.isTriHex\n mori = inv(orientation.Burgers(csChild,csParent));\n else\n mori = orientation.map(Miller(1,1,0,csParent),Miller(0,0,0,1,csChild),...\n Miller(-1,1,-1,csParent),Miller(2,-1,-1,0,csChild));\n end\n \n end\n \n function mori = Burger(varargin)\n \n warning('orientation.Burger has been renamed to orientation.Burgers')\n \n mori = orientation.Burgers(varargin{:});\n \n end\n \n \n function mori = ShojiNishiyama(csGamma,csEps)\n %\n % Syntax:\n % mori = orientation.ShojiNishiyama(csGamma,csEps)\n %\n % Input\n % csGamma - parent @crystalSymmetry\n % csEps - child @crystalSymmetry\n %\n \n mori = orientation.map(Miller(1, 1, 1,csGamma),Miller(0, 0, 0, 1,csEps),...\n Miller(1, 0, -1,csGamma,'uvw'),Miller(2, -1, -1, 0,csEps,'uvw'));\n \n end\n \nend\n\n\nmethods (Static = true, Hidden = true)\n\n function check_dot(cs)\n \n % first setting\n cs = crystalSymmetry('m-3m');\n n = 10000000;\n ori1 = orientation.rand(n,cs);\n ori2 = orientation.rand(n,cs);\n \n tic\n mori = inv(ori1) .* ori2;\n \n d1 = max(dot_outer(mori,cs.rot,'noSymmetry'),[],2);\n toc\n \n tic\n d2 = dot(ori1,ori2);\n toc\n \n norm(d1-d2)\n \n %second setting\n n = 1000000;\n ori1 = orientation.rand(n,cs,cs);\n ori2 = orientation.rand(cs,cs);\n \n tic\n d1 = dot(ori1,ori2);\n toc\n \n tic\n d2 = dot(ori2,ori1);\n toc\n \n norm(d1-d2)\n \n \n end\n \n \n \n \n \nend\n \nend\n", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/geometry/@orientation/orientation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.45713671682749474, "lm_q1q2_score": 0.30418359816786733}} {"text": "function [Eft, Varft, lpyt, Eyt, Varyt] = gpsvi_predgrad(gp,x,y,varargin)\n%GPSVI_PREDGRAD Make predictions with SVI GP\n%\n% Description\n% [EFT, VARFT] = GPSVI_PREDGRAD(GP, X, Y, XT, OPTIONS)\n% takes a GP structure together with matrix X of training inputs and\n% vector Y of training targets, and evaluates the predictive\n% distribution at test inputs XT. Returns a posterior mean EFT and\n% variance VARFT of latent variables. Each row of X corresponds to one\n% input vector and each row of Y corresponds to one output vector.\n%\n% [EFT, VARFT, LPYT] = GPSVI_PREDGRAD(GP, X, Y, XT, 'yt', YT, OPTIONS)\n% returns also logarithm of the predictive density LPYT of the\n% observations YT at test input locations XT. This can be used\n% for example in the cross-validation. Here Y has to be a vector.\n% \n% [EFT, VARFT, LPYT, EYT, VARYT] = GPSVI_PREDGRAD(GP, X, Y, XT, OPTIONS)\n% returns also the posterior predictive mean EYT and variance VARYT.\n%\n% [EF, VARF, LPY, EY, VARY] = GPSVI_PREDGRAD(GP, X, Y, OPTIONS)\n% evaluates the predictive distribution at training inputs X\n% and logarithm of the predictive density LPY of the training\n% observations Y.\n%\n% OPTIONS is optional parameter-value pair\n% predcf - an index vector telling which covariance functions are \n% used for prediction. Default is all (1:gpcfn). \n% See additional information below.\n% yt - optional observed yt in test points (see below)\n% z - optional observed quantity in triplet (x_i,y_i,z_i)\n% Some likelihoods may use this. For example, in case of \n% Poisson likelihood we have z_i=E_i, that is, expected value \n% for ith case. \n% zt - optional observed quantity in triplet (xt_i,yt_i,zt_i)\n% Some likelihoods may use this. For example, in case of \n% Poisson likelihood we have z_i=E_i, that is, the expected \n% value for the ith case. \n%\n% See also\n% GPSVI_PRED, SVIGP, DEMO_SVI*\n%\n\n% Copyright (c) 2014 Ville Tolvanen\n\n% This software is distributed under the GNU General Public\n% License (version 3 or later); please refer to the file\n% License.txt, included with the software, for details.\n\nip=inputParser;\nip.FunctionName = 'GP_PRED';\nip.addRequired('gp',@(x) isstruct(x) || iscell(x));\nip.addRequired('x', @(x) ~isempty(x) && isreal(x) && all(isfinite(x(:))))\nip.addRequired('y', @(x) ~isempty(x) && isreal(x) && all(isfinite(x(:))))\nip.addOptional('xt', [], @(x) isempty(x) || (isreal(x) && all(isfinite(x(:)))))\nip.addParamValue('yt', [], @(x) isreal(x) && all(isfinite(x(:))))\nip.addParamValue('zt', [], @(x) isreal(x) && all(isfinite(x(:))))\nip.addParamValue('z', [], @(x) isreal(x) && all(isfinite(x(:))))\nip.addParamValue('predcf', [], @(x) isempty(x) || ...\n isvector(x) && isreal(x) && all(isfinite(x)&x>=0))\nif numel(varargin)==0 || isnumeric(varargin{1})\n % inputParser should handle this, but it doesn't\n ip.parse(gp, x, y, varargin{:});\nelse\n ip.parse(gp, x, y, [], varargin{:});\nend\nxt=ip.Results.xt;\nyt=ip.Results.yt;\nzt=ip.Results.zt;\nz=ip.Results.z;\npredcf=ip.Results.predcf;\nif isempty(xt)\n xt=x;\n if isempty(yt)\n yt=y;\n end\n if isempty(zt)\n zt=z;\n end\nend\n\ntn = size(x,1);\nif nargout > 2 && isempty(yt)\n lpyt=[];\nend\n\n% [tmp,tmp,tmp,param]=gpsvi_e(gp_pak(gp),gp,x,y);\n\n% Check if the variational parameters has been set\nif ~isfield(gp, 'm') || ~isfield(gp, 'S')\n error('Variational parameters has not been set. Call SVIGP first.')\nend\n\nu = gp.X_u;\nm=gp.m;\nS=gp.S;\nif size(u,2) ~= size(x,2)\n % Turn the inducing vector on right direction\n u=u';\nend\n% Calculate some help matrices\nK_uu = gp_trcov(gp, u); % u x u, noiseles covariance K_uu\nK_nu = gp_dcov2(gp, u, [], xt, xt);\nK_nu = (K_nu(:,size(xt,1)+1:end))';\n% K_nu = gp_cov(gp,xt,u); % n x u\n[Luu, notpositivedefinite] = chol(K_uu,'lower');\nif notpositivedefinite\n Eft=NaN; Varft=NaN; lpyt=NaN; Eyt=NaN; Varyt=NaN;\n return\nend\n\nEft = K_nu*(Luu'\\(Luu\\m));\n\nif nargout > 1\n [Knn_v, Cnn_v] = gp_trvar(gp,xt,predcf);\n B2=Luu\\(K_nu');\n B3=K_uu\\(K_nu');\n\n Varft = Knn_v - sum(B2.*B2)' + sum(B3.*(S*B3))';\nend\ns2=gp.lik.sigma2;\n\n\nif nargout > 2\n if isequal(gp.lik.type, 'Gaussian')\n Eyt = Eft;\n Varyt = Varft + Cnn_v - Knn_v;\n if ~isempty(yt)\n lpyt = norm_lpdf(yt, Eyt, sqrt(Varyt));\n end\n else\n if nargout>3\n [lpyt, Eyt, Varyt] = gp.lik.fh.predy(gp.lik, Eft, Varft+s2, yt, zt);\n else\n lpyt = gp.lik.fh.predy(gp.lik, Eft, Varft+s2, yt, zt);\n end\n end\nend\nend\n\nfunction [C, Cinv] = gp_dcov2(gp, x1, xv1, x2, xv2, predcf)\n% Replacement for GP_DCOV where virtual inputs are given as arguments.\n\n% Split the training data for normal latent input and gradient inputs\nx12=x1;\n%x11=gp.xv;\nx11=xv1;\nx3=xv2;\n\n% Derivative observations\n[n,m]=size(x1);\n[n4,m4]=size(x2);\nncf=length(gp.cf);\nif isfield(gp, 'nvd')\n % Only specific dimensions\n ii1=abs(gp.nvd);\nelse\n % All dimensions\n ii1=1:m;\nend\nfor i1=1:ncf\n gpcf = gp.cf{i1}; \n if m==1\n Gset2 = gpcf.fh.ginput4(gpcf, x3, x12);\n Kff = gpcf.fh.cov(gpcf, x12, x2);\n if ~isempty(x11)\n Gset1 = gpcf.fh.ginput4(gpcf, x11, x2);\n Kdd = gpcf.fh.ginput2(gpcf, x11, x3);\n Kdf=Gset1{1};\n else\n Kdd={[]};\n Kdf=[];\n end\n\n Kfd=Gset2{1};\n C = [Kff Kfd'; Kdf Kdd{1}];\n \n % Input dimension is >1\n else\n [n,m]=size(x11);\n [n2,m2]=size(x3);\n \n Kff = gpcf.fh.cov(gpcf, x12, x2);\n Gset2 = gpcf.fh.ginput4(gpcf, x3, x12);\n \n %Gather matrices from Gset (d k(x1,x2) /d x1)\n Kfd22=cat(2,Gset2{ii1});\n Kdf22=cat(1,Gset2{ii1})';\n \n if ~isempty(x11)\n Gset1 = gpcf.fh.ginput4(gpcf, x11,x2);\n Kfd=cat(2,Gset1{ii1});\n Kdf=cat(1,Gset1{ii1});\n % both x derivatives, same dimension (to diagonal blocks)\n D = gpcf.fh.ginput2(gpcf, x11, x3);\n % both x derivatives, different dimension (non-diagonal blocks)\n Kdf2 = gpcf.fh.ginput3(gpcf, x11 ,x3);\n \n % Now build up Kdd m*n x m*n2 matrix, which contains all the\n % both partial derivative\" -matrices\n \n % Add the diagonal matrices\n Kdd=blkdiag(D{1:m});\n % Add the non-diagonal matrices to Kdd\n ii3=0;\n for j=0:m-2\n for i=1+j:m-1\n ii3=ii3+1;\n Kdd(i*n+1:(i+1)*n,j*n2+1:j*n2+n2) = Kdf2{ii3};\n Kdd(j*n+1:j*n+n,i*n2+1:(i+1)*n2) = Kdf2{ii3};\n end\n end\n if isfield(gp, 'nvd')\n % Collect the correct gradient dimensions, i.e. select the blocks\n % that correspond to the input dimensions for which we want the\n % gradients to be monotonic\n Kddtmp=[];\n for ii2=1:length(ii1)\n for ii3=ii2:length(ii1)\n Kddtmp((ii2-1)*n+1:ii2*n, (ii3-1)*n2+1:ii3*n2) = ...\n Kdd((ii1(ii2)-1)*n+1:ii1(ii2)*n,(ii1(ii3)-1)*n2+1:ii1(ii3)*n2);\n if ii2~=ii3\n Kddtmp((ii3-1)*n+1:ii3*n, (ii2-1)*n2+1:ii2*n2) = ...\n Kdd((ii1(ii3)-1)*n+1:ii1(ii3)*n,(ii1(ii2)-1)*n2+1:ii1(ii2)*n2);\n end\n end\n end\n Kdd=Kddtmp;\n end\n else\n Kdf=[];\n Kdd=[];\n end\n \n % Gather all the matrices into one final matrix K which is the\n % training covariance matrix\n C = [Kff Kdf22; Kdf Kdd];\n % C = [Kff; Kdf];\n end\n if i1==1\n CC=C;\n else\n CC=CC+C;\n end\nend\nC=CC;\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/gpsvi_predgrad.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.30410675852294755}} {"text": "function S_scalar2d = poynting(varargin)\n\nchkarg(nargin == 5 || nargin == 7, 'five or seven arguments are required.')\n\niarg = 0;\niarg = iarg + 1; polarization = varargin{iarg};\nchkarg(istypesizeof(polarization, 'Axis'), '\"argument %d should be \"polarization\" (instance of Axis).', iarg);\n\nif istypesizeof(varargin{iarg+1}, 'Scalar3d')\n\tiarg = iarg + 1; Ep3d = varargin{iarg};\n\tchkarg(istypesizeof(Ep3d, 'Scalar3d'), '\"argument %d should be \"Ep3d\" (instance of Scalar3d).\"', iarg);\n\n\tiarg = iarg + 1; Eq3d = varargin{iarg};\n\tchkarg(istypesizeof(Eq3d, 'Scalar3d'), '\"argument %d should be \"Eq3d\" (instance of Scalar3d).\"', iarg);\n\n\tiarg = iarg + 1; Hp3d = varargin{iarg};\n\tchkarg(istypesizeof(Hp3d, 'Scalar3d'), '\"argument %d should be \"Hp3d\" (instance of Scalar3d).\"', iarg);\n\n\tiarg = iarg + 1; Hq3d = varargin{iarg};\n\tchkarg(istypesizeof(Hq3d, 'Scalar3d'), '\"argument %d should be \"Hq3d\" (instance of Scalar3d).\"', iarg);\n\n\tiarg = iarg + 1; normal_axis = varargin{iarg};\n\tchkarg(istypesizeof(normal_axis, 'Axis'), 'argument %d should be \"normal_axis\" (instance of Axis).', iarg);\n\n\tiarg = iarg + 1; intercept = varargin{iarg};\n\tchkarg(istypesizeof(intercept, 'real'), 'argument %d should be \"intercept\" (real).', iarg);\n\t\t\n\tchkarg(isequal(Ep3d.grid3d, Eq3d.grid3d, Hp3d.grid3d, Hq3d.grid3d), ... \n\t\t'instances of Scalar3d do not have same grid3d.');\n\t\n\t% This makes the Poynting vector calculation independnet of whether the\n\t% primary grid is the E-field grid or H-field grid, when normal_axis is\n\t% normal to p and q.\n\tEp2d = slice_scalar3d(Ep3d, normal_axis, intercept);\n\tEq2d = slice_scalar3d(Eq3d, normal_axis, intercept);\n\tHp2d = slice_scalar3d(Hp3d, normal_axis, intercept);\n\tHq2d = slice_scalar3d(Hq3d, normal_axis, intercept);\n\n\tgrid2d = Ep2d.grid2d;\nelse\n\tiarg = iarg + 1; Ep2d = varargin{iarg};\n\tchkarg(istypesizeof(Ep2d, 'Scalar2d'), '\"argument %d should be \"Ep2d\" (instance of Scalar2d).\"', iarg);\n\n\tiarg = iarg + 1; Eq2d = varargin{iarg};\n\tchkarg(istypesizeof(Eq2d, 'Scalar2d'), '\"argument %d should be \"Eq2d\" (instance of Scalar2d).\"', iarg);\n\n\tiarg = iarg + 1; Hp2d = varargin{iarg};\n\tchkarg(istypesizeof(Hp2d, 'Scalar2d'), '\"argument %d should be \"Hp2d\" (instance of Scalar2d).\"', iarg);\n\n\tiarg = iarg + 1; Hq2d = varargin{iarg};\n\tchkarg(istypesizeof(Hq2d, 'Scalar2d'), '\"argument %d should be \"Hq2d\" (instance of Scalar2d).\"', iarg);\n\t\n\t\n\tchkarg(isequal(Ep2d.grid2d, Eq2d.grid2d, Hp2d.grid2d, Hq2d.grid2d), ... \n\t\t'instances of Scalar2d do not have same grid2d.'); % Grid2d has normal_axis, so passing this test implies shared normal axis\n\tchkarg(isequal(Ep2d.intercept, Eq2d.intercept, Hp2d.intercept, Hq2d.intercept), ...\n\t\t'instances of Scalar2d do not have same intercept.');\n\n\tgrid2d = Ep2d.grid2d;\n\tnormal_axis = grid2d.normal_axis;\n\tintercept = Ep2d.intercept;\nend\n\nif polarization == normal_axis\n\tassert(all(Ep2d.gt_array==Hq2d.gt_array) && all(Eq2d.gt_array==Hp2d.gt_array));\n\n\tpi = grid2d.l{Dir.h,GT.dual};\n\tqi = grid2d.l{Dir.v,GT.dual};\n\t[PI, QI] = ndgrid(pi, qi); % centers of grid cell faces\n\n\t[ep, l1] = Ep2d.data_expanded();\n\thq = Hq2d.data_expanded(); % hq and ep have same location\n\t[eq, l2] = Eq2d.data_expanded();\n\thp = Hp2d.data_expanded(); % hp and eq have same location\n\n\tsr1 = ep .* conj(hq);\n\tsr2 = eq .* conj(hp);\n\n\t[P1, Q1] = ndgrid(l1{:}); % locations of sr1\n\t[P2, Q2] = ndgrid(l2{:}); % locations of sr2\n\n\t% Interpolate sr1 and sr2 at the centers of grid cell faces.\n\tsr1 = interpn(P1, Q1, sr1, PI, QI);\n\tsr2 = interpn(P2, Q2, sr2, PI, QI);\n\n\tarray = real(sr1 - sr2) / 2;\n\n\t% Attach extra points.\n\tfor d = Dir.elems\n\t\tarray = attach_extra_S(array, d, grid2d);\n\tend\n\n\tosc = Ep2d.osc;\n\tphysQ = PhysQ.S;\n\tgt_array = [GT.dual, GT.dual]; % face centers\nelse % polarization ~= normal_axis\n\t% To be implemented. See an attempted usage in example/2d/pc_2d_basic.m.\n\t% Note that in this case, Ep and Hq are not co-located. Neither are Eq and\n\t% Hp. (Draw their locations, and compare it with Ew2d.gt_array and\n\t% Hw2d.gt_array.)\nend\n\n% The attached values to array should be the same as the ones inside the array\n% if BC is not periodic.\nS_scalar2d = Scalar2d(array, grid2d, gt_array, osc, physQ, ['<', physQ.symbol, '_', char(polarization), '>'], intercept);\n\n\nfunction array = attach_extra_S(array, d, grid2d)\nind_n = {':', ':'};\nind_p = {':', ':'};\nbc_d = grid2d.bc(d);\nif bc_d == BC.p\n\tind_n{d} = grid2d.N(d);\n\tind_p{d} = 1;\nelse % bc_d == BC.e or BC.m\n\tind_n{d} = 1;\n\tind_p{d} = grid2d.N(d);\t\nend\narray = cat(int(d), array(ind_n{:}), array, array(ind_p{:})); % Bloch phases in S are ignored due to conj(H)\n", "meta": {"author": "wsshin", "repo": "maxwellfdfd", "sha": "f7d583813781694c8a6f0533a91f56c2a78a9ee5", "save_path": "github-repos/MATLAB/wsshin-maxwellfdfd", "path": "github-repos/MATLAB/wsshin-maxwellfdfd/maxwellfdfd-f7d583813781694c8a6f0533a91f56c2a78a9ee5/integ/poynting.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.585101139733739, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.3039725175901484}} {"text": "function slc = resampleScanSlice(scanSetF, scanSetM)\n%\n% Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team.\n% \n% This file is part of The Computational Environment for Radiotherapy Research (CERR).\n% \n% CERR development has been led by: Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy.\n% \n% CERR has been financially supported by the US National Institutes of Health under multiple grants.\n% \n% CERR is distributed under the terms of the Lesser GNU Public License. \n% \n% This version of CERR is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% CERR is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;\n% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n% See the GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with CERR. If not, see .\n\nglobal planC stateS;\nindexS = planC{end}; \n\n [xV1, yV1, zV1] = getScanXYZVals(planC{indexS.scan}(scanSetF));\n [xV2, yV2, zV2] = getScanXYZVals(planC{indexS.scan}(scanSetM));\n\n XYZRes1 = {length(xV1), length(yV1), length(zV1)};\n\n xLims1 = [min(xV1) max(xV1)];\n yLims1 = [max(yV1) min(yV1)];\n zLims1 = [min(zV1) max(zV1)];\n\n sliceXVals1 = linspace(xLims1(1), xLims1(2), XYZRes1{1});\n sliceYVals1 = linspace(yLims1(1), yLims1(2), XYZRes1{2});\n sliceZVals1 = linspace(zLims1(1), zLims1(2), XYZRes1{3});\n\n for i=1:length(sliceZVals1)\n [xM1, yM1, zM1] = meshgrid(sliceXVals1, sliceYVals1, sliceZVals1(i));\n\n %Apply transformation to the limits if necessary.\n if isfield(planC{indexS.scan}(scanSetM), 'transM')\n mat = [xM1(:) yM1(:) zM1(:) ones(prod(size(xM1)), 1)]';\n mat = inv(planC{indexS.scan}(scanSetM).transM) * mat;\n xM = mat(1,:);\n yM = mat(2,:);\n zM = mat(3,:);\n end\n\n %Find corners of scan data included in this slice.\n [minX, jnk] = findnearest(xV2, min(xM(:)));\n [jnk, maxX] = findnearest(xV2, max(xM(:)));\n [minY, jnk] = findnearest(yV2, min(yM(:)));\n [jnk, maxY] = findnearest(yV2, max(yM(:)));\n\n [minZ, jnk] = findnearest(zV2, min(zM(:)));\n [jnk, maxZ] = findnearest(zV2, max(zM(:)));\n\n %Prepare the x,y,z vector inputs for finterp3.\n xVec = [xV2(1) xV2(2)-xV2(1) xV2(end)];\n yVec = [yV2(1) yV2(2)-yV2(1) yV2(end)];\n zVec = zV2(minZ:maxZ);\n\n %Interpolate to get slice.\n im = finterp3(xM(:), yM(:), zM(:), planC{indexS.scan}(scanSetM).scanArray(maxY:minY, minX:maxX, minZ:maxZ), xVec, yVec, zVec,0);\n\n imgSize = [length(sliceYVals1) length(sliceXVals1) 1];\n im = reshape(im, imgSize);\n im = squeeze(im);\n slc(:,:,i) = im; \n end\n \nend", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/CERR_core/ImageRegistration/resampleScanSlice.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.611381973294151, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.3033028244009828}} {"text": "% Defining A Sensor Mask By Opposing Corners Example\n%\n% This example demonstrates how to define a sensor mask using the grid\n% coordinates of two opposing corners of a rectangle, and then use this for\n% the detection of the pressure field generated by an initial pressure\n% distribution within a two-dimensional homogeneous propagation medium. It\n% builds on the Homogeneous Propagation Medium and Using A Binary Sensor\n% Mask examples.\n%\n% author: Bradley Treeby\n% date: 21st August 2014\n% last update: 21st August 2014\n% \n% This function is part of the k-Wave Toolbox (http://www.k-wave.org)\n% Copyright (C) 2009-2014 Bradley Treeby and Ben Cox\n\n% This file is part of k-Wave. k-Wave is free software: you can\n% redistribute it and/or modify it under the terms of the GNU Lesser\n% General Public License as published by the Free Software Foundation,\n% either version 3 of the License, or (at your option) any later version.\n% \n% k-Wave is distributed in the hope that it will be useful, but WITHOUT ANY\n% WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n% FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for\n% more details. \n% \n% You should have received a copy of the GNU Lesser General Public License\n% along with k-Wave. If not, see . \n\nclear all;\n\n% =========================================================================\n% SIMULATION\n% =========================================================================\n\n% create the computational grid\nNx = 128; % number of grid points in the x (row) direction\nNy = 128; % number of grid points in the y (column) direction\ndx = 0.1e-3; % grid point spacing in the x direction [m]\ndy = 0.1e-3; % grid point spacing in the y direction [m]\nkgrid = makeGrid(Nx, dx, Ny, dy);\n\n% define the properties of the propagation medium\nmedium.sound_speed = 1500; \t% [m/s]\nmedium.alpha_coeff = 0.75; % [dB/(MHz^y cm)]\nmedium.alpha_power = 1.5;\n\n% create initial pressure distribution using makeDisc\ndisc_magnitude = 5; % [Pa]\ndisc_x_pos = 50; % [grid points]\ndisc_y_pos = 50; % [grid points]\ndisc_radius = 8; % [grid points]\ndisc_1 = disc_magnitude*makeDisc(Nx, Ny, disc_x_pos, disc_y_pos, disc_radius);\n\ndisc_magnitude = 3; % [Pa]\ndisc_x_pos = 80; % [grid points]\ndisc_y_pos = 60; % [grid points]\ndisc_radius = 5; % [grid points]\ndisc_2 = disc_magnitude*makeDisc(Nx, Ny, disc_x_pos, disc_y_pos, disc_radius);\n\nsource.p0 = disc_1 + disc_2;\n\n% define the first rectangular sensor region by specifying the location of\n% opposing corners\nrect1_x_start = 25;\nrect1_y_start = 31;\nrect1_x_end = 30;\nrect1_y_end = 50;\n\n% define the second rectangular sensor region by specifying the location of\n% opposing corners\nrect2_x_start = 71;\nrect2_y_start = 81;\nrect2_x_end = 80;\nrect2_y_end = 90;\n\n% assign the list of opposing corners to the sensor mask\nsensor.mask = [rect1_x_start, rect1_y_start, rect1_x_end, rect1_y_end;...\n rect2_x_start, rect2_y_start, rect2_x_end, rect2_y_end].';\n\n% run the simulation\nsensor_data = kspaceFirstOrder2D(kgrid, medium, source, sensor);\n\n% query the size of the output data - note that when using a sensor mask\n% defined using opposing corners, the output data is returned as a\n% structure\nsize(sensor_data(1).p)\nsize(sensor_data(2).p)\n\n% =========================================================================\n% VISUALISATION\n% =========================================================================\n\n% plot a time trace from the centre of each rectangle\nfigure;\nplot(squeeze(sensor_data(1).p(end/2, end/2, :)), 'r-');\nhold on;\nplot(squeeze(sensor_data(2).p(end/2, end/2, :)), 'b-');\nlegend('Trace from centre of first rectangle', 'Trace from centre of second rectangle');\nxlabel('Time Index');\nylabel('Pressure');\naxis tight;", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/K-wave/k-Wave/examples/example_ivp_opposing_corners_sensor_mask.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926665999540697, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.30327734025005837}} {"text": "function [GraphObj]=createMetIntrcNetwork(model,metAbbr,varargin)\n% Create directed metabolite-metabolite interaction network using given metabolites and the model.\n% The produced network consists of given metabolites and its first neighbours.\n% Colour and width of edges will be adjusted based on flux values If fluxes of the model are given.\n% Another metabolite-metabolite interaction network will be generated if the node is clicked;\n%\n% Left click :Generate sub-metabolite-metabolite interaction network from the created figure. \n% This functionality was added for better looking at the created network \n% and showing flux values on edges lines.\n%\n% Right click :Generate metabolite-metabolite interaction network from model. This\n% functionality was added for creating metabolite-metabolite network using\n% clicked metabolite and model.\n% The produced figure by right and left click on the main figure also \n% has same property with the main figure, and it is clickable too.\n% \n% Note : If the fluxes are not given, irreversible COBRA model structure should use for \n% representing reversible reactions. See convertToIrreversible function at github page of cobratoolbox\n% https://opencobra.github.io/cobratoolbox/stable/modules/reconstruction/refinement/\n% USAGE:\n%\n% [GraphObj]=createMetIntrcNetwork(model,metAbbr,varargin)\n%\n% INPUTS:\n%\n% model: COBRA model structure\n% metAbbr: List of metabolite abbreviation as a cell array\n%\n% OPTIONAL INPUT:\n% varargin: Optional Inputs provided as 'ParameterName', Value\n% pairs. the following parameternames are available: \n%\n% * fluxes: flux vector\n% * Graphtitle: Title for a figure as a string \n% * excludedMets: As a cell array, Metabolite abbreviations that desired for exclude \n% * nodeColour: Colour for nodes (RGB Triplet) e.g. [0 1 0]\n% see https://www.mathworks.com/help/matlab/ref/colorspec.html\n% * Hnodecolour: Colour for nodes that will be highlighted e.g. [0 1 1] \n% * scaleMin Minimum value for scaling colorbar\n% * scaleMax Maximum value for scaling colorbar\n% * nodeSize Size of Nodes\n% * HnodeSize Highlighted node size\n% * arrowSize Arrow Size\n% * threshold Treshold for edges, the edges that has the flux value\n% below the treshold will be deleted, and if the node don't\n% have any relationship with any other nodes will be deleted.\n% * excNodesWithDeg It deletes nodes that has not degree in a given range. \n% It should be given as [minimum degree maximum degree]. \n% Example, [1 50]. it deletes nodes that has lower than 1 degree \n% and higher than 50 degree.\n% \n% OUTPUT:\n% GraphObj: Matlab digraph object\n% \n%\n% EXAMPLES:\n% 1) create network with succ[c] and akg[c] \n% [GraphObj]=createMetIntrcNetwork(model,{'succ[c]','akg[c]'})\n% 2) create network with flux values\n% [GraphObj]=createMetIntrcNetwork(model,{'succ[c]','akg[c]'},'fluxes',fluxvector) \n% 3) create network with flux values, and exculude exclude very employed metabolites \n% [GraphObj]=createMetIntrcNetwork(model,{'succ[c]','akg[c]'},'fluxes',fluxvector,'excludedMets',{'atp[c]','adp[c]'})\n% 4) create network with scaling colorbar, [0 1]\n% [GraphObj]=createMetIntrcNetwork(model,{'succ[c]','akg[c]'},'fluxes',fluxvector,'excludedMets',{'atp[c]','adp[c]'},'scaleMax',1,'scaleMin',0)\n%\n% .. Author: - Kadir KOCABAS November/2020\n\n\ndefaultGraphtitle ='Metabolite-Metabolite Interaction Network';\ndefaultexcludedMets ={};\ndefaultFluxes=ones(size(model.rxns,1),1);\ndefaultnodeColour=[0.9 0.7 1];\ndefaultHnodecolour=[0 1 0];\ndefaultscaleMax=1e-6;\ndefaultscaleMin=0;\ndefaultNodeSize=15;\ndefaultHNodeSize=25;\ndefaultarrowSize=9;\ndefaultThreshold=1e-7;\ndefaultexcNodesWithDeg=[0 1e+6];\n\np = inputParser;\naddRequired(p,'model',@isstruct);\naddRequired(p,'metAbbr',@iscell);\naddParameter(p,'fluxes',defaultFluxes,@isvector);\naddParameter(p,'Graphtitle',defaultGraphtitle,@(x) isstring(x) || ischar(x));\naddParameter(p,'excludedMets',defaultexcludedMets,@iscell);\naddParameter(p,'nodeColour',defaultnodeColour,@isvector);\naddParameter(p,'Hnodecolour',defaultHnodecolour,@isvector);\naddParameter(p,'nodeSize',defaultNodeSize,@isnumeric);\naddParameter(p,'HnodeSize',defaultHNodeSize,@isnumeric);\naddParameter(p,'arrowSize',defaultarrowSize,@isnumeric);\naddParameter(p,'scaleMax',defaultscaleMax,@isnumeric);\naddParameter(p,'scaleMin',defaultscaleMin,@isnumeric);\naddParameter(p,'threshold',defaultThreshold,@isnumeric);\naddParameter(p,'excNodesWithDeg',defaultexcNodesWithDeg,@isvector);\n\nparse(p,model,metAbbr,varargin{:});\np.KeepUnmatched = true;\nmodel=p.Results.model;\nmetAbbr=p.Results.metAbbr;\nfluxes=p.Results.fluxes;\nGraphtitle=p.Results.Graphtitle;\nexcludedMets=p.Results.excludedMets;\nnodeColour=p.Results.nodeColour;\nHnodecolour=p.Results.Hnodecolour;\nscaleMin=p.Results.scaleMin;\nscaleMax=p.Results.scaleMax;\nnodeSize=p.Results.nodeSize;\nHnodeSize=p.Results.HnodeSize;\narrowSize=p.Results.arrowSize;\nthreshold=p.Results.threshold;\nexcNodesWithDeg=p.Results.excNodesWithDeg;\n\n%Controlling scale values\nif ~(scaleMax>scaleMin)\n error('scaleMax should bigger than scaleMin');\nend\n\n%controlling degre values\nif (excNodesWithDeg(1)>excNodesWithDeg(2))\n error('maximum degree should bigger or equal to minimum degree');\nend\n\n%controlling if flux vakues given\nif (sum(fluxes)==size(model.rxns,1)&all(ismember(fluxes,1))) \n fcont=1;\n \nelse\n fcont=0;\nend\n\nif ((fcont==1) & ~(scaleMax==1e-6 && scaleMin==0) )\n warning('Scales are given without giving fluxes')\nend\n\nif ~all(ismember(metAbbr,model.mets)) \n str = strjoin( metAbbr(~ismember(metAbbr,model.mets)), ' ' );\n warning(['These metabolites are not found in model : ' str])\nend\n\n%if user wants to delete edges with 0 fluxes treeshold assign 1e-5. Because\n%weight of edges with zero fluxes shown as 1e-6 since weight of edges cannot \n%be 0 in the matlab graph objects\n\nif threshold==0\n threshold=1e-5;\nend\n\n%Create table, creating table without fluxrates if fluxes are not supplied \nIndexesofMets=find(ismember(model.mets,metAbbr));\nmetMatrix=~ismember(model.S(IndexesofMets,:),0);\nRxns=model.rxns(any(metMatrix,1));\nFluxRes=fluxes(ismember(model.rxns,Rxns));\n%\n%Get sub S matrix from S matrix \nRxnsMatrx=~ismember(model.S(:,any(metMatrix,1)),0); \nInvolvedMets=model.mets(any(RxnsMatrx,2));\nadjunc_mat=model.S(any(RxnsMatrx,2),any(metMatrix,1));\n%\n%Multiply sub S matrix with flux values to keep flux value information\nFluxMatrix =FluxRes+1e-6;\nFluxMatrix = repmat(FluxMatrix',size(adjunc_mat,1),1);\nadjunc_mat=adjunc_mat.*FluxMatrix;\n\n%Create left and right matrix( left matrix : comsumed metabolites, righ matrix:\n%produced metabolites)\nleftMatrix=adjunc_mat;\nleftMatrix(leftMatrix > 0)=0;\nrightMatrix=adjunc_mat;\nrightMatrix(rightMatrix < 0)=0;\nrightMatrix(rightMatrix > 0)=1;\n\n%create adjacency matrix\nA=(leftMatrix*rightMatrix')*(-1);\n\n%Delete metabolites that is not first neighbour of metAbbr \nidx=ismember(InvolvedMets,metAbbr);\nnewadjMtrx=zeros(size(A));\nnewadjMtrx(idx,:)=A(idx,:);\nnewadjMtrx(:,idx)=A(:,idx);\nrows=any(newadjMtrx,1);\ncols=any(newadjMtrx,2);\nindofMets=rows'|cols;\nmetnames=InvolvedMets(indofMets);\nnewadjMtrx=newadjMtrx(indofMets,indofMets);\nA=newadjMtrx;\n\n%create graph object.\nG = digraph(A,metnames);\n\nGraphObj=G;\nexcludedMets=excludedMets(~ismember(excludedMets,metAbbr));\n\n%Exclude given metabolites\nG=rmnode(G,excludedMets);\n\nif threshold~=1e-7 \n edesBelowTresholdIdx=find(G.Edges.Weight maxDegree)\n error('There is no node with degree in the given range')\nend\n\nG=rmnode(G,find(totalDegreemaxDegree ));\n\n\nfigure;\nhold on\n\n%chech if there is a edge in the network\nif ~isempty(G.Edges.Weight) \n G.Edges.LWidths = (G.Edges.Weight-min(G.Edges.Weight))/(max(G.Edges.Weight)-min(G.Edges.Weight))+0.00001;\n edgeCont=true;\nelse\n warning('There is no edges in the Network');\n edgeCont=false;\nend\n\n%create plot\nh=plot(G,'MarkerSize',nodeSize,'NodeColor',nodeColour,'ArrowSize',arrowSize,'NodeLabelMode','auto','Layout','force','UseGravity',true);\nmetAbbr=metAbbr(ismember(metAbbr,G.Nodes.Name));\nhighlight(h,metAbbr,'NodeColor',Hnodecolour,'MarkerSize',HnodeSize);\n\nnl = h.NodeLabel;\nh.NodeLabel = '';\nxd = get(h, 'XData');\nyd = get(h, 'YData');\ntitle(Graphtitle,'Interpreter', 'none');\ntxt=text(xd, yd, nl, 'FontSize',8, 'FontWeight','bold', 'HorizontalAlignment','center', 'VerticalAlignment','middle');\nset(txt,'Interpreter', 'none');\n%Define function for texts \nset(txt,'ButtonDownFcn',{@hit_node,A,metnames,model,fluxes,excludedMets,Graphtitle,nodeColour,Hnodecolour,fcont,scaleMin,scaleMax,nodeSize,HnodeSize,arrowSize,threshold,excNodesWithDeg});\n\n%define color and width of edges if fluxes are given \nif edgeCont % control if there is edge in the network\n if fcont==1\n h.LineWidth=1;\n elseif ~any(isnan(G.Edges.LWidths)) \n h.LineWidth=G.Edges.LWidths*2.5;\n colormap jet(10)\n h.EdgeCData=G.Edges.Weight; \n hcb=colorbar;\n colorTitleHandle = get(hcb,'Title');\n else \n h.LineWidth=1;\n colormap jet(10)\n h.EdgeCData=G.Edges.Weight; \n hcb=colorbar;\n colorTitleHandle = get(hcb,'Title');\n\n end \n\n if fcont==0\n if ~(scaleMax==1e-6 && scaleMin==0) \n caxis([scaleMin scaleMax])\n titleBar = ['Scaled Fluxes',' ', '(', num2str(scaleMin),' - ',num2str(scaleMax),')'];\n set(colorTitleHandle ,'String',titleBar,'FontWeight','Bold');\n else\n set(colorTitleHandle ,'String','Fluxes','FontWeight','Bold');\n end\n end\nend\n\nset(gca,'XTickLabel',{' '});\nset(gca,'YTickLabel',{' '});\nset(gca,'YTick',[]);\nset(gca,'XTick',[]);\nset(gca,'XColor', 'none','YColor','none');\nend", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/src/visualization/createMetIntrcNetwork/createMetIntrcNetwork.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5964331319177487, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.30287582063703666}} {"text": "function trainingModel = loadTrainingData(param)\n% Generates the structure that contains all the training data needed for\n% Component Contribution.\n%\n% USAGE:\n%\n% trainingModel = loadTrainingData(formation_weight)\n%\n% INPUT:\n% formation_weight: the relative weight to give the formation energies (Alberty's data)\n% compared to the reaction measurements (TECRDB)\n%\n% OUTPUT:\n% trainingModel: structure with data for Component Contribution\n% *.S `m x n` stoichiometric matrix of training data\n% *.cids: `m x 1` compound ids\n% *.dG0_prime: `n x 1`\n% *.T: `n x 1`\n% *.I: `n x 1`\n% *.pH: `n x 1`\n% *.pMg: `n x 1`\n% *.weights: `n x 1`\n% *.balance: `n x 1`\n% *.cids_that_dont_decompose: k x 1 ids of compounds that do not decompose\n\nif ~exist('param','var')\n formation_weight = 1;\n use_cached_kegg_inchis=true;\n use_model_pKas_by_default=true;\nelse\n if ~isfield(param,'formation_weight')\n formation_weight = 1;\n end\n if ~isfield(params,'use_cached_kegg_inchis')\n use_cached_kegg_inchis = true;\n % use_cached_kegg_inchis = false;\n else\n use_cached_kegg_inchis=params.use_cached_kegg_inchis;\n end\n if ~isfield(params,'use_model_pKas_by_default')\n use_model_pKas_by_default = true;\n else\n use_model_pKas_by_default=params.use_model_pKas_by_default;\n end\nend\n\nTECRDB_TSV_FNAME = 'data/TECRDB.tsv';\nFORMATION_TSV_FNAME = 'data/formation_energies_transformed.tsv';\nREDOX_TSV_FNAME = 'data/redox.tsv';\n\nWEIGHT_TECRDB = 1;\nWEIGHT_FORMATION = formation_weight;\nWEIGHT_REDOX = formation_weight;\n\nR=8.31451;\n%Energies are expressed in kJ mol^-1.*)\nR=R/1000; % kJ/mol/K\n%Faraday Constant (kJ/mol)\nF=96.48; %kJ/mol\n\nif ~exist(TECRDB_TSV_FNAME, 'file')\n error(['file not found: ', TECRDB_TSV_FNAME]);\nend\n\nif ~exist(FORMATION_TSV_FNAME, 'file')\n error(['file not found: ', FORMATION_TSV_FNAME]);\nend\n\nif ~exist(REDOX_TSV_FNAME, 'file')\n error(['file not found: ', REDOX_TSV_FNAME]);\nend\n\n% Read the raw data of TECRDB (NIST)\nreactions = {};\nrxns={};\ncids = [];\ncids_that_dont_decompose = [];\nthermo_params = []; % columns are: dG'0, T, I, pH, pMg, weight, balance?\n\n\nfid = fopen(TECRDB_TSV_FNAME, 'r');\n% fields are: \n% 1. URL\n% 2. REF_ID\n% 3. METHOD\n% 4. EVAL\n% 5. EC\n% 6. ENZYME NAME\n% 7. REACTION IN KEGG IDS\n% 8. REACTION IN COMPOUND NAMES\n% 9. K\n% 10. K'\n% 11. T\n% 12. I\n% 13. pH\n% 14. pMg\n% 15. ID\n\nres = textscan(fid, '%s%s%s%s%s%s%s%s%f%f%f%f%f%f%f', 'delimiter','\\t');\nfclose(fid);\n\ninds = find(~isnan(res{10}) .* ~isnan(res{11}) .* ~isnan(res{13}));\n\ndG0_prime = -R * res{11}(inds) .* log(res{10}(inds)); % calculate dG'0\nthermo_params = [dG0_prime, res{11}(inds), res{12}(inds), res{13}(inds), ...\n res{14}(inds), WEIGHT_TECRDB * ones(size(inds)), ...\n true(size(inds))];\n\n% parse the reactions in each row\nfor i = 1:length(inds)\n sprs = reaction2sparse(res{7}{inds(i)});\n cids = unique([cids, find(sprs)]);\n reactions = [reactions, {sprs}];\n rxns = [rxns;strtrim(['TECRDB_' int2str(res{15}(inds(i)))])];\n if strcmp('TECRDB_4403',strtrim(['TECRDB_' int2str(res{15}(inds(i)))]))\n pause(0.1);\n end\nend\nfprintf('Successfully added %d values from TECRDB\\n', length(inds));\n\n% Read the Formation Energy data.\nfid = fopen(FORMATION_TSV_FNAME, 'r');\nfgetl(fid); % skip the first header line\n% fields are: \n% 1. cid\n% 2. name\n% 3. dG'0\n% 4. pH\n% 5. I\n% 6. pMg\n% 7. T\n% 8. decompose?\n% 9. compound_ref\n% 10. remark\n\nres = textscan(fid, '%f%s%f%f%f%f%f%f%s%s', 'delimiter','\\t');\nfclose(fid);\n\ninds = find(~isnan(res{3}));\nthermo_params = [thermo_params; [res{3}(inds), res{7}(inds), res{5}(inds), ...\n res{4}(inds), res{6}(inds), ...\n WEIGHT_FORMATION * ones(size(inds)), ...\n false(size(inds))]];\n \neval(['cid = {' regexprep(sprintf('''C%05d''; ',res{1}),'(;\\s)$','') '};']);\nfor i = 1:length(inds)\n sprs = sparse([]);\n sprs(res{1}(inds(i))) = 1;\n reactions = [reactions, {sprs}];\n rxns = [rxns;['FORM_' cid{i}]];\nend\n\ncids = union(cids, res{1}');\ncids_that_dont_decompose = res{1}(find(res{8} == 0));\n\nfprintf('Successfully added %d formation energies\\n', length(res{1}));\n\n\n% Read the Reduction potential data.\nfid = fopen(REDOX_TSV_FNAME, 'r');\nfgetl(fid); % skip the first header line\n% fields are: \n% 1. name\n% 2. CID_ox\n% 3. nH_ox\n% 4. charge_ox\n% 5. CID_red\n% 6. nH_red,\n% 7. charge_red\n% 8. E'0\n% 9. pH\n% 10. I\n% 11. pMg\n% 12. T\n% 13. ref\nres = textscan(fid, '%s%f%f%f%f%f%f%f%f%f%f%f%s', 'delimiter', '\\t');\nfclose(fid);\n\ndelta_e = (res{6} - res{3}) - (res{7} - res{4}); % delta_nH - delta_charge\ndG0_prime = -F * res{8} .* delta_e;\nthermo_params = [thermo_params; [dG0_prime, res{12}, res{10}, res{9}, ...\n res{11}, ...\n WEIGHT_REDOX * ones(size(dG0_prime)), ...\n false(size(dG0_prime))]];\n\nfor i = 1:length(res{1})\n sprs = sparse([]);\n sprs(res{2}(i)) = -1;\n sprs(res{5}(i)) = 1;\n cids = unique([cids, res{2}(i), res{5}(i)]);\n reactions = [reactions, {sprs}];\n rxns = [rxns;['REDOX_' strrep(res{1}{i},' ','_')]];\nend\n\nfprintf('Successfully added %d redox potentials\\n', length(res{1}));\n\n% convert the list of reactions in sparse notation into a full\n% stoichiometric matrix, where the rows (compounds) are according to the\n% CID list 'cids'.\nS = zeros(length(cids), length(reactions));\nfor i = 1:length(reactions)\n r = reactions{i};\n S(ismember(cids, find(r)), i) = r(r ~= 0);\n %production of h20 in certain redox reactions\n if any(strcmp(rxns{i},{'REDOX_dimethyl_sulfoxide';'REDOX_Trimethylamine'}))\n S(cids==1,i)=1;\n end\nend\n\ntrainingModel.S = sparse(S);\n\nif ~isfield(trainingModel,'rxns')\n for i=1:size(trainingModel.S,2)\n trainingModel.rxns{i,1}=['rxn' int2str(i)];\n end\nend\nif ~isfield(trainingModel,'lb')\n trainingModel.lb=ones(size(trainingModel.S,2),1)*-inf;\nend\nif ~isfield(trainingModel,'ub')\n trainingModel.ub=ones(size(trainingModel.S,2),1)*inf;\nend\n\ntrainingModel.rxns = rxns;\ntrainingModel.cids = cids';\ntrainingModel.dG0_prime = thermo_params(:, 1);\ntrainingModel.T = thermo_params(:, 2);\ntrainingModel.I = thermo_params(:, 3);\ntrainingModel.pH = thermo_params(:, 4);\ntrainingModel.pMg = thermo_params(:, 5);\ntrainingModel.weights = thermo_params(:, 6);\ntrainingModel.balance = thermo_params(:, 7);\ntrainingModel.cids_that_dont_decompose = cids_that_dont_decompose;\n\n%remove some problematic entries\nboolRemove=false(size(trainingModel.rxns,1),1);\n\n%http://xpdb.nist.gov/enzyme_thermodynamics/enzyme_data1.pl?col=1.&T1=66DED_421\tC00089 + C06215 = C00031 + C06215\tsucrose(aq) + (2,6--D-fructosyl)n(aq) = D-glucose(aq) + (2,6--D-fructosyl)n+1(aq)\n%C06215 present on both sides of the reaction\n%Need proper ID's for (2,6--D-fructosyl)n(aq) and (2,6--D-fructosyl)n+1(aq)\nboolRemove = boolRemove | ismember(trainingModel.rxns,'TECRDB_695');\n\n% http://xpdb.nist.gov/enzyme_thermodynamics/enzyme_data1.pl?col=1.&T1=93AND/BUL_1509\t93AND/BUL\tradioactivity\tB\t2.3.1.129\tUDP-N-acetylglucosamine acyltransferase\tC04688 + C00043 = C03688 + C04738\t(R)-3-hydroxytetradecanoyl-[acyl-carrier-protein](aq) + UDP-N-acetyl-D-glucosamine(aq) = acyl-carrier-protein(aq) + UDP-3-O-(3-hydroxytetradecanoyl)-N-acetyl-D-glucosamine(aq)\t\t0.007\t296.15\t\t7.4\t\t2905\n% http://xpdb.nist.gov/enzyme_thermodynamics/enzyme_data1.pl?col=1.&T1=93AND/BUL_1509\t93AND/BUL\tradioactivity\tB\t2.3.1.129\tUDP-N-acetylglucosamine acyltransferase\tC04688 + C00043 = C03688 + C04738\t(R)-3-hydroxytetradecanoyl-[acyl-carrier-protein](aq) + UDP-N-acetyl-D-glucosamine(aq) = acyl-carrier-protein(aq) + UDP-3-O-(3-hydroxytetradecanoyl)-N-acetyl-D-glucosamine(aq)\t\t0.004\t296.15\t\t8.5\t\t2906\n% http://xpdb.nist.gov/enzyme_thermodynamics/enzyme_data1.pl?col=1.&T1=93AND/BUL_1509\t93AND/BUL\tradioactivity\tB\t2.3.1.129\tUDP-N-acetylglucosamine acyltransferase\tC04688 + C00043 = C03688 + C04738\t(R)-3-hydroxytetradecanoyl-[acyl-carrier-protein](aq) + UDP-N-acetyl-D-glucosamine(aq) = acyl-carrier-protein(aq) + UDP-3-O-(3-hydroxytetradecanoyl)-N-acetyl-D-glucosamine(aq)\t\t0.002\t296.15\t\t9\t\t2907\n% http://xpdb.nist.gov/enzyme_thermodynamics/enzyme_data1.pl?col=1.&T1=93AND/BUL_1509\t93AND/BUL\tradioactivity\tB\t2.3.1.129\tUDP-N-acetylglucosamine acyltransferase\tC04688 + C00043 = C03688 + C04738\t(R)-3-hydroxytetradecanoyl-[acyl-carrier-protein](aq) + UDP-N-acetyl-D-glucosamine(aq) = acyl-carrier-protein(aq) + UDP-3-O-(3-hydroxytetradecanoyl)-N-acetyl-D-glucosamine(aq)\t\t0.0095\t296.15\t\t8\t\t2908\nboolRemove = boolRemove | ismember(trainingModel.rxns,'TECRDB_2905');\nboolRemove = boolRemove | ismember(trainingModel.rxns,'TECRDB_2906');\nboolRemove = boolRemove | ismember(trainingModel.rxns,'TECRDB_2907');\nboolRemove = boolRemove | ismember(trainingModel.rxns,'TECRDB_2908');\n\n%These were missing water on the rhs, fixed in TECRDB.tsv\n%TECRDB_4540 85LIE\t\tA\t4.3.-.-\tformaldehyde condensation with THF\tC00101 + C00067 = C00143 + C00001\tTHF(aq) + formaldehyde(aq) = 5,10-CH2-THF(aq) + H2O(l)\t\t30000\t311.15\t0.25\t7\t\t4540\n%TECRDB_4541 +66KAL/JEN\t\tE\t4.3.-.-\tformaldehyde condensation with THF\tC00101 + C00067 = C00143 + C00001\tTHF(aq) + formaldehyde(aq) = 5,10-CH2-THF(aq) + H2O(l)\t\t32000\t298.15\t1\t7\t\t4541\n%TECRDB_4544 +59BLA\t\tE\t4.3.-.-\tformaldehyde condensation with THF\tC00101 + C00067 = C00143 + C00001\tTHF(aq) + formaldehyde(aq) = 5,10-CH2-THF(aq)\t\t7700\t293.15\t\t7.2\t\t4544\n\n%The record of 85LIE is problematic i.e. TECRDB_870 - TECRDB_884\n%e.g. http://xpdb.nist.gov/enzyme_thermodynamics/enzyme_data1.pl?col=1.&T1=85LIE_292\t85LIE\tspectrophotometry and enzymatic assay\tA\t1.4.4.2\tglycine dehydrogenase (decarboxylating)\tC00037 + C00725 = C80069 + C00288\tglycine(aq) + lipoate(aq) = S-aminomethyldihydro--lipoate(aq) + carbon dioxide(aq)\t\t0.031\t311.15\t\t6.39\t\t870\n%is C00725 really C00248 ???\n%C80069 is InChI=1S/C9H19NO2S2/c10-7-14-6-5-8(13)3-1-2-4-9(11)12/h8,13H,1-7,10H2,(H,11,12)\n%C80069\tbut is it InChI=1S/C9H20N2OS2/c10-7-14-6-5-8(13)3-1-2-4-9(11)12/h8,13H,1-7,10H2,(H2,11,12)/p+1 ???\nboolRemove = boolRemove | ismember(trainingModel.rxns,'TECRDB_870');\nboolRemove = boolRemove | ismember(trainingModel.rxns,'TECRDB_871');\nboolRemove = boolRemove | ismember(trainingModel.rxns,'TECRDB_872');\nboolRemove = boolRemove | ismember(trainingModel.rxns,'TECRDB_873');\nboolRemove = boolRemove | ismember(trainingModel.rxns,'TECRDB_874');\nboolRemove = boolRemove | ismember(trainingModel.rxns,'TECRDB_875');\nboolRemove = boolRemove | ismember(trainingModel.rxns,'TECRDB_876');\nboolRemove = boolRemove | ismember(trainingModel.rxns,'TECRDB_877');\nboolRemove = boolRemove | ismember(trainingModel.rxns,'TECRDB_878');\nboolRemove = boolRemove | ismember(trainingModel.rxns,'TECRDB_879');\nboolRemove = boolRemove | ismember(trainingModel.rxns,'TECRDB_880');\nboolRemove = boolRemove | ismember(trainingModel.rxns,'TECRDB_881');\nboolRemove = boolRemove | ismember(trainingModel.rxns,'TECRDB_882');\nboolRemove = boolRemove | ismember(trainingModel.rxns,'TECRDB_883');\nboolRemove = boolRemove | ismember(trainingModel.rxns,'TECRDB_884');\n% The overall reaction reported in the abstract of the dissertation (https://digitalcommons.library.tmc.edu/dissertations/AAI8516325/) is as follows:\n%85LIE\t\tA\t1.1.-.-\tglycine cleavage system (a series of enzymes)\tC00037 + C00003 + C00101 = C00143 + C00004 + C00014 + C00011 \tglycine(aq) + NAD+(aq) + THF(aq) = 5,10-CH2-THF(aq) + NADH(aq) + NH3(aq) + CO2(aq)\t\t0.00156\t311.15\t0.25\t7\t\t4539\n\n%http://xpdb.nist.gov/enzyme_thermodynamics/enzyme_data1.pl?col=1.&T1=65STR_520\t65STR\tspectrophotometry\tC\t2.6.1.13\tornithine-oxo-acid transaminase\tC00077 + C00026 = C03912 + C00025\tL-ornithine(aq) + 2-oxoglutarate(aq) = DL-D-1-pyrroline-5-carboxylate(aq) + L-glutamate(aq)\t\t71\t310.15\t\t7.1\t\t2719\n%is http://xpdb.nist.gov/enzyme_thermodynamics/enzyme_data1.pl?col=1.&T1=65STR_520\t65STR\tspectrophotometry\tC\t2.6.1.13\tornithine-oxo-acid transaminase\tC00077 + C00026 = C01165 + C00025 + C00001\tL-ornithine(aq) + 2-oxoglutarate(aq) = DL-D-1-pyrroline-5-carboxylate(aq) + L-glutamate(aq)\t\t71\t310.15\t\t7.1\t\t2719\n%i.e. C00001 added to rhs, it is balanced, but is this correct?\n\n%85LIE\t\tA\t1.1.-.-\tglycine cleavage system\tC00037 + C00003 + C00101 = C00143 + C00004 + C00014 + C00288 \tglycine(aq) + NAD+(aq) + THF(aq) = 5,10-CH2-THF(aq) + NADH(aq) + NH3(aq) + CO2(aq)\t\t0.00156\t311.15\t0.25\t7\t\t4539\n%is 85LIE\t\tA\t1.1.-.-\tglycine cleavage system\tC00037 + C00003 + C00101 = C00143 + C00004 + C00014 + C00011 \tglycine(aq) + NAD+(aq) + THF(aq) = 5,10-CH2-THF(aq) + NADH(aq) + NH3(aq) + CO2(aq)\t\t0.00156\t311.15\t0.25\t7\t\t4539\n%i.e. C00288 replaced by C00011\n\n%http://xpdb.nist.gov/enzyme_thermodynamics/enzyme_data1.pl?col=1.&T1=07LIN/ALG_1584\t07LIN/ALG\tspectrophotometry\tA\t1.1.1.87\thomoisocitrate dehydrogenase\t C05662 + C00003 = C00322 + C00288 + C00004\t(1R,2S)-1-hydroxybutane-1,2,4-tricarboxylate(aq) + NAD(ox) = 2-oxoadipate(aq) + carbon dioxide(aq) + NAD(red)\t\t0.45\t298.15\t\t7.5\t\t1\n%is http://xpdb.nist.gov/enzyme_thermodynamics/enzyme_data1.pl?col=1.&T1=07LIN/ALG_1584\t07LIN/ALG\tspectrophotometry\tA\t1.1.1.87\thomoisocitrate dehydrogenase\tC00001 + C05662 + C00003 = C00322 + C00288 + C00004\tH2O(l) + (1R,2S)-1-hydroxybutane-1,2,4-tricarboxylate(aq) + NAD(ox) = 2-oxoadipate(aq) + carbon dioxide(aq) + NAD(red)\t\t0.45\t298.15\t\t7.5\t\t1\n%i.e. lhs missing h20\n\n%http://xpdb.nist.gov/enzyme_thermodynamics/enzyme_data1.pl?col=1.&T1=95PEL/MAC_1595\t95PEL/MAC\tspectrophotometry and enzymatic assay\tB\t1.5.1.5\tmethylenetetrahydrofolate dehydrogenase (NADP+)\tC00143 + C00006 = C00234 + C00005\t5,10-methylenetetrahydrofolate(aq) + NADP(ox)(aq) = 10-formyltetrahydrofolate(aq) + NADP(red)(aq)\t\t16\t303.15\t\t7.3\t\t267\n%is http://xpdb.nist.gov/enzyme_thermodynamics/enzyme_data1.pl?col=1.&T1=95PEL/MAC_1595\t95PEL/MAC\tspectrophotometry and enzymatic assay\tB\t1.5.1.5\tmethylenetetrahydrofolate dehydrogenase (NADP+)\tC00001 + C00143 + C00006 = C00234 + C00005\tH2O(l) + 5,10-methylenetetrahydrofolate(aq) + NADP(ox)(aq) = 10-formyltetrahydrofolate(aq) + NADP(red)(aq)\t\t16\t303.15\t\t7.3\t\t267\n%i.e. lhs missing h20\n\n%remove some of the training reactions that are problematic, e.g. those involving ACP\ntrainingModel.S = trainingModel.S(:,~boolRemove);\ntrainingModel.lb = trainingModel.lb(~boolRemove);\ntrainingModel.ub = trainingModel.ub(~boolRemove);\ntrainingModel.rxns = trainingModel.rxns(~boolRemove);\ntrainingModel.dG0_prime = trainingModel.dG0_prime(~boolRemove);\ntrainingModel.T = trainingModel.T(~boolRemove);\ntrainingModel.I = trainingModel.I(~boolRemove);\ntrainingModel.pH = trainingModel.pH(~boolRemove);\ntrainingModel.pMg = trainingModel.pMg(~boolRemove);\ntrainingModel.weights = trainingModel.weights(~boolRemove);\ntrainingModel.balance = trainingModel.balance(~boolRemove);\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/src/analysis/thermo/trainingModel/new/loadTrainingData.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.66192288918838, "lm_q2_score": 0.45713671682749485, "lm_q1q2_score": 0.30258925635654577}} {"text": "function [stat] = ft_spike_xcorr(cfg, spike)\n\n% FT_SPIKE_XCORR computes the cross-correlation histogram and shift predictor.\n%\n% Use as\n% [stat] = ft_spike_xcorr(cfg, data)\n%\n% The input SPIKE should be organised as the spike or the raw datatype, obtained from\n% FT_SPIKE_MAKETRIALS or FT_PREPROCESSING (in that case, conversion is done\n% within the function). A mex file is located in /contrib/spike/private\n% which will be automatically mexed.\n%\n% Configurations options for xcorr general:\n% cfg.maxlag = number in seconds, indicating the maximum lag for the\n% cross-correlation function in sec (default = 0.1 sec).\n% cfg.debias = 'yes' (default) or 'no'. If 'yes', we scale the\n% cross-correlogram by M/(M-abs(lags)), where M = 2*N -1 with N\n% the length of the data segment.\n% cfg.method = 'xcorr' or 'shiftpredictor'. If 'shiftpredictor'\n% we do not compute the normal cross-correlation\n% but shuffle the subsequent trials.\n% If two channels are independent, then the shift\n% predictor should give the same correlogram as the raw\n% correlogram calculated from the same trials.\n% Typically, the shift predictor is subtracted from the\n% correlogram.\n% cfg.outputunit = - 'proportion' (value in each bin indicates proportion of occurence)\n% - 'center' (values are scaled to center value which is set to 1)\n% - 'raw' (default) unnormalized crosscorrelogram.\n% cfg.binsize = [binsize] in sec (default = 0.001 sec).\n% cfg.channelcmb = Mx2 cell-array with selection of channel pairs (default = {'all' 'all'}),\n% see FT_CHANNELCOMBINATION for details\n% cfg.latency = [begin end] in seconds, 'max' (default), 'min', 'prestim'(t<=0), or\n% 'poststim' (t>=0).%\n% cfg.vartriallen = 'yes' (default) or 'no'.\n% If 'yes' - accept variable trial lengths and use all available trials\n% and the samples in every trial.\n% If 'no' - only select those trials that fully cover the window as\n% specified by cfg.latency and discard those trials that do not.\n% if cfg.method = 'yes', then cfg.vartriallen\n% should be 'no' (otherwise, fewer coincidences\n% will occur because of non-overlapping windows)\n% cfg.trials = numeric selection of trials (default = 'all')\n% cfg.keeptrials = 'yes' or 'no' (default)\n%\n% A peak at a negative lag for stat.xcorr(chan1,chan2,:) means that chan1 is leading\n% chan2. Thus, a negative lag represents a spike in the second dimension of\n% stat.xcorr before the channel in the third dimension of stat.stat.\n%\n% Variable trial length is controlled by the option cfg.vartriallen. If it is\n% specified as cfg.vartriallen='yes', all trials are selected that have a minimum\n% overlap with the latency window of cfg.maxlag. However, the shift predictor\n% calculation demands that following trials have the same amount of data, otherwise,\n% it does not control for rate non-stationarities. If cfg.vartriallen = 'yes', all\n% trials should fall in the latency window, otherwise we do not compute the shift\n% predictor.\n%\n% Output:\n% stat.xcorr = nchans-by-nchans-by-(2*nlags+1) cross correlation histogram with dimord 'chan_chan_time'\n% or\n% stat.shiftpredictor = nchans-by-nchans-by-(2*nlags+1) shift predictor with dimord 'chan_chan_time'\n% and\n% stat.lags = (2*nlags + 1) vector with lags in seconds.\n% stat.trial = ntrials-by-nchans-by-nchans-by-(2*nlags + 1) with single trials and dimord 'rpt_chan_chan_time'\n% stat.label = corresponding labels to channels in stat.xcorr\n% stat.cfg = configurations used in this function\n\n% Copyright (C) 2010-2012, Martin Vinck\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% 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 provenance spike\n\n\n% check input spike structure\nspike = ft_checkdata(spike, 'datatype', 'spike', 'feedback', 'yes');\n\n% get the default options\ncfg.trials = ft_getopt(cfg, 'trials', 'all');\ncfg.latency = ft_getopt(cfg, 'latency','maxperiod');\ncfg.keeptrials = ft_getopt(cfg, 'keeptrials', 'no');\ncfg.method = ft_getopt(cfg, 'method', 'xcorr');\ncfg.channelcmb = ft_getopt(cfg, 'channelcmb', 'all');\ncfg.vartriallen = ft_getopt(cfg, 'vartriallen', 'yes');\ncfg.debias = ft_getopt(cfg, 'debias', 'yes');\ncfg.maxlag = ft_getopt(cfg, 'maxlag', 0.01);\ncfg.binsize = ft_getopt(cfg, 'binsize', 0.001);\ncfg.outputunit = ft_getopt(cfg, 'outputunit', 'proportion');\n\n% ensure that the options are valid\ncfg = ft_checkopt(cfg, 'latency', {'char', 'ascendingdoublebivector'});\ncfg = ft_checkopt(cfg, 'trials', {'char', 'doublevector', 'logical'});\ncfg = ft_checkopt(cfg, 'keeptrials', 'char', {'yes', 'no'});\ncfg = ft_checkopt(cfg, 'method', 'char', {'xcorr', 'shiftpredictor'});\ncfg = ft_checkopt(cfg, 'channelcmb', {'char', 'cell'});\ncfg = ft_checkopt(cfg, 'vartriallen', 'char', {'no', 'yes'});\ncfg = ft_checkopt(cfg, 'debias', 'char', {'yes', 'no'});\ncfg = ft_checkopt(cfg, 'maxlag', 'doublescalar');\ncfg = ft_checkopt(cfg, 'binsize', 'doublescalar');\ncfg = ft_checkopt(cfg, 'outputunit', 'char', {'proportion', 'center', 'raw'});\n\ncfg = ft_checkconfig(cfg, 'allowed', {'latency', 'trials', 'keeptrials', 'method', 'channelcmb', 'vartriallen', 'debias', 'maxlag', 'binsize', 'outputunit'});\n\ndoShiftPredictor = strcmp(cfg.method, 'shiftpredictor'); % shift predictor\n\n% determine the corresponding indices of the requested channel combinations\ncfg.channelcmb = ft_channelcombination(cfg.channelcmb, spike.label(:), true);\ncmbindx = zeros(size(cfg.channelcmb));\nfor k=1:size(cfg.channelcmb,1)\n cmbindx(k,1) = strmatch(cfg.channelcmb(k,1), spike.label, 'exact');\n cmbindx(k,2) = strmatch(cfg.channelcmb(k,2), spike.label, 'exact');\nend\nnCmbs \t = size(cmbindx,1);\nchansel = unique(cmbindx(:)); % get the unique channels\nnChans = length(chansel);\nif isempty(chansel), error('No channel was selected'); end\n\n% get the number of trials or change SPIKE according to cfg.trials\nnTrials = size(spike.trialtime,1);\nif strcmp(cfg.trials,'all')\n cfg.trials = 1:nTrials;\nelseif islogical(cfg.trials) || all(cfg.trials==0 | cfg.trials==1)\n cfg.trials = find(cfg.trials);\nend\ncfg.trials = sort(cfg.trials(:));\nif max(cfg.trials)>nTrials, error('maximum trial number in cfg.trials should not exceed length of DATA.trial'); end\nif isempty(cfg.trials), errors('No trials were selected in cfg.trials'); end\nnTrials = length(cfg.trials);\n\n% get the latencies\nbegTrialLatency = spike.trialtime(cfg.trials,1);\nendTrialLatency = spike.trialtime(cfg.trials,2);\ntrialDur = endTrialLatency - begTrialLatency;\n\n% select the latencies\nif strcmp(cfg.latency,'minperiod')\n cfg.latency = [max(begTrialLatency) min(endTrialLatency)];\nelseif strcmp(cfg.latency,'maxperiod')\n cfg.latency = [min(begTrialLatency) max(endTrialLatency)];\nelseif strcmp(cfg.latency,'prestim')\n cfg.latency = [min(begTrialLatency) 0];\nelseif strcmp(cfg.latency,'poststim')\n cfg.latency = [0 max(endTrialLatency)];\nend\n\n% check whether the time window fits with the data\nif (cfg.latency(1) < min(begTrialLatency)), cfg.latency(1) = min(begTrialLatency);\n warning('Correcting begin latency of averaging window');\nend\nif (cfg.latency(2) > max(endTrialLatency)), cfg.latency(2) = max(endTrialLatency);\n warning('Correcting begin latency of averaging window');\nend\n\n% get the maximum number of lags in samples\nfsample = (1/cfg.binsize);\nif cfg.maxlag>(cfg.latency(2)-cfg.latency(1))\n warning('Correcting cfg.maxlag since it exceeds latency period');\n cfg.maxlag = (cfg.latency(2) - cfg.latency(1));\nend\nnLags = round(cfg.maxlag*fsample);\nlags = (-nLags:nLags)/fsample; % create the lag axis\n\n% check which trials will be used based on the latency\nfullDur = trialDur>=(cfg.maxlag); % only trials which are larger than maximum lag\noverlaps = endTrialLatency>(cfg.latency(1)+cfg.maxlag) & begTrialLatency<(cfg.latency(2)-cfg.maxlag);\nhasWindow = ones(nTrials,1);\nif strcmp(cfg.vartriallen,'no') % only select trials that fully cover our latency window\n startsLater = single(begTrialLatency) > (single(cfg.latency(1)) + 0.5*cfg.binsize);\n endsEarlier = single(endTrialLatency) < (single(cfg.latency(2)) - 0.5*cfg.binsize);\n hasWindow = ~(startsLater | endsEarlier); % check this in all other funcs\nend\ntrialSel = fullDur(:) & overlaps(:) & hasWindow(:);\ncfg.trials = cfg.trials(trialSel);\nbegTrialLatency = begTrialLatency(trialSel);\nendTrialLatency = endTrialLatency(trialSel);\n\nif isempty(cfg.trials), warning('No trials were selected'); end\nif length(cfg.trials)<2&&doShiftPredictor\n error('Shift predictor can only be calculated with more than 1 selected trial.');\nend\n\n% if we allow variable trial lengths\nif strcmp(cfg.vartriallen,'yes') && doShiftPredictor && ~strcmp(cfg.outputunit,'proportion')\n warning('using cfg.vartriallen = \"yes\" and shift predictor method: please use cfg.outputunit = \"proportion\"');\nend\nnTrials = length(cfg.trials); % only now reset nTrials\n\n% preallocate the sum and the single trials and the shift predictor\nkeepTrials = strcmp(cfg.keeptrials,'yes');\ns = zeros(nChans,nChans,2*nLags);\nif keepTrials\n warning('storing single trials for cross correlation is memory expensive, please check');\n singleTrials = zeros(nTrials,nChans,nChans,2*nLags);\nend\n\nif strcmp(cfg.method,'shiftpredictor'), singleTrials(1,:,:,:) = NaN; end\n\nif ((cfg.latency(2)-cfg.latency(1))/cfg.maxlag)<2.5\n warning('selected latency will cause highly variable xcorr at borders');\nend\n\nft_progress('init', 'text', 'Please wait...');\nfor iTrial = 1:nTrials\n origTrial = cfg.trials(iTrial);\n ft_progress(iTrial/nTrials, 'Processing trial %d from %d', iTrial, nTrials);\n \n for iCmb = 1:nCmbs\n % take only the times that are in this trial and latency window\n indx = cmbindx(iCmb,:);\n inTrial1 = spike.trial{indx(1)}==origTrial;\n inTrial2 = spike.trial{indx(2)}==origTrial;\n inWindow1 = spike.time{indx(1)}>=cfg.latency(1) & spike.time{indx(1)}<=cfg.latency(2);\n inWindow2 = spike.time{indx(2)}>=cfg.latency(1) & spike.time{indx(2)}<=cfg.latency(2);\n ts1 = sort(spike.time{indx(1)}(inTrial1(:) & inWindow1(:)));\n ts2 = sort(spike.time{indx(2)}(inTrial2(:) & inWindow2(:)));\n \n switch cfg.method\n case 'xcorr'\n % compute the xcorr if both are non-empty\n if ~isempty(ts1) && ~isempty(ts2)\n if indx(1)<=indx(2)\n [x] = spike_crossx_matlab(ts1(:),ts2(:),cfg.binsize,nLags*2+1); % removed the mex file for now, until issue on windows is resolved\n else\n [x] = spike_crossx_matlab(ts2(:),ts1(:),cfg.binsize,nLags*2+1); % removed the mex file for now, until issue on windows is resolved\n end\n \n % remove the center peaks from the auto-correlogram\n if indx(1)==indx(2), x(nLags:nLags+1) = 0; end\n \n if strcmp(cfg.debias,'yes')\n lags = (-nLags:nLags)*cfg.binsize;\n lags = (lags(2:end)+lags(1:end-1))/2;\n T = nanmin([endTrialLatency(iTrial);cfg.latency(2)])-nanmax([begTrialLatency(iTrial);cfg.latency(1)]);\n sc = (T./(T-abs(lags(:))));\n sc = length(sc)*sc./sum(sc);\n x = x(:).*sc(:);\n end\n % sum the xcorr\n s(indx(1),indx(2),:) = s(indx(1),indx(2),:) + shiftdim(x(:),-2);\n s(indx(2),indx(1),:) = s(indx(2),indx(1),:) + shiftdim(flipud(x(:)),-2);\n \n % store individual trials if requested\n if keepTrials\n singleTrials(iTrial,indx(1),indx(2),:) = shiftdim(x(:),-3);\n singleTrials(iTrial,indx(2),indx(1),:) = shiftdim(flipud(x(:)),-3);\n end\n end\n case 'shiftpredictor'\n if iTrial>1\n % symmetric, get x21 to x12 and x22 to x11\n inTrial1_old = spike.trial{indx(1)}==cfg.trials(iTrial-1);\n ts1_old = sort(spike.time{indx(1)}(inTrial1_old(:) & inWindow1(:)));\n inTrial2_old = spike.trial{indx(2)}==cfg.trials(iTrial-1);\n ts2_old = sort(spike.time{indx(2)}(inTrial2_old(:) & inWindow2(:)));\n \n % compute both combinations\n for k = 1:2\n \n % take chan from this and previous channel\n if k==1\n A = ts1;\n B = ts2_old;\n else\n A = ts1_old;\n B = ts2;\n end\n if ~isempty(A) && ~isempty(B)\n if indx(1)<=indx(2)\n [x] = spike_crossx_matlab(A(:),B(:),cfg.binsize,nLags*2+1);\n else\n [x] = spike_crossx_matlab(B(:),A(:),cfg.binsize,nLags*2+1);\n end\n % remove the center peaks from the auto-correlogram\n if indx(1)==indx(2), x(nLags:nLags+1) = 0; end\n \n if strcmp(cfg.debias,'yes')\n lags = (-nLags:nLags)*cfg.binsize;\n lags = (lags(2:end)+lags(1:end-1))/2;\n T = nanmin([endTrialLatency(iTrial);cfg.latency(2)])-nanmax([begTrialLatency(iTrial);cfg.latency(1)]);\n sc = (T./(T-abs(lags(:))));\n sc = length(sc)*sc./sum(sc);\n x = x(:).*sc(:);\n end\n % compute the sum\n s(indx(1),indx(2),:) = s(indx(1),indx(2),:) + shiftdim(x(:),-2);\n s(indx(2),indx(1),:) = s(indx(2),indx(1),:) + shiftdim(flipud(x(:)),-2);\n if keepTrials\n singleTrials(iTrial,indx(1),indx(2),:) = shiftdim(x(:)/2,-3);\n singleTrials(iTrial,indx(2),indx(1),:) = shiftdim(flipud(x(:))/2,-3);\n end\n end\n end\n end\n end % symmetric shift predictor loop\n end % combinations\nend % trial loop\nft_progress('close')\n% multiply the shift sum by a factor so it has the same scale as raw\ndofShiftPred = 2*(nTrials-1);\nif doShiftPredictor, s = s*nTrials/dofShiftPred; end\nswitch cfg.outputunit\n case 'proportion'\n sm = repmat(nansum(s,3),[1 1 nLags*2]);\n s = s./sm;\n if keepTrials\n singleTrials = singleTrials./repmat(shiftdim(sm,-1),[nTrials 1 1 1]);\n end\n case 'center'\n center = repmat(s(:,:,nLags+1),[1 1 nLags*2]);\n s = s./center;\n if keepTrials\n singleTrials = singleTrials./repmat(shiftdim(center,-1),[nTrials 1 1 1]);\n end\nend\n\n% return the results\nstat.(cfg.method) = s;\nlags = (-nLags:nLags)*cfg.binsize;\nlags = (lags(2:end)+lags(1:end-1))/2;\nstat.time = lags;\nstat.dimord = 'chan_chan_time';\nif keepTrials\n stat.trial = singleTrials;\n stat.dimord = 'trial_chan_chan_time';\nend\nstat.label = spike.label(chansel);\n\n% do the general cleanup and bookkeeping at the end of the function\n\nft_postamble previous spike\nft_postamble provenance stat\nft_postamble history stat\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% SUBFUNCTION\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [C] = spike_crossx_matlab(tX,tY,binsize,nbins)\ntX = sort(tX(:));\ntY = sort(tY(:));\n\nminLag = - binsize * (nbins-1) / 2;\nj = 0:nbins-1;\nB = minLag + j * binsize;\ntX(tX<(tY(1)+minLag) | tX>(tY(end)-minLag)) = [];\nif isempty(tX)\n C = zeros(1,length(B)-1);\n return;\nend\ntY(tY>(tX(end)-minLag) | tY<(tX(1)+minLag)) = [];\nif isempty(tY)\n C = zeros(1,length(B)-1);\n return;\nend\nnX = length(tX); nY = length(tY);\n\n% compute all distances at once using a multiplication trick\nif (nX*nY)<2*10^7 % allow matrix to grow to about 150 MB, should always work\n D = log(exp(-tX(:))*exp(tY(:)'));\n D = D(:);\n D(abs(D)>abs(minLag)) = [];\n [C] = histc(D,B);\n C(end) = [];\nelse\n % break it down in pieces such that nX*nY<2*10*7\n k = 2;\n nXs = round(nX/k);\n while (nXs*nY)>=(2*10^7)\n k = k+1;\n nXs = round(nX/k);\n end\n \n % get the indices\n steps = round(nX/k);\n begs = 1:steps:steps*k;\n ends = begs+(steps-1);\n rm = begs>nX;\n begs(rm) = [];\n ends(rm) = [];\n ends(end) = nX;\n nSteps = length(begs);\n \n C = zeros(1,length(B));\n for iStep = 1:nSteps\n d = log(exp(-tX(begs(iStep):ends(iStep)))*exp(tY(:)'));\n d = d(:);\n d(abs(d)>abs(minLag)) = [];\n C = C + histc(d,B)';\n end\n C(end) = [];\nend\n\nif isempty(C)\n C = zeros(1,length(B)-1);\nend\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/contrib/spike/ft_spike_xcorr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.45713671682749474, "lm_q1q2_score": 0.30258925025907973}} {"text": "function h = plus(f, g)\n%+ Plus for BALLFUN.\n% F + G adds F and G. F and G can be scalars or BALLFUNs.\n\n% Copyright 2019 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\nfIsBallfun = isa(f, 'ballfun');\ngIsBallfun = isa(g, 'ballfun');\n\n% Empty check\nif isempty( f )\n h = g;\n if ~gIsBallfun\n h = ballfun(h);\n end\n return\nend\n\n% Empty check\nif isempty( g )\n h = f;\n if ~fIsBallfun\n h = ballfun(h);\n end\n return\nend\n\nif (fIsBallfun && gIsBallfun)\n [mf,nf,pf] = size(f); \n [mg,ng,pg] = size(g); \n m = max(mf,mg); \n n = max(nf,ng);\n p = max(pf,pg); \n X = zeros(m,n,p);\n X(1:mf,floor(n/2)+1-floor(nf/2):floor(n/2)+nf-floor(nf/2),floor(p/2)+1-floor(pf/2):floor(p/2)+pf-floor(pf/2)) = f.coeffs;\n X(1:mg,floor(n/2)+1-floor(ng/2):floor(n/2)+ng-floor(ng/2),floor(p/2)+1-floor(pg/2):floor(p/2)+pg-floor(pg/2)) = ...\n X(1:mg,floor(n/2)+1-floor(ng/2):floor(n/2)+ng-floor(ng/2),floor(p/2)+1-floor(pg/2):floor(p/2)+pg-floor(pg/2)) + g.coeffs;\n h = ballfun(X,'coeffs');\nelseif (fIsBallfun && isnumeric(g))\n S = size(f);\n X = f.coeffs;\n % Add the constant g\n X(1,floor(S(2)/2)+1,floor(S(3)/2)+1) = X(1,floor(S(2)/2)+1,floor(S(3)/2)+1) + g;\n h = ballfun(X,'coeffs');\nelseif (isnumeric(f) && gIsBallfun)\n S = size(g);\n X = g.coeffs;\n % Add the constant f\n X(1,floor(S(2)/2)+1,floor(S(3)/2)+1) = X(1,floor(S(2)/2)+1,floor(S(3)/2)+1) + f;\n h = ballfun(X,'coeffs');\nelse\n error('BALLFUN:plus:unknown', ...\n ['Undefined function ''plus'' for input arguments of type ' ...\n '%s and %s.'], class(f), class(g));\nend\nend\n", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/@ballfun/plus.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5736783928749126, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.30251009566877635}} {"text": "close all\nclear\n\n%------------------------------------------------------------------------------------------\nnb = 1000;%Total number of initial states\nnmpcd=zeros(1,nb);%Store computing time for one time-step for NMPC-DCBF\nimpcd=zeros(1,nb);%Store computing time for one time-step for iMPC-DCBF\nnmpcinf=zeros(1,1);%Store infeasible rate for one time-step for NMPC-DCBF\nimpcinf=zeros(1,1);%Store infeasible rate for one time-step for iMPC-DCBF\ni=24;%i is number of horozon\nts = 1;%Total time steps\nload(gamma1_0p6\\InitialStateData');%Load the generated 1000 initial states\n[a, b, c, d]=compare(i,ts,nb,InitialMat);%Involves NMPC-DCBF and iMPC-DCBF\nnmpcd(1,:)=a;\nimpcd(1,:)=b;\nnmpcinf(1,1)=c;\nimpcinf(1,1)=d;\nnmpcplot1=nmpcd(1,:);\nnmpcplot1(nmpcplot1==-1)=[];%Eliminate infeasible one time-step trajectories\nimpcplot1=impcd(1,:);\nimpcplot1(impcplot1==-1)=[];%Eliminate infeasible one time-step trajectories\n\nsave('timecom24','nmpcplot1','impcplot1');\nsave('feasibility24','nmpcinf','impcinf');\n\ndistnmpc = fitdist(nmpcplot1','Normal');\ndistimpc = fitdist(impcplot1','Normal');\nmu1=distnmpc.mu;%Get mean of sample of computing time for NMPC-DCBF\nmu2=distimpc.mu;%Get mean of sample of computing time for iMPC-DCBF\nsigma1=distnmpc.sigma;%Get variance of sample of computing time for NMPC-DCBF\nsigma2=distimpc.sigma;%Get variance of sample of computing time for iMPC-DCBF\n\n\n%Initialize atmosphere parameters\nfunction [tnmpc, timpc, ratiotnmpc, ratiotimpc]=compare(N11,ttsim,samplen,InitialMat)\ntnmpc=[];\ntimpc=[];\nfor i=1:samplen\nN1=N11;\ntsim=ttsim;\nxini1=InitialMat(1,i);\nyini1=InitialMat(2,i);\nthetaini1=InitialMat(3,i);\nvini1=InitialMat(4,i);\nx01=[xini1;yini1;thetaini1;vini1];\nx02=[xini1 yini1 thetaini1 vini1];\nt1 = nmpcdcbf(x01, N1, tsim);\nt2 = impcdcbf(x02, N1, tsim);\ntindex=[N11 i];\ndisp(tindex);\ntnmpc=[tnmpc t1];%Computing time for NMPC-DCBF\ntimpc=[timpc t2];%Computing time for iMPC-DCBF\nend\nnnmpc1 = length(tnmpc);\nnimpc1 = length(timpc);\ntnmpcs = tnmpc;\ntimpcs = timpc;\ntnmpcs(tnmpcs==-1)=[];\ntimpcs(timpcs==-1)=[];\nnnmpc2 = length(tnmpcs);\nnimpc2 = length(timpcs);\nratiotnmpc = (nnmpc1-nnmpc2)/nnmpc1;%Infeasible rate for NMPC-DCBF\nratiotimpc = (nimpc1-nimpc2)/nimpc1;%Infeasible rate for iMPC-DCBF\nend\n\n\n\n\n\nfunction t1 = nmpcdcbf(x00, N1, ttsim)\n%% General Flags\nrun_nmpc_dcbf_one = true;\nrun_nmpc_dcbf_multiple = true;\n\n%% Setup and Parameters\nx0 = x00;\ndt = 0.1;\ntime_total = ttsim *dt;\nP = zeros(4,4);%Weight matrix P\nP(1,1) = 10; P(2,2) = 10; P(3,3) = 10;P(4,4) = 10;\nQ = zeros(4,4);%Weight matrix Q\nQ(1,1) = 10; Q(2,2) = 10; Q(3,3) = 10;Q(4,4) = 10;\nR = zeros(4,4);%Weight matrix R\nR(1,1) = 1; R(2,2) = 1;R(3,3) = 1000;R(4,4) = 1000;\n%Variables range as below\nxmin = [-10; -10; -10;-10];\nxmax = [10; 10; 10;10];\numin = [-7; -5;-inf;-inf];\numax = [7; 5;inf;inf];\n\n%% Discrete-time unicycle model\nsystem.dt = dt;\nsystem.A = [1 0 0 0;\n 0 1 0 0;\n 0 0 1 0;\n 0 0 0 1];\nsystem.B = [x0(4,1)*cos(x0(3,1))*dt;\n x0(4,1)*sin(x0(3,1))*dt;\n 0;\n 0];\nsystem.C =[0 0 0 0;\n 0 0 0 0;\n 1*dt 0 0 0;\n 0 1*dt 0 0];\nsystem.xl = xmin;\nsystem.xu = xmax;\nsystem.ul = umin;\nsystem.uu = umax;\n\n%% NMPC-DCBF parameters\nparams_nmpc_dcbf.Q = Q;\nparams_nmpc_dcbf.R = R;\nparams_nmpc_dcbf.P = P;\nparams_nmpc_dcbf.gamma1 = 0.6;\nparams_nmpc_dcbf.gamma2 = 0.6;\n\n%% Obstacle\nobs.pos1 = [0; 0];\nobs.r1 = 1;\n\n\n\n%% Simulate NMPC-DCBF with other N\nparams_nmpc_dcbf.N = N1;\nif run_nmpc_dcbf_one\n fprintf('Run NMPC-DCBF-24\\n');\n controller_nmpc_dcbf_multiple24 = NMPCDCBF1(x0, system, params_nmpc_dcbf);%Highest order mcbf=2\n controller_nmpc_dcbf_multiple24.obs = obs;\n controller_nmpc_dcbf_multiple24.sim(time_total);\nend\nt1=controller_nmpc_dcbf_multiple24.tt;\nend\n\n\nfunction t2=impcdcbf(x00, N1, ttsim)\nt2=0;\nxo = 0;\nyo = 0;\nr = 1;\nN = N1;%Number of horizon\nK1 = 1000;%Maximum iteration times, jmax\nK = 1000;%Maximum iteration times, jmax\ndt = 0.1;\ngamma1 = 6;\ngamma2 = 6;\nnsim = ttsim;\n\ntic;\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 = x00;\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);%First order CBF constraints\nlcbf = -abc(3, :);\nlcbf(1) = [];\nlcbf = lcbf';\nucbf = inf * ones(N, 1);\nA2cbf = cbfmat2(abc, nx, nu, dt, gamma1, gamma2, x0);%Second order CBF constraints\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];\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!')\n t2=-1;\n return\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)%Iterations for the first time-step\n storagex = ctrlx;%store the state variables and inputs in order to compare them with the next iteration\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];\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 t2=-1;\n return\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);\nt2=t2+toc;\nreturn\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)%Iterations for the left time steps\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];\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 t2=-1;\n return\n end\n ctrlx = res.x(1:(N+1)*nx);\n ctrlu = res.x((N+1)*nx+1:(N+1)*nx+N*nu);\n x0 = ctrlx(1:nx);\n testx0 = [testx0 x0];\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\nend\n\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/benchmark/gamma1-0p6/test_each_horizon/test_N24.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.5234203489363239, "lm_q1q2_score": 0.3022728255546674}} {"text": "function [granger, v, n] = ft_connectivity_granger(H, Z, S, varargin)\n\n% FT_CONNECTIVITY_GRANGER computes spectrally resolved granger causality. This\n% implementation is loosely based on the code used in Brovelli, et. al., PNAS 101,\n% 9849-9854 (2004).\n%\n% Use as\n% [GRANGER, V, N] = FT_CONNECTIVITY_GRANGER(H, Z, S, ...)\n%\n% The input data should be\n% H = spectral transfer matrix, Nrpt x Nchan x Nchan x Nfreq (x Ntime),\n% or Nrpt x Nchancmb x Nfreq (x Ntime). Nrpt can be 1.\n% Z = the covariance matrix of the noise, Nrpt x Nchan x Nchan (x Ntime),\n% or Nrpt x Nchancmb (x Ntime).\n% S = the cross-spectral density matrix with the same dimensionality as H.\n%\n% Additional optional input arguments come as key-value pairs:\n% 'dimord' = required string specifying how to interpret the input data\n% supported values are 'rpt_chan_chan_freq(_time) and\n% 'rpt_chan_freq(_time), 'rpt_pos_pos_XXX' and 'rpt_pos_XXX'\n% 'method' = 'granger' (default), or 'instantaneous', or 'total'.\n% 'hasjack' = 0 (default) is a boolean specifying whether the input\n% contains leave-one-outs, required for correct variance\n% estimate\n% 'powindx' = is a variable determining the exact computation, see below\n%\n% If the inputdata is such that the channel-pairs are linearly indexed, granger\n% causality is computed per quadruplet of consecutive entries, where the convention\n% is as follows:\n%\n% H(:, (k-1)*4 + 1, :, :, :) -> 'chan1-chan1'\n% H(:, (k-1)*4 + 2, :, :, :) -> 'chan1->chan2'\n% H(:, (k-1)*4 + 3, :, :, :) -> 'chan2->chan1'\n% H(:, (k-1)*4 + 4, :, :, :) -> 'chan2->chan2'\n%\n% The same holds for the Z and S matrices.\n%\n% Pairwise block-granger causality can be computed when the inputdata has\n% dimensionality Nchan x Nchan. In that case powindx should be specified, as a 1x2\n% cell-array indexing the individual channels that go into each 'block'.\n%\n% See also FT_CONNECTIVITYANALYSIS\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Undocumented option: powindx can be a struct. In that case, blockwise\n% conditional granger can be computed.\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% Copyright (C) 2009-2017, Jan-Mathijs Schoffelen\n%\n% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org\n% for the documentation and details.\n%\n% FieldTrip is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% FieldTrip is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with FieldTrip. If not, see .\n%\n% $Id$\n\nmethod = ft_getopt(varargin, 'method', 'granger');\nhasjack = ft_getopt(varargin, 'hasjack', 0);\npowindx = ft_getopt(varargin, 'powindx', []);\ndimord = ft_getopt(varargin, 'dimord', []);\n\n%FIXME speed up code and check\nsiz = size(H);\nif numel(siz)==4\n siz(5) = 1;\nend\nn = siz(1);\nNc = siz(2);\n\noutsum = zeros(siz(2:end));\noutssq = zeros(siz(2:end));\n\n% crossterms are described by chan_chan_therest\nissquare = length(strfind(dimord, 'chan'))==2 || length(strfind(dimord, 'pos'))==2;\n\nswitch method\n case 'granger'\n \n if issquare && isempty(powindx)\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % data are chan_chan_therest\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%\n \n for kk = 1:n\n for ii = 1:Nc\n for jj = 1:Nc\n if ii ~=jj\n zc = reshape(Z(kk,jj,jj,:) - Z(kk,ii,jj,:).^2./Z(kk,ii,ii,:),[1 1 1 1 siz(5)]);\n zc = repmat(zc,[1 1 1 siz(4) 1]);\n numer = reshape(abs(S(kk,ii,ii,:,:)),[1 1 siz(4:end)]);\n denom = reshape(abs(S(kk,ii,ii,:,:)-zc.*abs(H(kk,ii,jj,:,:)).^2),[1 1 siz(4:end)]);\n outsum(jj,ii,:,:) = outsum(jj,ii,:,:) + log(numer./denom);\n outssq(jj,ii,:,:) = outssq(jj,ii,:,:) + (log(numer./denom)).^2;\n end\n end\n outsum(ii,ii,:,:) = 0; %self-granger set to zero\n end\n end\n \n elseif ~issquare && isempty(powindx)\n %%%%%%%%%%%%%%%%%%%%%%%%%%\n %data are linearly indexed\n %%%%%%%%%%%%%%%%%%%%%%%%%%\n \n for j = 1:n\n for k = 1:Nc\n %FIXME powindx is not used here anymore\n %iauto1 = sum(powindx==powindx(k,1),2)==2;\n %iauto2 = sum(powindx==powindx(k,2),2)==2;\n %icross1 = k;\n %icross2 = sum(powindx==powindx(ones(Nc,1)*k,[2 1]),2)==2;\n \n % The following is based on hard-coded assumptions: which is fair\n % to do if the order of the labelcmb is according to the output of\n % ft_connectivity_csd2transfer\n if mod(k-1, 4)==0\n continue; % auto granger set to 0\n %iauto1=k;iauto2=k;icross1=k;icross2=k;\n elseif mod(k-1, 4)==1\n iauto1=k+2;iauto2=k-1;icross1=k;icross2=k+1;\n elseif mod(k-1, 4)==2\n iauto1=k-2;iauto2=k+1;icross1=k;icross2=k-1;\n elseif mod(k-1, 4)==3\n continue; % auto granger set to 0\n %iauto1=k;iauto2=k;icross1=k;icross2=k;\n end\n \n zc = Z(j,iauto2,:,:) - Z(j,icross1,:,:).^2./Z(j,iauto1,:,:);\n numer = abs(S(j,iauto1,:,:));\n denom = abs(S(j,iauto1,:,:)-zc(:,:,ones(1,size(H,3)),:).*abs(H(j,icross1,:,:)).^2);\n outsum(icross2,:,:) = outsum(icross2,:,:) + reshape(log(numer./denom), [1 siz(3:end)]);\n outssq(icross2,:,:) = outssq(icross2,:,:) + reshape((log(numer./denom)).^2, [1 siz(3:end)]);\n end\n end\n \n elseif issquare && iscell(powindx)\n %%%%%%%%%%%%%%%%%%%\n % blockwise granger\n %%%%%%%%%%%%%%%%%%%\n \n % H = transfer function nchan x nchan x nfreq\n % Z = noise covariance nchan x nchan\n % S = crosspectrum nchan x nchan x nfreq\n % powindx{k} is a list of indices for block k\n \n nblock = numel(powindx);\n n = size(H,1);\n nfreq = size(H,4);\n \n outsum = zeros(nblock,nblock,nfreq);\n outssq = zeros(nblock,nblock,nfreq);\n \n for k = 1:nblock\n for m = (k+1):nblock\n indx = [powindx{k}(:);powindx{m}(:)];\n indx = cat(1,indx,setdiff((1:size(Z,2))',indx));\n n1 = numel(powindx{k});\n n2 = numel(powindx{m});\n ntot = numel(indx);\n indx1 = 1:n1;\n indx1_ = (1:ntot)'; indx1_(indx1) = [];\n indx2 = n1+(1:n2);\n indx12_ = (1:ntot)'; indx12_([indx1(:);indx2(:)]) = []; \n \n for kk = 1:n\n tmpZ = reshape(Z(kk,indx,indx), [ntot ntot]);\n \n % projection matrix for therest+block2 -> block1\n P1 = [eye(n1) zeros(n1,ntot-n1);\n -tmpZ(indx1_,indx1)/tmpZ(indx1,indx1) eye(ntot-n1)];\n \n % projection matrix for therest+block1 -> block2\n P2 = [ eye(n1) -tmpZ(indx1,indx2)/tmpZ(indx2,indx2) zeros(n1,ntot-n1-n2);\n zeros(n2,n1) eye(n2) zeros(n2, ntot-n1-n2);\n zeros(ntot-n1-n2,n1) -tmpZ(indx12_,indx2)/tmpZ(indx2,indx2) eye(ntot-n1-n2)];\n \n % invert only once\n for jj = 1:nfreq\n % post multiply transfer matrix with the inverse of the projection matrix\n % this is equivalent to time domain pre multiplication with P\n Sj = reshape(S(kk,indx,indx,jj), [ntot ntot]);\n Zj = tmpZ; %(:,:);\n H1 = reshape(H(kk,indx,indx,jj), [ntot ntot])/P1;\n H2 = reshape(H(kk,indx,indx,jj), [ntot ntot])/P2;\n num1 = abs(det(Sj(indx1,indx1))); % numerical round off leads to tiny imaginary components\n num2 = abs(det(Sj(indx2,indx2))); % numerical round off leads to tiny imaginary components\n denom1 = abs(det(H1(indx1,indx1)*Zj(indx1,indx1)*H1(indx1,indx1)'));\n denom2 = abs(det(H2(indx2,indx2)*Zj(indx2,indx2)*H2(indx2,indx2)'));\n %rH1 = real(H1(indx1,indx1));\n %rH2 = real(H2(indx2,indx2));\n %iH1 = imag(H1(indx1,indx1));\n %iH2 = imag(H2(indx2,indx2));\n %h1 = rH1*Zj(indx1,indx1)*rH1' + iH1*Zj(indx1,indx1)*iH1';\n %h2 = rH2*Zj(indx2,indx2)*rH2' + iH2*Zj(indx2,indx2)*iH2';\n %denom1 = abs(det(h1));\n %denom2 = abs(det(h2));\n \n outsum(m,k,jj) = log( num1./denom1 ) + outsum(m,k,jj);\n outsum(k,m,jj) = log( num2./denom2 ) + outsum(k,m,jj);\n outssq(m,k,jj) = log( num1./denom1 ).^2 + outssq(m,k,jj);\n outssq(k,m,jj) = log( num2./denom2 ).^2 + outssq(k,m,jj);\n end\n end\n \n end\n end\n \n elseif ~issquare && isstruct(powindx) && isfield(powindx, 'n')\n %%%%%%%%%%%%%%%%%%%%%%\n %blockwise conditional\n %%%%%%%%%%%%%%%%%%%%%%\n \n n = size(H,1);\n ncmb = size(H,2);\n nfreq = size(H,3);\n ncnd = size(powindx.cmbindx,1);\n \n outsum = zeros(ncnd, nfreq);\n outssq = zeros(ncnd, nfreq);\n for k = 1:n\n tmpS = reshape(S, [ncmb nfreq]);\n tmpH = reshape(H, [ncmb nfreq]);\n tmpZ = reshape(Z, [ncmb 1]);\n tmp = blockwise_conditionalgranger(tmpS,tmpH,tmpZ,powindx.cmbindx,powindx.n);\n \n outsum = outsum + tmp;\n outssq = outssq + tmp.^2;\n end\n \n elseif ~issquare && isstruct(powindx)\n %%%%%%%%%%%%%%%%%%%%%%\n %triplet conditional\n %%%%%%%%%%%%%%%%%%%%%%\n \n % decode from the powindx struct which rows in the data correspond with\n % the triplets, and which correspond with the duplets\n ublockindx = unique(powindx.blockindx);\n nperblock = zeros(size(ublockindx));\n for k = 1:numel(ublockindx)\n nperblock(k,1) = sum(powindx.blockindx==ublockindx(k));\n end\n if ~all(ismember(nperblock,[4 9]))\n error('the data should be a mixture of trivariate and bivariate decompositions');\n end\n indx_triplets = ismember(powindx.blockindx, ublockindx(nperblock==9)); ntriplets = sum(indx_triplets)./9;\n indx_duplets = ismember(powindx.blockindx, ublockindx(nperblock==4)); nduplets = sum(indx_duplets)./4;\n \n % this assumes well-behaved powindx.cmbindx\n cmbindx2 = reshape(powindx.cmbindx(indx_duplets, 1), 2, [])';\n cmbindx3 = reshape(powindx.cmbindx(indx_triplets,1), 3, [])';\n \n cmbindx2 = cmbindx2(1:2:end,:);\n cmbindx3 = cmbindx3(1:3:end,:);\n \n cmbindx = powindx.outindx;\n \n n = size(H,1);\n siz = size(H);\n \n outsum = zeros(size(cmbindx,1), size(H,3));\n outssq = outsum;\n \n % call the low-level function\n for k = 1:n\n H3 = reshape(H(k,indx_triplets,:,:), [3 3 ntriplets siz(3:end)]);\n Z3 = reshape(Z(k,indx_triplets), [3 3 ntriplets]);\n \n H2 = reshape(H(k,indx_duplets,:,:), [2 2 nduplets siz(3:end)]);\n Z2 = reshape(Z(k,indx_duplets), [2 2 nduplets]);\n \n tmp = triplet_conditionalgranger(H3,Z3,cmbindx3,H2,Z2,cmbindx2,cmbindx);\n \n outsum = outsum + tmp;\n outssq = outssq + tmp.^2;\n end\n \n \n \n end\n \n case 'instantaneous'\n \n if issquare && isempty(powindx)\n % data are chan_chan_therest\n for kk = 1:n\n for ii = 1:Nc\n for jj = 1:Nc\n if ii ~=jj\n zc1 = reshape(Z(kk,jj,jj,:) - Z(kk,ii,jj,:).^2./Z(kk,ii,ii,:),[1 1 1 1 siz(5)]);\n zc2 = reshape(Z(kk,ii,ii,:) - Z(kk,jj,ii,:).^2./Z(kk,jj,jj,:),[1 1 1 1 siz(5)]);\n zc1 = repmat(zc1,[1 1 1 siz(4) 1]);\n zc2 = repmat(zc2,[1 1 1 siz(4) 1]);\n term1 = abs(S(kk,ii,ii,:,:)) - zc1.*abs(H(kk,ii,jj,:,:)).^2;\n term2 = abs(S(kk,jj,jj,:,:)) - zc2.*abs(H(kk,jj,ii,:,:)).^2;\n numer = term1.*term2;\n denom = abs(S(kk,ii,ii,:,:).*S(kk,jj,jj,:,:) - S(kk,ii,jj,:,:).*S(kk,jj,ii,:,:));\n outsum(jj,ii,:,:) = outsum(jj,ii,:,:) + reshape(log(numer./denom), [1 1 siz(4:end)]);\n outssq(jj,ii,:,:) = outssq(jj,ii,:,:) + reshape((log(numer./denom)).^2, [1 1 siz(4:end)]);\n end\n end\n outsum(ii,ii,:,:) = 0; %self-granger set to zero\n end\n end\n elseif ~issquare && isempty(powindx)\n % data are linearly indexed\n for j = 1:n\n for k = 1:Nc\n %iauto1 = sum(powindx==powindx(k,1),2)==2;\n %iauto2 = sum(powindx==powindx(k,2),2)==2;\n %icross1 = k;\n %icross2 = sum(powindx==powindx(ones(Nc,1)*k,[2 1]),2)==2;\n if mod(k-1, 4)==0\n continue; % auto granger set to 0\n %iauto1=k;iauto2=k;icross1=k;icross2=k;\n elseif mod(k-1, 4)==1\n iauto1=k+2;iauto2=k-1;icross1=k;icross2=k+1;\n elseif mod(k-1, 4)==2\n iauto1=k-2;iauto2=k+1;icross1=k;icross2=k-1;\n elseif mod(k-1, 4)==3\n continue; % auto granger set to 0\n %iauto1=k;iauto2=k;icross1=k;icross2=k;\n end\n \n zc1 = Z(j,iauto1,:, :) - Z(j,icross2,:, :).^2./Z(j,iauto2,:, :);\n zc2 = Z(j,iauto2,:, :) - Z(j,icross1,:, :).^2./Z(j,iauto1,:, :);\n term1 = abs(S(j,iauto2,:,:)) - zc1(:,:,ones(1,size(H,3)),:).*abs(H(j,icross2,:,:)).^2;\n term2 = abs(S(j,iauto1,:,:)) - zc2(:,:,ones(1,size(H,3)),:).*abs(H(j,icross1,:,:)).^2;\n numer = term1.*term2;\n denom = abs(S(j,iauto1,:,:).*S(j,iauto2,:,:) - S(j,icross1,:,:).*S(j,icross2,:,:));\n \n outsum(icross2,:,:) = outsum(icross2,:,:) + reshape(log(numer./denom), [1 siz(3:end)]);\n outssq(icross2,:,:) = outssq(icross2,:,:) + reshape((log(numer./denom)).^2, [1 siz(3:end)]);\n end\n end\n elseif issquare && iscell(powindx)\n % blockwise granger\n % H = transfer function nchan x nchan x nfreq\n % Z = noise covariance nchan x nchan\n % S = crosspectrum nchan x nchan x nfreq\n % powindx{1} is a list of indices for block1\n % powindx{2} is a list of indices for block2\n ft_error('instantaneous causality is not implemented for blockwise factorizations');\n elseif isstruct(powindx)\n %blockwise conditional\n ft_error('blockwise conditional instantaneous causality is not implemented');\n else\n ft_error('not implemented');\n end\n \n case 'total'\n \n if issquare && isempty(powindx)\n % data are chan_chan_therest\n for kk = 1:n\n for ii = 1:Nc\n for jj = 1:Nc\n if ii ~=jj\n numer = abs(S(kk,ii,ii,:,:).*S(kk,jj,jj,:,:));\n denom = abs(S(kk,ii,ii,:,:).*S(kk,jj,jj,:,:) - S(kk,ii,jj,:,:).*S(kk,jj,ii,:,:));\n outsum(jj,ii,:,:) = outsum(jj,ii,:,:) + reshape(log(numer./denom), [1 1 siz(4:end)]);\n outssq(jj,ii,:,:) = outssq(jj,ii,:,:) + reshape((log(numer./denom)).^2, [1 1 siz(4:end)]);\n end\n end\n outsum(ii,ii,:,:) = 0; %self-granger set to zero\n end\n end\n elseif ~issquare && isempty(powindx)\n % data are linearly indexed\n for j = 1:n\n for k = 1:Nc\n %iauto1 = sum(powindx==powindx(k,1),2)==2;\n %iauto2 = sum(powindx==powindx(k,2),2)==2;\n %icross1 = k;\n %icross2 = sum(powindx==powindx(ones(Nc,1)*k,[2 1]),2)==2;\n if mod(k-1, 4)==0\n continue; % auto granger set to 0\n %iauto1=k;iauto2=k;icross1=k;icross2=k;\n elseif mod(k-1, 4)==1\n iauto1=k+2;iauto2=k-1;icross1=k;icross2=k+1;\n elseif mod(k-1, 4)==2\n iauto1=k-2;iauto2=k+1;icross1=k;icross2=k-1;\n elseif mod(k-1, 4)==3\n continue; % auto granger set to 0\n %iauto1=k;iauto2=k;icross1=k;icross2=k;\n end\n \n numer = abs(S(j,iauto1,:,:).*S(j,iauto2,:,:));\n denom = abs(S(j,iauto1,:,:).*S(j,iauto2,:,:) - S(j,icross1,:,:).*S(j,icross2,:,:));\n outsum(icross2,:,:) = outsum(icross2,:,:) + reshape(log(numer./denom), [1 siz(3:end)]);\n outssq(icross2,:,:) = outssq(icross2,:,:) + reshape((log(numer./denom)).^2, [1 siz(3:end)]);\n end\n end\n elseif issquare && iscell(powindx)\n % blockwise total interdependence\n \n % S = crosspectrum nchan x nchan x nfreq\n % powindx{k} is a list of indices for block k\n \n nblock = numel(powindx);\n n = size(S,1);\n nfreq = size(S,4);\n \n outsum = zeros(nblock,nblock,nfreq);\n outssq = zeros(nblock,nblock,nfreq);\n \n for k = 1:nblock\n for m = (k+1):nblock\n indx = [powindx{k}(:);powindx{m}(:)];\n n1 = numel(powindx{k});\n n2 = numel(powindx{m});\n ntot = n1+n2;\n indx1 = 1:n1;\n indx2 = (n1+1):ntot;\n \n for kk = 1:n\n for jj = 1:nfreq\n Sj = reshape(S(kk,indx,indx,jj), [ntot ntot]);\n num1 = abs(det(Sj(indx1,indx1))); % numerical round off leads to tiny imaginary components\n num2 = abs(det(Sj(indx2,indx2))); % numerical round off leads to tiny imaginary components\n num = num1.*num2;\n denom = abs(det(Sj));\n \n outsum(m,k,jj) = log( num./denom ) + outsum(m,k,jj);\n outsum(k,m,jj) = log( num./denom ) + outsum(k,m,jj);\n outssq(m,k,jj) = log( num./denom ).^2 + outssq(m,k,jj);\n outssq(k,m,jj) = log( num./denom ).^2 + outssq(k,m,jj);\n end\n end\n \n end\n end\n \n elseif issquare && isstruct(powindx)\n %blockwise conditional\n ft_error('blockwise conditional total interdependence is not implemented');\n end\n \n case 'iis'\n ft_warning('THIS IS EXPERIMENTAL CODE, USE AT YOUR OWN RISK!');\n % this is experimental\n if ~issquare && isempty(powindx)\n A = transfer2coeffs(shiftdim(H),(0:size(H,3)-1));\n ncmb = size(A,1)./4;\n iis = coeffs2iis(reshape(A,[2 2 ncmb size(A,2)]),reshape(Z,[2 2 ncmb]));\n iis = repmat(iis(:),[1 4])';\n outsum = iis(:);\n outssq = nan(size(outsum));\n else\n ft_error('iis can only be computed when the input contains sets of bivariate factorizations');\n end\n \n otherwise\n ft_error('unsupported output requested');\nend\n\ngranger = outsum./n;\nif n>1\n if hasjack\n bias = (n-1).^2;\n else\n bias = 1;\n end\n v = bias*(outssq - (outsum.^2)./n)./(n - 1);\nelse\n v = [];\nend\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/external/fieldtrip/connectivity/ft_connectivity_granger.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.4263215925474904, "lm_q1q2_score": 0.30227016626190306}} {"text": "function [g1, g2, g3] = sdlfmaXsdlfmaKernGradientBlockIGJ(lfmKern1, lfmKern2, ...\n t1, t2, i, j, generalConst, generalConstGrad, covGrad, g1Mean, ...\n g2Mean, gsp1Mean, gsp2Mean, typeMeanParam, typeMeanSwitching, ...\n typeKernParam1, typeKernParam2, typeKernSwitching1, typeKernSwitching2)\n\n% SDLFMAXSDLFMAKERNGRADIENTBLOCKIGJ \n% FORMAT\n% DESC computes the gradients of the parameters for system 1 and system 2\n% when i is greater than j. It assummes both systems represent\n% accelerations.\n% ARG lfmKern1 : structure containing parameters for the system 1\n% ARG lfmKern2 : structure containing parameters for the system 2\n% ARG t1 : times at which the system 1 is evaluated\n% ARG t2 : times at which the system 2 is evaluated\n% ARG covGrad : partial derivatives of the objective function wrt portion\n% of the corresponding kernel matrix\n% ARG g1Mean : gradients of the parameter of the system 1 obtained from the\n% part of the function that uses the funcitons accommpanying the initial\n% conditions.\n% ARG g2Mean : gradients of the parameter of the system 2 obtained from the\n% part of the function that uses the funcitons accommpanying the initial\n% conditions.\n% ARG gsp1Mean : gradient of the switching point of the system 1 obtained \n% from the part of the function that uses the funcitons accommpanying the \n% initial conditions.\n% ARG gsp2Mean : gradient of the switching point of the system 2 obtained \n% from the part of the function that uses the funcitons accommpanying the \n% initial conditions.\n% ARG typeMeanParam : specify the mean functions used to compute this part \n% of the kernel\n% ARG typeMeanSwitching : specify the functions used to compute the\n% gradients of the swicthing points in part thst uses mean functions\n% ARG typeKernParam1 : specify the first kernel function used to compute \n% this part of the kernel\n% ARG typeKernParam2 : specify the second kernel function used to compute \n% this part of the kernel\n% ARG typeKernSwitching1 : specify the functions used to compute the\n% gradients of the swicthing points in both sides of the kernel function 1\n% ARG typeKernSwitching2 : specify the functions used to compute the\n% gradients of the swicthing points in both sides of the kernel function 2\n% RETURN g1 : gradients of parameters for the system 1\n% RETURN g2 : gradients of parameters for the system 2\n% RETURN g3 : gradients of switching points\n%\n% COPYRIGHT : Mauricio A. Alvarez, 2010.\n\n% KERN\n\nif nargin < 14\n typeMeanParam = 'sdlfm';\n typeMeanSwitching = 'sdlfmv';\n typeKernParam1 = 'lfmXlfm';\n typeKernParam2 = 'lfmvXlfm';\n typeKernSwitching1= {'lfmvXlfm', 'lfmvXlfm'};\n typeKernSwitching2 ={'lfmaXlfm', 'lfmvXlfmv'};\nend\n\ng3 = [];\n\nfhandleMeanParam = str2func([typeMeanParam 'MeanCompute']);\nfhandleMeanGradParam = str2func([typeMeanParam 'MeanGradient']);\nfhandleMeanGradSwitching = str2func([typeMeanSwitching 'MeanCompute']);\nfhandleKernPosPos = str2func([typeKernParam1 'KernCompute']);\nfhandleKernGradPosPos = str2func([typeKernParam1 'KernGradient']);\nfhandleKernGradSwitchingPosPos1 = str2func([typeKernSwitching1{1} 'KernCompute']);\nfhandleKernGradSwitchingPosPos2 = str2func([typeKernSwitching1{2} 'KernCompute']);\nfhandleKernVelPos = str2func([typeKernParam2 'KernCompute']);\nfhandleKernGradVelPos = str2func([typeKernParam2 'KernGradient']);\nfhandleKernGradSwitchingVelPos1 = str2func([typeKernSwitching2{1} 'KernCompute']);\nfhandleKernGradSwitchingVelPos2 = str2func([typeKernSwitching2{2} 'KernCompute']);\n\n\nc1 = fhandleMeanParam(lfmKern1(1), t1, 'Pos');\ne1 = fhandleMeanParam(lfmKern1(1), t1, 'Vel');\n\nif isempty(generalConst{i,j})\n coeffPosPos = c1;\n coeffVelPos = e1;\nelse\n coeffPosPos = generalConst{i,j}(1,1)*c1 + generalConst{i,j}(2,1)*e1;\n coeffVelPos = generalConst{i,j}(1,2)*c1 + generalConst{i,j}(2,2)*e1;\nend\ng1Kern = zeros(length(lfmKern1), 5);\ng2Kern = zeros(length(lfmKern1), 5);\nPosPos = zeros(1,length(t2));\nVelPos = zeros(1,length(t2));\n\nfor k=1:length(lfmKern1)\n PosPos = PosPos + fhandleKernPosPos(lfmKern2(k), lfmKern1(k), t2, ...\n lfmKern2(k).limit).';\n [g2KLocal, g1KLocal] = fhandleKernGradPosPos(lfmKern2(k), lfmKern1(k), ...\n t2, lfmKern2(k).limit, covGrad.', coeffPosPos.');\n g1Kern(k,:) = g1Kern(k, :) + g1KLocal;\n g2Kern(k,:) = g2Kern(k, :) + g2KLocal;\n VelPos = VelPos + fhandleKernVelPos(lfmKern2(k), lfmKern1(k), ...\n t2, lfmKern2(k).limit).';\n [g2KLocal, g1KLocal] = fhandleKernGradVelPos(lfmKern2(k), lfmKern1(k), ...\n t2, lfmKern2(k).limit, covGrad.', coeffVelPos.');\n g1Kern(k,:) = g1Kern(k, :) + g1KLocal;\n g2Kern(k,:) = g2Kern(k, :) + g2KLocal;\nend\n[gcAlpha, gcOmega] = fhandleMeanGradParam(lfmKern1(1), t1, 'Pos');\n[geAlpha, geOmega] = fhandleMeanGradParam(lfmKern1(1), t1, 'Vel');\n[gradAlpha, gradOmega] = getLocalGradAlphaOmega(lfmKern1);\ng1Pos = fhandleMeanGradSwitching(lfmKern1(1), t1, 'Pos');\nh1Vel = fhandleMeanGradSwitching(lfmKern1(1), t1, 'Vel');\ngsp1Kern = zeros(1, length(lfmKern1));\ngsp2Kern = zeros(1, length(lfmKern1));\n% This means that are only two switching points involved, t1\n% and t0 appear in k, like k_{ff}(t1-t0,t'-t0) and\n% k_{mf}(t1-t0,t'-t0). The other points appear in c1(t - t1)\n% and e1(t - t1)\nfor k=1:length(lfmKern1)\n temp = fhandleKernGradSwitchingPosPos1(lfmKern2(k), lfmKern1(k), t2, lfmKern2(k).limit).';\n gsp2Kern(k) = gsp2Kern(k) - sum(sum((coeffPosPos*temp).*covGrad));\n gsp1Kern(k) = gsp1Kern(k) + sum(sum((coeffPosPos*temp).*covGrad));\n temp = fhandleKernGradSwitchingPosPos2(lfmKern2(k), lfmKern1(k), t2, lfmKern2(k).limit).';\n gsp2Kern(k) = gsp2Kern(k) - sum(sum((coeffPosPos*temp).*covGrad));\n temp = fhandleKernGradSwitchingVelPos1(lfmKern1(k), lfmKern2(k), lfmKern2(k).limit, t2);\n gsp2Kern(k) = gsp2Kern(k) - sum(sum((coeffVelPos*temp).*covGrad));\n gsp1Kern(k) = gsp1Kern(k) + sum(sum((coeffVelPos*temp).*covGrad));\n temp = fhandleKernGradSwitchingVelPos2(lfmKern2(k), lfmKern1(k), t2, lfmKern2(k).limit).';\n gsp2Kern(k) = gsp2Kern(k) - sum(sum((coeffVelPos*temp).*covGrad));\nend\nif isempty(generalConst{i,j})\n matGradAlpha = gcAlpha*PosPos + geAlpha*VelPos;\n matGradOmega = gcOmega*PosPos + geOmega*VelPos;\n gCoeff = gradAlpha*sum(sum(matGradAlpha.*covGrad)) + ...\n gradOmega*(sum(sum(matGradOmega.*covGrad)));\n matGradSp1 = g1Pos*PosPos + h1Vel*VelPos;\n gsp1 = - sum(sum(matGradSp1.*covGrad));\n g3(i) = gsp1Mean + sum(gsp1Kern) + gsp1; % switching point 1\n g3(j) = gsp2Mean + sum(gsp2Kern); % switching point 2\nelse\n constGradAlpha = generalConstGrad{1}{i,j};\n constGradOmega = generalConstGrad{2}{i,j};\n constVal = generalConst{i,j};\n % Derivative wrt parameters\n matGradAlpha = (constVal(1,1)*gcAlpha + constGradAlpha(1,1)*c1 ...\n + constVal(2,1)*geAlpha + constGradAlpha(2,1)*e1)*PosPos ...\n + (constVal(1,2)*gcAlpha + constGradAlpha(1,2)*c1 ...\n + constVal(2,2)*geAlpha + constGradAlpha(2,2)*e1)*VelPos;\n matGradOmega = (constVal(1,1)*gcOmega + constGradOmega(1,1)*c1 ...\n + constVal(2,1)*geOmega + constGradOmega(2,1)*e1)*PosPos ...\n + (constVal(1,2)*gcOmega + constGradOmega(1,2)*c1 ...\n + constVal(2,2)*geOmega + constGradOmega(2,2)*e1)*VelPos;\n gCoeff = gradAlpha*sum(sum(matGradAlpha.*covGrad)) + ...\n gradOmega*(sum(sum(matGradOmega.*covGrad)));\n % Derivative wrt switching points\n % Firts, notice that gsp1Kern doesn't correspond to the switching point\n % of the interval i (or say 1). It's just the derivative of the inner\n % switching point that lead to the actual switching point for the\n % interval 1. So we rename it first.\n gspInt = sum(gsp1Kern);\n % Compute the derivative of the swicthing point i, not appearing in the\n % constant\n matGradSp1 = (constVal(1,1)*g1Pos + constVal(2,1)*h1Vel)*PosPos + ...\n (constVal(1,2)*g1Pos + constVal(2,2)*h1Vel)*VelPos;\n gsp1 = - sum(sum(matGradSp1.*covGrad));\n % Compute the derivatives for all the switching points apearing in the\n % constant\n constGradSPoint = generalConstGrad{3}{i,j};\n numberSP = size(constGradSPoint,2);\n gspInBetween = zeros(1, numberSP);\n for k=1:numberSP\n temp = (constGradSPoint(1,k)*c1 + constGradSPoint(3,k)*e1)*PosPos + ...\n (constGradSPoint(2,k)*c1 + constGradSPoint(4,k)*e1)*VelPos;\n gspInBetween(k) = sum(sum(temp.*covGrad));\n end\n % Assign derivatives wrt all other switching points, with a correction\n % for the derivative of the innermost switching point in the constant\n gspInBetween(end) = gspInBetween(end) + gspInt;\n g3(i) = gsp1Mean + gsp1 + gspInBetween(1);\n g3(j) = gsp2Mean + sum(gsp2Kern);\n g3(j+1:i-1) = fliplr(gspInBetween(2:end));\nend\n% Assign derivatives wrt first system\ng1{1} = g1Mean + sum(g1Kern(:,1:3), 1) + gCoeff; % mass 1, spring 1, damper 1\ng1{2} = g1Kern(:,4).'; % inverse widths\ng1{3} = g1Kern(:,5).'; % seinsitivities 1\n% Assign derivatives wrt second system\ng2{1} = g2Mean + sum(g2Kern(:,1:3), 1); % mass 2, spring 2, damper 2\ng2{2} = g2Kern(:,4).'; % inverse widths\ng2{3} = g2Kern(:,5).';\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/kern/sdlfmaXsdlfmaKernGradientBlockIGJ.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6825737473266735, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.30147439856953856}} {"text": "function [cnt1, cnt2] = elec1020_follow(pnt, dhk, v1, v2, v3, feedback)\n\n% ELEC1020_FOLLOW\n\n% Copyright (C) 2003, Robert Oostenveld\n%\n% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org\n% for the documentation and details.\n%\n% FieldTrip is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% FieldTrip is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with FieldTrip. If not, see .\n\nif nargin<6\n feedback = false;\nend\n\n% compute the distribution of edge lengths\nedge = [\n pnt(dhk(:,1),:) - pnt(dhk(:,2),:)\n pnt(dhk(:,2),:) - pnt(dhk(:,3),:)\n pnt(dhk(:,3),:) - pnt(dhk(:,1),:)\n ];\nedgelength = sqrt(sum(edge.^2,2));\n\n% the tolerance depends on the edge length\ntolerance = min(edgelength)*1e-6;\ntolerance_limit = min(edgelength)*1e-3;\n\nnpnt = size(pnt,1);\nndhk = size(dhk,1);\n\npside = nan(1,npnt);\nfor i=1:npnt\n % determine on which side of the plane each vertex lies\n pside(i) = ptriside(v1, v2, v3, pnt(i,:), tolerance);\nend\n\n% dcut = zeros(ndhk,1);\n% for i=1:ndhk\n% % find the triangles that are intersected by the plane\n% if sum(pside(dhk(i,:))==0)==2\n% dcut(i) = 1;\n% elseif sum(pside(dhk(i,:))==0)==1 & sum(pside(dhk(i,:))==1)==1 & sum(pside(dhk(i,:))==-1)==1\n% dcut(i) = 1;\n% elseif sum(pside(dhk(i,:))==1)==2 & sum(pside(dhk(i,:))==-1)==1\n% dcut(i) = 1;\n% elseif sum(pside(dhk(i,:))==1)==1 & sum(pside(dhk(i,:))==-1)==2\n% dcut(i) = 1;\n% end\n% end\ntmp = pside(dhk);\ndcut = true(ndhk,1);\ndcut(all(tmp== 1,2)) = false;\ndcut(all(tmp==-1,2)) = false;\n\n% continue working with only the intersecting triangles\ndhk = dhk(dcut,:);\nndhk = size(dhk,1);\n\n% for each triangle determine the neighbouring triangles\nneighb = zeros(ndhk,ndhk);\nfor i=1:ndhk\n for j=(i+1):ndhk\n if dhk(i,1)==dhk(j,1)\n neighb(i,j) = 1;\n elseif dhk(i,1)==dhk(j,2)\n neighb(i,j) = 1;\n elseif dhk(i,1)==dhk(j,3)\n neighb(i,j) = 1;\n elseif dhk(i,2)==dhk(j,1)\n neighb(i,j) = 1;\n elseif dhk(i,2)==dhk(j,2)\n neighb(i,j) = 1;\n elseif dhk(i,2)==dhk(j,3)\n neighb(i,j) = 1;\n elseif dhk(i,3)==dhk(j,1)\n neighb(i,j) = 1;\n elseif dhk(i,3)==dhk(j,2)\n neighb(i,j) = 1;\n elseif dhk(i,3)==dhk(j,3)\n neighb(i,j) = 1;\n else\n neighb(i,j) = 0;\n end\n neighb(j,i) = neighb(i,j);\n end\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% make a contour from v1 via v2 to v3\n\n% find the nearest triangle on which point v1 projects\nv1_dist = inf;\nfor i=1:ndhk\n % shift a fraction towards v2 to avoid starting in the vertex of a wrong triangle\n [proj, dist] = ptriproj(pnt(dhk(i,1),:), pnt(dhk(i,2),:), pnt(dhk(i,3),:), v1+tolerance*(v2-v1)/norm(v2-v1), 1);\n if distncnt)\n tolerance = 2*tolerance;\n if tolerance>=tolerance_limit\n ft_warning('premature end of contour')\n break\n else\n ft_warning('increasing tolerance');\n end\n end\n \n % stop if we arrive on the triangle with the endpoint\n if pntdist(prev_proj, v3_proj) params.em1_params.max_iters\n return\n end\n % Shift the centered events in time by the current estimate of the\n % flow.\n time_shifted_points = centered_events(1:2,:) + ...\n bsxfun(@times, flow,(target_time - centered_events(3,:)));\n\n % Only compute the event window once.\n if isempty(event_window)\n event_window = time_shifted_points(1, :) >= -params.window_size/2 & ...\n time_shifted_points(2, :) >= -params.window_size/2 & ...\n time_shifted_points(1, :) <= params.window_size/2 & ...\n time_shifted_points(2, :) <= params.window_size/2;\n n_in_window = sum(event_window);\n \n % Don't bother optimizing if there aren't enough events.\n if n_in_window < params.min_events_for_em\n return\n end\n \n centered_events = centered_events(:, event_window);\n time_shifted_points = time_shifted_points(:, event_window);\n % params.max_distance = n_in_window / 400;\n end\n \n % Scale the events so that the computed distances are equal to\n % (x1-x2)/(2*sigma^2). Saves us having to divide all the\n % correspondences later.\n normalized_events = time_shifted_points' / (sqrt(2) * params.em1_params.sigma);\n \n % The KD tree allows us to compute distances between neighboring\n % events, while also performing outlier rejection. Unfortunately, as\n % the time shifted events change every iteration, it must also be\n % reconstructed at every iteration.\n kdtree = KDTreeSearcher(...\n normalized_events, ...\n 'Distance', ...\n 'euclidean');\n \n % Threshold distances by the Malhalanobis distance.\n [neighbors_cell, distances_cell] = rangesearch(...\n kdtree, ...\n normalized_events, ...\n params.em1_params.max_distance);\n\n distancesstacked = cell2mat(cellfun(...\n @transpose, distances_cell, 'UniformOutput', false))';\n\n % Can't solve for flow without any correspondences :(\n if isempty(distancesstacked)\n return\n end\n \n % Number of neighbors for each event.\n % NOTE: 'length' is not the same as @length\n num_neighbors_per_event = cellfun('length', neighbors_cell);\n \n neighbor_inds = cell2mat(cellfun(...\n @transpose, neighbors_cell, 'UniformOutput', false))';\n \n event_inds = repelem(1:n_in_window, num_neighbors_per_event);\n \n % The event to neighbor graph is undirected, so no need to double count\n % the event-neighbor correspondences.\n valid_correspondences = neighbor_inds > event_inds;\n \n neighbor_inds = neighbor_inds(valid_correspondences);\n event_inds = event_inds(valid_correspondences);\n distancesstacked = distancesstacked(valid_correspondences);\n \n % Distances are already scaled by the variance. Note that the original\n % equation in the paper is the sum of the product of two weights. Here\n % we simplify it with a single weight for speed.\n weights = exp(-distancesstacked);\n \n %% Simultaneously minimize over flow and translation.\n neighbor_events = centered_events(:, neighbor_inds);\n original_events = centered_events(:, event_inds);\n \n % These are the X and D matrices specified in the original paper,\n % except the weighting is handled by multiplying the D with the full\n % weight.\n X = original_events(1:2, :) - neighbor_events(1:2, :);\n D = original_events(3, :)-neighbor_events(3, :);\n weighted_D = bsxfun(@times, D, weights);\n DDT = weighted_D*D';\n XDT = X*weighted_D';\n \n flow = XDT/DDT;\n \n %% Calculate change in flow, plot debug information.\n if (norm(flow - prev_flow) < params.em1_params.min_err)\n break;\n end\n \n delta_flows(num_iter+1) = norm(flow - prev_flow);\n prev_flow = flow;\n \n if params.debug\n set(0, 'CurrentFigure', fig)\n subplot(2,1,1)\n plot(delta_flows(delta_flows > 0),'b')\n title('EM1 change in flow (convergence criterion)')\n xlim([0 params.em1_params.max_iters])\n \n subplot(2,1,2)\n if (~isempty(scatter_plot_handle))\n delete(scatter_plot_handle)\n end\n scatter_plot_handle = scatter(...\n time_shifted_points(1, :), ...\n time_shifted_points(2, :), 'r.');\n \n axis equal\n axis([-params.window_size/2-5 params.window_size/2+5 -params.window_size/2-5 params.window_size/2+5])\n axis ij\n title('EM1 Time shifted events')\n pause(0.01)\n end\n \n num_iter = num_iter + 1;\nend\n\nif params.debug\n pause(0.5)\nend\n\nflow_out = flow;\n\n% Calculate the final shifted events to be used in EM2 later.\ndt = events(3, end) - events(3, 1);\ncentered_events = events;\ncentered_events(1:2, :) = bsxfun(@minus, events(1:2, :), feature_pos + flow * dt);\ntime_shifted_points = centered_events(1:2, :) + ...\n bsxfun(@times, flow,(events(3, end)-centered_events(3, :)));\n\n% Make the window a little bigger.\nwindow_size = round(params.window_size * 1.5);\n\nevent_window = time_shifted_points(1, :) >= -window_size/2 & ...\n time_shifted_points(2, :) >= -window_size/2 & ...\n time_shifted_points(1, :) <= window_size/2 & ...\n time_shifted_points(2, :) <= window_size/2;\n\ntime_shifted_points_out = time_shifted_points(:, event_window);\nend", "meta": {"author": "daniilidis-group", "repo": "event_feature_tracking", "sha": "b29f85f18121bef638fc117922038dbad9de7068", "save_path": "github-repos/MATLAB/daniilidis-group-event_feature_tracking", "path": "github-repos/MATLAB/daniilidis-group-event_feature_tracking/event_feature_tracking-b29f85f18121bef638fc117922038dbad9de7068/EventFeatureTracking/Tracker/em1_flow.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.30096313101869365}} {"text": "close all\nclear\n\n%------------------------------------------------------------------------------------------\nnb = 1000;%Total number of initial states\nnmpcd=zeros(1,nb);%Store computing time for one time-step for NMPC-DCBF\nimpcd=zeros(1,nb);%Store computing time for one time-step for iMPC-DCBF\nnmpcinf=zeros(1,1);%Store infeasible rate for one time-step for NMPC-DCBF\nimpcinf=zeros(1,1);%Store infeasible rate for one time-step for iMPC-DCBF\ni=24;%i is number of horozon\nts = 1;%Total time steps\nload(gamma1_0p6gamma2_0p6\\InitialStateData');%Load the generated 1000 initial states\n[a, b, c, d]=compare(i,ts,nb,InitialMat);%Involves NMPC-DCBF and iMPC-DCBF\nnmpcd(1,:)=a;\nimpcd(1,:)=b;\nnmpcinf(1,1)=c;\nimpcinf(1,1)=d;\nnmpcplot1=nmpcd(1,:);\nnmpcplot1(nmpcplot1==-1)=[];%Eliminate infeasible one time-step trajectories\nimpcplot1=impcd(1,:);\nimpcplot1(impcplot1==-1)=[];%Eliminate infeasible one time-step trajectories\n\nsave('timecom24','nmpcplot1','impcplot1');\nsave('feasibility24','nmpcinf','impcinf');\n\ndistnmpc = fitdist(nmpcplot1','Normal');\ndistimpc = fitdist(impcplot1','Normal');\nmu1=distnmpc.mu;%Get mean of sample of computing time for NMPC-DCBF\nmu2=distimpc.mu;%Get mean of sample of computing time for iMPC-DCBF\nsigma1=distnmpc.sigma;%Get variance of sample of computing time for NMPC-DCBF\nsigma2=distimpc.sigma;%Get variance of sample of computing time for iMPC-DCBF\n\n\n%Initialize atmosphere parameters\nfunction [tnmpc, timpc, ratiotnmpc, ratiotimpc]=compare(N11,ttsim,samplen,InitialMat)\ntnmpc=[];\ntimpc=[];\nfor i=1:samplen\nN1=N11;\ntsim=ttsim;\nxini1=InitialMat(1,i);\nyini1=InitialMat(2,i);\nthetaini1=InitialMat(3,i);\nvini1=InitialMat(4,i);\nx01=[xini1;yini1;thetaini1;vini1];\nx02=[xini1 yini1 thetaini1 vini1];\nt1 = nmpcdcbf(x01, N1, tsim);\nt2 = impcdcbf(x02, N1, tsim);\ntindex=[N11 i];\ndisp(tindex);\ntnmpc=[tnmpc t1];%Computing time for NMPC-DCBF\ntimpc=[timpc t2];%Computing time for iMPC-DCBF\nend\nnnmpc1 = length(tnmpc);\nnimpc1 = length(timpc);\ntnmpcs = tnmpc;\ntimpcs = timpc;\ntnmpcs(tnmpcs==-1)=[];\ntimpcs(timpcs==-1)=[];\nnnmpc2 = length(tnmpcs);\nnimpc2 = length(timpcs);\nratiotnmpc = (nnmpc1-nnmpc2)/nnmpc1;%Infeasible rate for NMPC-DCBF\nratiotimpc = (nimpc1-nimpc2)/nimpc1;%Infeasible rate for iMPC-DCBF\nend\n\n\n\n\n\nfunction t1 = nmpcdcbf(x00, N1, ttsim)\n%% General Flags\nrun_nmpc_dcbf_one = true;\nrun_nmpc_dcbf_multiple = true;\n\n%% Setup and Parameters\nx0 = x00;\ndt = 0.1;\ntime_total = ttsim *dt;\nP = zeros(4,4);%Weight matrix P\nP(1,1) = 10; P(2,2) = 10; P(3,3) = 10;P(4,4) = 10;\nQ = zeros(4,4);%Weight matrix Q\nQ(1,1) = 10; Q(2,2) = 10; Q(3,3) = 10;Q(4,4) = 10;\nR = zeros(4,4);%Weight matrix R\nR(1,1) = 1; R(2,2) = 1;R(3,3) = 1000;R(4,4) = 1000;\n%Variables range as below\nxmin = [-10; -10; -10;-10];\nxmax = [10; 10; 10;10];\numin = [-7; -5;-inf;-inf];\numax = [7; 5;inf;inf];\n\n%% Discrete-time unicycle model\nsystem.dt = dt;\nsystem.A = [1 0 0 0;\n 0 1 0 0;\n 0 0 1 0;\n 0 0 0 1];\nsystem.B = [x0(4,1)*cos(x0(3,1))*dt;\n x0(4,1)*sin(x0(3,1))*dt;\n 0;\n 0];\nsystem.C =[0 0 0 0;\n 0 0 0 0;\n 1*dt 0 0 0;\n 0 1*dt 0 0];\nsystem.xl = xmin;\nsystem.xu = xmax;\nsystem.ul = umin;\nsystem.uu = umax;\n\n%% NMPC-DCBF parameters\nparams_nmpc_dcbf.Q = Q;\nparams_nmpc_dcbf.R = R;\nparams_nmpc_dcbf.P = P;\nparams_nmpc_dcbf.gamma1 = 0.6;\nparams_nmpc_dcbf.gamma2 = 0.6;\n\n%% Obstacle\nobs.pos1 = [0; 0];\nobs.r1 = 1;\n\n\n\n%% Simulate NMPC-DCBF with other N\nparams_nmpc_dcbf.N = N1;\nif run_nmpc_dcbf_one\n fprintf('Run NMPC-DCBF-24\\n');\n controller_nmpc_dcbf_multiple24 = NMPCDCBF2(x0, system, params_nmpc_dcbf);%Highest order mcbf=2\n controller_nmpc_dcbf_multiple24.obs = obs;\n controller_nmpc_dcbf_multiple24.sim(time_total);\nend\nt1=controller_nmpc_dcbf_multiple24.tt;\nend\n\n\nfunction t2=impcdcbf(x00, N1, ttsim)\nt2=0;\nxo = 0;\nyo = 0;\nr = 1;\nN = N1;%Number of horizon\nK1 = 1000;%Maximum iteration times, jmax\nK = 1000;%Maximum iteration times, jmax\ndt = 0.1;\ngamma1 = 6;\ngamma2 = 6;\nnsim = ttsim;\n\ntic;\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 = x00;\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);%First order CBF constraints\nlcbf = -abc(3, :);\nlcbf(1) = [];\nlcbf = lcbf';\nucbf = inf * ones(N, 1);\nA2cbf = cbfmat2(abc, nx, nu, dt, gamma1, gamma2, x0);%Second order CBF constraints\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];\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!')\n t2=-1;\n return\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)%Iterations for the first time-step\n storagex = ctrlx;%store the state variables and inputs in order to compare them with the next iteration\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];\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 t2=-1;\n return\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);\nt2=t2+toc;\nreturn\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)%Iterations for the left time steps\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];\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 t2=-1;\n return\n end\n ctrlx = res.x(1:(N+1)*nx);\n ctrlu = res.x((N+1)*nx+1:(N+1)*nx+N*nu);\n x0 = ctrlx(1:nx);\n testx0 = [testx0 x0];\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\nend\n\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/benchmark/gamma1-0p6gamma2-0p6/test_each_horizon/test_N24.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.3005463427108183}} {"text": "% gsn - training an GSN (stochastic backprop)\n% Copyright (C) 2013 KyungHyun Cho\n%\n% This program is free software; you can redistribute it and/or\n% modify it under the terms of the GNU General Public License\n% as published by the Free Software Foundation; either version 2\n% of the License, or (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n%\nfunction [G] = gsn(G, patches, n_walkback, valid_patches, valid_portion);\n\nif nargin < 3\n n_walkback = G.structure.n_layers * 2;\nend\n\nvalid_err = 0;\n\nif nargin < 4\n early_stop = 0;\n valid_patches = [];\n valid_portion = 0;\nelse\n early_stop = 1;\n valid_err = -Inf;\n valid_best_err = -Inf;\n valid_violate_cnt = 0;\nend\n\nactual_lrate = G.learning.lrate;\n\nn_samples = size(patches, 1);\n\nlayers = G.structure.layers;\nn_layers = length(layers);\n\nif layers(1) ~= size(patches, 2)\n error('Data is not properly aligned');\nend\n\nminibatch_sz = G.learning.minibatch_sz;\nn_minibatches = ceil(n_samples / minibatch_sz);\n\nn_epochs = G.iteration.n_epochs;\n\nmomentum = G.learning.momentum;\nweight_decay = G.learning.weight_decay;\n\nbiases_grad = cell(n_layers, 1);\nW_grad = cell(n_layers, 1);\nbiases_grad_old = cell(n_layers, 1);\nW_grad_old = cell(n_layers, 1);\nfor l = 1:n_layers\n biases_grad{l} = zeros(size(G.biases{l}))';\n if l < n_layers\n W_grad{l} = zeros(size(G.W{l}));\n end\n biases_grad_old{l} = zeros(size(G.biases{l}))';\n if l < n_layers\n W_grad_old{l} = zeros(size(G.W{l}));\n end\nend\n\nmin_recon_error = Inf;\nmin_recon_error_update_idx = 0;\nstopping = 0;\n\ndo_normalize = G.do_normalize;\ndo_normalize_std = G.do_normalize_std;\n\nif G.data.binary == 0\n if do_normalize == 1\n % make it zero-mean\n patches_mean = mean(patches, 1);\n patches = bsxfun(@minus, patches, patches_mean);\n end\n\n if do_normalize_std ==1\n % make it unit-variance\n patches_std = std(patches, [], 1);\n patches = bsxfun(@rdivide, patches, patches_std);\n end\nend\n\nanneal_counter = 0;\nactual_lrate0 = actual_lrate;\n\nrerr_ma = 0;\n\n% try\n% use_gpu = gpuDeviceCount;\n% catch errgpu\n% use_gpu = false;\n% disp(['Could not use CUDA. Error: ' errgpu.identifier])\n% end\nuse_gpu = 0;\n\n% figure;\n\nfor step=1:n_epochs\n if G.verbose\n fprintf(2, 'Epoch %d/%d: ', step, n_epochs)\n end\n if use_gpu\n % push\n G = push_to_gpu (G);\n end\n\n for mb=1:n_minibatches\n G.iteration.n_updates = G.iteration.n_updates + 1;\n\n mb_start = (mb - 1) * minibatch_sz + 1;\n mb_end = min(mb * minibatch_sz, n_samples);\n\n % p_0\n v0 = patches(mb_start:mb_end, :);\n mb_sz = size(v0,1);\n\n if use_gpu > 0\n v0 = gpuArray(single(v0));\n end\n\n % add error\n v0_clean = v0;\n\n % forward pass\n h0 = cell(n_layers, n_walkback * 2 + 1);\n v1clean = cell(1, n_walkback * 2 + 1);\n occupied = zeros(n_layers, n_walkback * 2 + 1);\n\n h0{1,1} = v0;\n v1clean{1,1} = v0;\n occupied(1,1) = 1;\n\n for wi = 1:(n_walkback * 2 + 1)\n for l = 1:min(wi,n_layers)\n if sum(occupied(1, 2:end)) == n_walkback\n break;\n end\n \n if l == 2\n if G.data.binary == 0 && G.noise.level > 0\n if use_gpu\n h0{l-1,wi-1} = h0{l-1,wi-1} + G.noise.level * parallel.gpu.GPUArray.randn(size(h0{l-1,wi-1}));\n else\n h0{l-1,wi-1} = h0{l-1,wi-1} + G.noise.level * randn(size(h0{l-1,wi-1}));\n end\n end\n \n if G.noise.drop > 0\n mask = binornd(1, 1-G.noise.drop, size(h0{l-1,wi-1}));\n if G.data.binary\n sandp = binornd(1, 0.5, size(h0{l-1,wi-1}));\n else\n sandp = zeros(size(h0{l-1,wi-1}));\n end\n h0{l-1,wi-1} = h0{l-1,wi-1} .* mask + (1 - mask) .* sandp;\n clear mask;\n end\n end\n\n if l == 1 && wi == 1\n continue;\n end\n\n prev_exist = 0;\n\n if l > 1 && occupied(l-1, wi-1) == 1\n prev_exist = prev_exist + 1;\n end\n if l < n_layers && occupied(l+1, wi-1) == 1\n prev_exist = prev_exist + 1;\n end\n\n if prev_exist == 0\n continue;\n end\n\n occupied(l, wi) = 1;\n h0{l, wi} = zeros(mb_sz, G.structure.layers(l));\n if l > 1 && occupied(l-1, wi-1) == 1\n h0{l, wi} = h0{l, wi} + h0{l-1, wi-1} * G.W{l-1};\n end\n if l < n_layers && occupied(l+1, wi-1) == 1\n h0{l, wi} = h0{l, wi} + h0{l+1, wi-1} * G.W{l}';\n end\n h0{l, wi} = bsxfun(@plus, h0{l, wi}, G.biases{l}');\n\n % pre-sigmoid noise\n if l > 1\n if G.hidden.add_noise(l)\n if use_gpu\n h0{l, wi} = h0{l, wi} + G.hidden.noise_level * parallel.gpu.GPUArray.randn(mb_sz, G.structure.layers(l));\n else\n h0{l, wi} = h0{l, wi} + G.hidden.noise_level * randn(mb_sz, G.structure.layers(l));\n end\n end\n end\n\n if l == 1 \n if G.data.binary\n h0{l, wi} = sigmoid(h0{l, wi});\n end\n v1clean{l, wi} = h0{l, wi};\n else\n h0{l, wi} = sigmoid(h0{l, wi}, G.hidden.use_tanh);\n end\n \n % FIXME: unable to train a GSN with post-sigmoid noise.\n% % post-sigmoid noise\n% if l > 1\n% if G.hidden.add_noise(l)\n% if use_gpu\n% h0{l, wi} = h0{l, wi} + G.hidden.noise_level * parallel.gpu.GPUArray.randn(mb_sz, G.structure.layers(l));\n% else\n% h0{l, wi} = h0{l, wi} + G.hidden.noise_level * randn(mb_sz, G.structure.layers(l));\n% end\n% end\n% end\n end\n\n if sum(occupied(1, 2:end)) == n_walkback\n break;\n end\n end\n \n % reset gradients\n for l = 1:n_layers\n biases_grad{l} = 0 * biases_grad{l};\n if l < n_layers\n W_grad{l} = 0 * W_grad{l};\n end\n end\n\n % error backprop\n delta = cell(n_layers, n_walkback * 2 + 1);\n\n rerr = 0;\n for wi = 2:(n_walkback * 2 + 1)\n if occupied(1, wi) \n rerr = rerr + mean(sum((v1clean{1, wi} - v0_clean).^2,2));\n end\n end\n\n\n if use_gpu > 0\n rerr = gather(rerr);\n end\n\n rerr_ma = rerr * 0.1 + rerr_ma * 0.9;\n\n G.signals.recon_errors = [G.signals.recon_errors rerr];\n\n for wi = (n_walkback * 2 + 1):-1:1\n for l = 1:min(wi,n_layers)\n if occupied(l, wi) == 0\n continue;\n end\n\n delta{l, wi} = zeros(mb_sz, G.structure.layers(l));\n\n if wi < (n_walkback * 2 + 1)\n if l > 1 && occupied(l-1,wi+1) == 1\n delta{l, wi} = delta{l, wi} + delta{l-1,wi+1} * G.W{l-1};\n end\n if l < n_layers && occupied(l+1,wi+1) == 1\n delta{l, wi} = delta{l, wi} + delta{l+1,wi+1} * G.W{l}';\n end\n end\n \n if l == 1 \n if G.data.binary && wi < (n_walkback * 2 + 1)\n delta{l, wi} = delta{l, wi} .* dsigmoid(h0{l, wi});\n end\n \n delta{l, wi} = delta{l, wi} + (v1clean{l, wi} - v0_clean);\n %delta{l, wi} = delta{l, wi} + (h0{l, wi} - v0_clean);\n else\n delta{l, wi} = delta{l, wi} .* dsigmoid(h0{l, wi}, G.hidden.use_tanh);\n end\n\n if wi > 1\n biases_grad{l} = biases_grad{l} + mean(delta{l, wi}, 1);\n if l > 1 && occupied(l-1,wi-1) == 1\n W_grad{l-1} = W_grad{l-1} + (h0{l-1, wi-1}' * delta{l, wi})/size(v0,1);\n end\n if l < n_layers && occupied(l+1,wi-1) == 1\n W_grad{l} = W_grad{l} + (delta{l, wi}' * h0{l+1, wi-1})/size(v0,1);\n end\n end\n end\n end\n\n % learning rate\n if G.adadelta.use\n % update\n for l = 1:n_layers\n biases_grad_old{l} = (1 - momentum) * biases_grad{l} + momentum * biases_grad_old{l};\n if l < n_layers\n W_grad_old{l} = (1 - momentum) * W_grad{l} + momentum * W_grad_old{l};\n end\n end\n\n if G.iteration.n_updates == 1\n adamom = 0;\n else\n adamom = G.adadelta.momentum;\n end\n\n for l = 1:n_layers\n if l < n_layers\n G.adadelta.gW{l} = adamom * G.adadelta.gW{l} + (1 - adamom) * W_grad_old{l}.^2;\n end\n\n G.adadelta.gbiases{l} = adamom * G.adadelta.gbiases{l} + (1 - adamom) * biases_grad_old{l}.^2';\n end\n\n for l = 1:n_layers\n dbias = -(biases_grad_old{l}' + ...\n weight_decay * G.biases{l}) .* (sqrt(G.adadelta.biases{l} + G.adadelta.epsilon) ./ ...\n sqrt(G.adadelta.gbiases{l} + G.adadelta.epsilon));\n G.biases{l} = G.biases{l} + dbias;\n\n G.adadelta.biases{l} = adamom * G.adadelta.biases{l} + (1 - adamom) * dbias.^2;\n clear dbias;\n\n if l < n_layers\n dW = -(W_grad_old{l} + ...\n weight_decay * G.W{l}) .* (sqrt(G.adadelta.W{l} + G.adadelta.epsilon) ./ ...\n sqrt(G.adadelta.gW{l} + G.adadelta.epsilon));\n G.W{l} = G.W{l} + dW;\n\n G.adadelta.W{l} = adamom * G.adadelta.W{l} + (1 - adamom) * dW.^2;\n\n clear dW;\n end\n\n end\n else\n if G.learning.lrate_anneal > 0 && (step >= G.learning.lrate_anneal * n_epochs)\n anneal_counter = anneal_counter + 1;\n actual_lrate = actual_lrate0 / anneal_counter;\n else\n if G.learning.lrate0 > 0\n actual_lrate = G.learning.lrate / (1 + G.iteration.n_updates / G.learning.lrate0);\n else\n actual_lrate = G.learning.lrate;\n end\n actual_lrate0 = actual_lrate;\n end\n\n G.signals.lrates = [G.signals.lrates actual_lrate];\n\n % update\n for l = 1:n_layers\n biases_grad_old{l} = (1 - momentum) * biases_grad{l} + momentum * biases_grad_old{l};\n if l < n_layers\n W_grad_old{l} = (1 - momentum) * W_grad{l} + momentum * W_grad_old{l};\n end\n end\n\n for l = 1:n_layers\n G.biases{l} = G.biases{l} - actual_lrate * (biases_grad_old{l}' + weight_decay * G.biases{l});\n if l < n_layers\n G.W{l} = G.W{l} - actual_lrate * (W_grad_old{l} + weight_decay * G.W{l});\n end\n end\n end\n\n if G.verbose == 1\n fprintf(2, '.%f.', rerr);\n end\n\n if use_gpu > 0\n clear v0 h0 h0d h0e v0_clean vr hr deltae deltad v1clean\n end\n\n if early_stop\n n_valid = size(valid_patches, 1);\n rndidx = randperm(n_valid);\n v0valid = gpuArray(single(valid_patches(rndidx(1:round(n_valid * valid_portion)),:)));\n valid_sz = size(v0valid, 1);\n\n valid0 = cell(n_layers, 1);\n valid0{1} = v0valid;\n for l = 2:n_layers\n valid0{l} = zeros(valid_sz, G.structure.layers(l));\n end\n\n valid0 = gsn_sample(G, valid0, 1);\n\n rerr = mean(sum((v0valid - valid0{1}).^2, 1));\n\n if use_gpu > 0\n rerr = gather(rerr);\n end\n\n G.signals.valid_errors = [G.signals.valid_errors rerr];\n\n if valid_err == -Inf\n valid_err = rerr;\n valid_best_err = rerr;\n valid_violate_cnt = 0;\n\n M_best = G;\n M_best = pull_from_gpu (M_best);\n else\n prev_err = valid_err;\n valid_err = 0.99 * valid_err + 0.01 * rerr;\n\n\n if step > G.valid_min_epochs\n if (1.1 * valid_best_err) < valid_err \n fprintf(2, 'Early-stop! %f, %f\\n', valid_err, valid_best_err);\n stopping = 1;\n break;\n end\n\n if valid_best_err <= valid_err\n valid_violate_cnt = valid_violate_cnt + 1;\n if valid_violate_cnt > (n_minibatches * G.valid_min_epochs)\n fprintf(2, 'Unable to improve! %f, %f\\n', valid_err, valid_best_err);\n stopping = 1;\n break;\n end\n else\n valid_violate_cnt = 0;\n end\n\n end\n\n if valid_err < valid_best_err\n valid_best_err = valid_err;\n\n G_best = G;\n G_best = pull_from_gpu (G_best);\n end\n end\n else\n if G.stop.criterion > 0\n if G.stop.criterion == 1\n if min_recon_error > G.signals.recon_errors(end)\n min_recon_error = G.signals.recon_errors(end);\n min_recon_error_update_idx = G.iteration.n_updates;\n else\n if G.iteration.n_updates > min_recon_error_update_idx + G.stop.recon_error.tolerate_count \n fprintf(2, '\\nStopping criterion reached (recon error) %f > %f\\n', ...\n G.signals.recon_errors(end), min_recon_error);\n stopping = 1;\n break;\n end\n end\n else\n error ('Unknown stopping criterion %d', G.stop.criterion);\n end\n end\n end\n\n if length(G.hook.per_update) > 1\n err = G.hook.per_update{1}(G, G.hook.per_update{2});\n\n if err == -1\n stopping = 1;\n break;\n end\n end\n \n end\n\n if use_gpu > 0\n % pull\n G = pull_from_gpu (G);\n end\n\n if length(G.hook.per_epoch) > 1\n err = G.hook.per_epoch{1}(G, G.hook.per_epoch{2});\n\n if err == -1\n stopping = 1;\n end\n end\n\n if stopping == 1\n break;\n end\n \n if G.verbose == 1\n fprintf(2, '\\n');\n end\n \n fprintf(2, 'Epoch %d/%d - recon_error: %f(%f) valid_error: %f\\n', step, n_epochs, rerr_ma, rerr, valid_err);\nend\n\nif use_gpu > 0\n % pull\n G = pull_from_gpu (G);\nend\n\nif early_stop\n G = G_best;\nend\n\nend\n\nfunction [G] = push_to_gpu (G)\n n_layers = length(G.structure.layers);\n\n % push\n for l = 1:n_layers\n if l < n_layers \n G.W{l} = gpuArray(single(G.W{l}));\n end\n G.biases{l} = gpuArray(single(G.biases{l}));\n end\n\n if G.adadelta.use\n for l = 1:n_layers\n if l < n_layers \n G.adadelta.gW{l} = gpuArray(single(G.adadelta.gW{l}));\n G.adadelta.W{l} = gpuArray(single(G.adadelta.W{l}));\n end\n G.adadelta.gbiases{l} = gpuArray(single(G.adadelta.gbiases{l}));\n G.adadelta.biases{l} = gpuArray(single(G.adadelta.biases{l}));\n end\n end\nend\n\nfunction [G] = pull_from_gpu (G)\n n_layers = length(G.structure.layers);\n\n\n for l = 1:n_layers\n if l < n_layers\n G.W{l} = gather(G.W{l});\n end\n G.biases{l} = gather(G.biases{l});\n end\n\n if G.adadelta.use\n for l = 1:n_layers\n if l < n_layers\n G.adadelta.W{l} = gather(G.adadelta.W{l});\n G.adadelta.gW{l} = gather(G.adadelta.gW{l});\n end\n G.adadelta.biases{l} = gather(G.adadelta.biases{l});\n G.adadelta.gbiases{l} = gather(G.adadelta.gbiases{l});\n end\n end\n\nend\n\n\n", "meta": {"author": "kyunghyuncho", "repo": "deepmat", "sha": "6fd133406b5d78e1b87e2f736e27cfb2024807af", "save_path": "github-repos/MATLAB/kyunghyuncho-deepmat", "path": "github-repos/MATLAB/kyunghyuncho-deepmat/deepmat-6fd133406b5d78e1b87e2f736e27cfb2024807af/gsn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6859494550081925, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.30032479060716666}}