{"text": "function [FluxCorrelations, PValues, TaxonomyInfo] = correlateFluxWithTaxonAbundance(abundancePath, fluxPath, infoFilePath, corrMethod)\n% Part of the Microbiome Modeling Toolbox. This function calculates and\n% plots the correlations between fluxes for one or more reactions of\n% interest in a number of microbiome samples and the relative microbe\n% abundance on different taxonomical levels in the same samples.\n% The function should be used after running mgPipe to identify correlations\n% between the computed metabolic profiles and specific taxa in the samples.\n%\n% USAGE\n%\n% [FluxCorrelations, PValues, TaxonomyInfo] = correlateFluxWithTaxonAbundance(abundancePath, fluxPath, taxonomy, corrMethod)\n%\n% INPUTS:\n% abundancePath: Path to the .csv file with the abundance data.\n% Needs to be in same format as example file\n% 'cobratoolbox/papers/018_microbiomeModelingToolbox/examples/normCoverage.csv'\n% fluxPath: Path to the .csv file with the fluxes for reactions \n% of interest with sample IDs as rows and reaction\n% IDs in microbiome community models as columns\n%\n% OPTIONAL INPUTS:\n% infoFilePath: Path to the spreadsheet with the taxonomy information\n% on organisms (default: AGORA_infoFile.xlsx)\n% corrMethod: Method to compute the linear correlation\n% coefficient. Allowed inputs: 'Pearson' (default),\n% 'Kendall', 'Spearman'.\n%\n% OUTPUTS:\n% FluxCorrelations: Structure with correlations between fluxes for each\n% reaction and abundances on taxon levels\n% PValues: p-values corresponding to each calculated\n% correlation\n% TaxonomyInfo: Taxonomical information on each taxon level \n%\n% .. Author: Almut Heinken, 03/2018\n% 10/2018: changed input to location of the csv file with the\n% abundance data\n% 01/2020: adapted to be suitable for pan-models, and\n% changed flux input to a csv file.\n\n% read the csv file with the abundance data\nabundance = readInputTableForPipeline(abundancePath);\nif isnumeric(abundance{2, 1})\n abundance(:, 1) = [];\nend\n% adapt IDs if neccessary\nabundance(1,2:end) = strrep(abundance(1,2:end),'-','_');\n\nfluxes = readInputTableForPipeline(fluxPath);\nfluxes(1,:) = strrep(fluxes(1,:),'microbiota_model_diet_','');\nfluxes(1,:) = strrep(fluxes(1,:),'microbiota_model_samp_','');\nfluxes(:,1) = strrep(fluxes(:,1),'microbiota_model_diet_','');\nfluxes(:,1) = strrep(fluxes(:,1),'microbiota_model_samp_','');\n\n% check if data is from same samples\nif ~isempty(setdiff(fluxes(1,2:end),abundance(1,2:end)))\n fluxes=fluxes';\n % if it still does not match\n if ~isempty(setdiff(fluxes(1,2:end),abundance(1,2:end)))\n error('Sample IDs in abundance and flux files do not agree!')\n end\nend\n\n% load database\ndatabase=loadVMHDatabase;\n\nfluxes(:,1)=strrep(fluxes(:,1),'EX_','');\nfluxes(:,1)=strrep(fluxes(:,1),'(e)','');\nfluxes(:,1)=strrep(fluxes(:,1),'[fe]','');\n% for i=2:size(fluxes,1)\n% fluxes{i,1}=database.metabolites{find(strcmp(database.metabolites(:,1),fluxes{i,1})),2};\n% end\n\n% Get the taxonomy information\nif exist('infoFilePath','var')\n taxonomy = readInputTableForPipeline(infoFilePath);\nelse\n taxonomy = readInputTableForPipeline('AGORA_infoFile.xlsx');\nend\n\nif ~exist('corrMethod', 'var') % Define correlation coefficient method if not entered\n corrMethod = 'Pearson';\nend\n\n% Calculate the abundance in each sample on all taxon levels\nTaxonomyLevels = {\n 'Phylum'\n 'Class'\n 'Order'\n 'Family'\n 'Genus'\n 'Species'\n};\n% extract the list of entries on each taxonomical level and prepare the\n% summarized abundance table\nfprintf('Calculating the relative abundances on all taxon levels. \\n')\nfor t = 1:size(TaxonomyLevels, 1)\n % find the columns corresponding to each taxonomy level and the list of\n % unique taxa\n taxonCol = find(strcmp(taxonomy(1, :), TaxonomyLevels{t}));\n % find and save all entries\n taxa = unique(taxonomy(2:end, taxonCol));\n % exclude unclassified entries\n taxa(strncmp('unclassified', taxa, taxonCol)) = [];\n TaxonomyLevels{t, 2} = taxa;\n for i = 1:length(taxa)\n SampleAbundance.(TaxonomyLevels{t}){1, i + 1} = taxa{i};\n for j = 2:size(abundance, 2)\n SampleAbundance.(TaxonomyLevels{t}){j, 1} = abundance{1, j};\n SampleAbundance.(TaxonomyLevels{t}){j, i + 1} = 0;\n end\n end\nend\n\n% Go through the abundance data and summarize taxon abundances for each\n% strain in at least one sample\n\n% Find the right column for the input data (strains, species,..)\nif sum(strncmp(abundance(:,1),'pan',3))==size(abundance,1)-1\nabundance(:,1)=regexprep(abundance(:,1),'pan','','once');\nend\ninputTaxa={};\nfor i=1:size(taxonomy,2)\n if ~isnumeric(taxonomy{2,i})\n taxa=strrep(taxonomy(:,i),' ','_');\n taxa=strrep(taxa,'.','_');\n taxa=strrep(taxa,'/','_');\n taxa=strrep(taxa,'-','_');\n taxa=strrep(taxa,'-','_');\n taxa=strrep(taxa,'[','');\n taxa=strrep(taxa,']','');\n taxa=strrep(taxa,')','');\n taxa=strrep(taxa,'__','_');\n if length(intersect(abundance(2:end,1),taxa))==size(abundance,1)-1\n inputTaxa=taxa;\n inputCol=i;\n break\n end\n end\nend\nif isempty(inputTaxa)\n error('Some taxa in the abundance file are not found in the taxonomy file!')\nend\n\nfor i = 2:size(abundance, 2)\n for j = 2:size(abundance, 1)\n for t = 1:size(TaxonomyLevels, 1)\n % find the taxon for the current strain\n taxonCol = find(strcmp(taxonomy(1, :), TaxonomyLevels{t}));\n if taxonCol >= inputCol\n findTax = taxonomy(find(strcmp(abundance{j, 1}, inputTaxa)), taxonCol);\n if isempty(strfind(findTax{1}, 'unclassified'))\n % find the taxon for the current strain in the sample abundance\n % variable\n findinSampleAbun = find(strcmp(findTax{1}, SampleAbundance.(TaxonomyLevels{t})(1, :)));\n % sum up the relative abundance\n if contains(version,'(R202') % for Matlab R2020a and newer\n SampleAbundance.(TaxonomyLevels{t}){i, findinSampleAbun} = SampleAbundance.(TaxonomyLevels{t}){i, findinSampleAbun} + abundance{j, i};\n else\n SampleAbundance.(TaxonomyLevels{t}){i, findinSampleAbun} = SampleAbundance.(TaxonomyLevels{t}){i, findinSampleAbun} + str2double(abundance{j, i});\n end\n end\n end\n end\n end\nend\n% remove the taxa not present in samples or only present in small abundances\nfor t = 1:size(TaxonomyLevels, 1)\n delArray = [];\n cnt = 1;\n for i = 2:size(SampleAbundance.(TaxonomyLevels{t}), 2)\n for j = 2:size(SampleAbundance.(TaxonomyLevels{t}), 1)\n abun(j - 1, 1) = SampleAbundance.(TaxonomyLevels{t}){j, i};\n end\n if sum(abun) < 0.005\n delArray(cnt, 1) = i;\n cnt = cnt + 1;\n end\n end\n SampleAbundance.(TaxonomyLevels{t})(:, delArray) = [];\nend\n% find the flux data for each reaction\nfprintf('Calculating the correlations between fluxes and abundances. \\n')\nfor i = 2:size(fluxes, 1)\n data = [];\n for m = 2:size(fluxes, 2)\n data(m - 1, 1) = str2double(string(fluxes{i, m}));\n end\n for t = 1:size(TaxonomyLevels, 1)\n FluxCorrelations.(TaxonomyLevels{t}){1, i} = fluxes{i, 1};\n PValues.(TaxonomyLevels{t}){1, i} = fluxes{i, 1};\n % find the abundance data for each taxon\n for j = 2:size(SampleAbundance.(TaxonomyLevels{t}), 2)\n FluxCorrelations.(TaxonomyLevels{t}){j, 1} = SampleAbundance.(TaxonomyLevels{t}){1, j};\n PValues.(TaxonomyLevels{t}){j, 1} = SampleAbundance.(TaxonomyLevels{t}){1, j};\n % find the abundance data for each sample\n dataTaxa = data;\n for k = 2:size(SampleAbundance.(TaxonomyLevels{t}), 1)\n % match with correct individual in flux table\n sampleInFluxes = find(strcmp(fluxes(1, :), SampleAbundance.(TaxonomyLevels{t}){k, 1}));\n dataTaxa(sampleInFluxes - 1, 2) = SampleAbundance.(TaxonomyLevels{t}){k, j};\n end\n % exclude NaNs\n dataTaxa(find(isnan(dataTaxa(:,1))),:)=[];\n dataTaxa(find(isnan(dataTaxa(:,2))),:)=[];\n % calculate the correlation with the given correlation coefficient method\n [RHO, PVAL] = corr(dataTaxa(:, 1), dataTaxa(:, 2), 'type', corrMethod);\n if isnan(RHO)\n RHO = 0;\n end\n if abs(RHO) < 0.0000000001\n RHO = 0;\n end\n FluxCorrelations.(TaxonomyLevels{t}){j, i} = RHO;\n PValues.(TaxonomyLevels{t}){j, i} = PVAL;\n end\n end\nend\n\n% remove entries that are only weak correlations and empty taxonomy entries\nfor t = 1:size(TaxonomyLevels, 1)\n cnt=1;\n delArray=[];\n for j=2:size(FluxCorrelations.(TaxonomyLevels{t}),2)\n if ~any(abs(cell2mat(FluxCorrelations.(TaxonomyLevels{t})(2:end,j))) > 0.3)\n delArray(cnt,1)=j;\n cnt=cnt+1;\n end\n end\n FluxCorrelations.(TaxonomyLevels{t})(:,delArray)=[];\n \n cnt=1;\n delArray=[];\n for j=2:size(FluxCorrelations.(TaxonomyLevels{t}),1)\n if ~any(abs(cell2mat(FluxCorrelations.(TaxonomyLevels{t})(j,2:end))) > 0.3)\n delArray(cnt,1)=j;\n cnt=cnt+1;\n end\n end\n FluxCorrelations.(TaxonomyLevels{t})(delArray,:)=[];\n\n FluxCorrelations.(TaxonomyLevels{t})(find(strcmp(FluxCorrelations.(TaxonomyLevels{t})(:,1),'')),:)=[];\nend\n\n% translate to metabolite descriptions\nfor t = 2:size(TaxonomyLevels, 1)\n for i=2:size(FluxCorrelations.(TaxonomyLevels{t}),2)\n try\n FluxCorrelations.(TaxonomyLevels{t}){1,i}=database.metabolites{find(strcmp(database.metabolites(:,1),FluxCorrelations.(TaxonomyLevels{t}){1,i})),2};\n catch\n warning('Flux label could not be translated to metabolite name.')\n end\n end\nend\n\n% export taxonomical information\ntaxonCol = 'Phylum';\n% remove unnecessary columns\ntaxonomy(:,taxonCol+1:end)=[];\n\nfor t = 2:size(TaxonomyLevels, 1)\n TaxonomyReduced=taxonomy;\n taxonCol = find(strcmp(taxonomy(1, :), TaxonomyLevels{t}));\n TaxonomyReduced(:,1:taxonCol-1)=[];\n % remove duplicate entries\n [C,IA] = unique(TaxonomyReduced(:,1),'stable');\n % remove unclassified taxa\n findUncl=find(contains(C,'unclassified'));\n IA(findUncl,:)=[];\n TaxonomyInfo.(TaxonomyLevels{t})=TaxonomyReduced(IA,:);\nend\n\nset(0, 'DefaultTextInterpreter', 'none')\n\n% Plot the calculated correlations.\nfor t = 1:length(TaxonomyLevels)\n data = string(FluxCorrelations.(TaxonomyLevels{t})(2:end, 2:end));\n data = str2double(data);\n\n if size(FluxCorrelations.(TaxonomyLevels{t}),2) > 5 && size(FluxCorrelations.(TaxonomyLevels{t}),1) > 5\n if size(FluxCorrelations.(TaxonomyLevels{t}),2) < 50\n cgo = clustergram(data,...\n 'RowLabels', FluxCorrelations.(TaxonomyLevels{t})(2:end,1),...\n 'ColumnLabels', FluxCorrelations.(TaxonomyLevels{t})(1,2:end),...\n 'ColumnLabelsRotate', 45, ...\n 'Cluster', 'all', ...\n 'ShowDendrogram','True', ...\n 'symmetric','False', ...\n 'colormap', 'turbo' ...\n );\n else\n cgo = clustergram(data,...\n 'RowLabels', FluxCorrelations.(TaxonomyLevels{t})(2:end,1),...\n 'Cluster', 'all', ...\n 'ShowDendrogram','True', ...\n 'symmetric','False', ...\n 'colormap', 'turbo' ...\n );\n end\n h = plot(cgo);\n set(h,'TickLabelInterpreter','none');\n colorbar(h)\n end\nend\n\nend\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/src/analysis/multiSpecies/microbiomeModelingToolbox/additionalAnalysis/correlateFluxWithTaxonAbundance.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.36658972940200996, "lm_q1q2_score": 0.19900810408049538}} {"text": "function [sampft, sampyt] = gp_rnd(gp, x, y, varargin)\n%GP_RND Random draws from the posterior Gaussian process\n%\n% Description\n% [SAMPFT, SAMPYT] = GP_RND(GP, X, Y, XT, OPTIONS) takes a\n% Gaussian process structure, record structure (from gp_mc) or\n% array (from gp_ia) GP together with a matrix XT of input\n% vectors, matrix X of training inputs and vector Y of training\n% targets, and returns a random sample SAMPFT and SAMPYT from\n% the posterior distribution p(ft|x,y,xt) and the predictive\n% distribution p(yt|x,y,xt) at locations XT.\n%\n% OPTIONS is optional parameter-value pair\n% nsamp - determines the number of samples (default = 1).\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\n% value\n% for ith case. \n% fcorr - Method used for latent marginal posterior corrections. \n% Default is 'off'. Possible methods are 'fact' for EP\n% and either 'fact', 'cm2' or 'lr' for Laplace. If method is\n% 'on', 'fact' is used for EP and 'cm2' for Laplace.\n% See GP_PREDCM and Cseke & Heskes (2011) for more information.\n% splitnormal - determines if the samples are drawn from\n% split-Normal approximation (Geweke, 1989) in the\n% case of non-Gaussian likelihood.\n% Possible values are 'on' (default) and 'off'. \n% n_scale - the maximum number of the most significant principal\n% component directories to scale in the split-Normal\n% approximation (default 50).\n%\n% If likelihood is non-Gaussian and gp.latent_method is Laplace the\n% samples are drawn from split-Normal approximation (see option\n% splitnormal), and if gp.latent_method is EP the samples are drawn\n% from the normal approximation.\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% Geweke, J. (1989). Bayesian inference in econometric models using\n% Monte Carlo integration. Econometrica 57:1317-1339.\n%\n% See also\n% GP_PRED, GP_PAK, GP_UNPAK\n\n% Internal comments\n% - sampling with FIC, PIC and CS+FIC forms full nxn matrix and\n% works only when sampling for the training inputs\n% - The code is not optimized\n%\n% Copyright (c) 2007-2010 Jarno Vanhatalo\n% Copyright (c) 2008 Jouni Hartikainen\n% Copyright (c) 2011 Aki Vehtari\n\n% This software is distributed under the GNU General Public\n% License (version 3 or later); please refer to the file\n% License.txt, included with the software, for details.\n\nip=inputParser;\nip.FunctionName = 'GP_RND';\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('z', [], @(x) isreal(x) && all(isfinite(x(:))))\nip.addParamValue('zt', [], @(x) isreal(x) && all(isfinite(x(:))))\nip.addParamValue('predcf', [], @(x) isempty(x) || ...\n isvector(x) && isreal(x) && all(isfinite(x)&x>0))\nip.addParamValue('tstind', [], @(x) isempty(x) || iscell(x) ||...\n (isvector(x) && isreal(x) && all(isfinite(x)&x>0)))\nip.addParamValue('nsamp', 1, @(x) isreal(x) && isscalar(x))\nip.addParamValue('fcorr', 'off', @(x) ismember(x, {'fact','cm2','off','on','lr'}))\nip.addParamValue('splitnormal', 'on', @(x) (islogical(x) && isscalar(x))|| ...\n ismember(x,{'on' 'off' 'full'}))\nip.addParamValue('n_scale',50, @(x) isnumeric(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;\nz=ip.Results.z;\nzt=ip.Results.zt;\ntn = size(x,1);\npredcf=ip.Results.predcf;\ntstind=ip.Results.tstind;\nnsamp=ip.Results.nsamp;\nfcorr=ip.Results.fcorr;\nsplitnormal = ip.Results.splitnormal;\nn_scale = min(tn, floor(ip.Results.n_scale));\nif 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\nend\n\nif isfield(gp, 'latent_method')\n if iscell(gp)\n gplatmet=gp{1}.latent_method;\n else\n gplatmet=gp.latent_method;\n end\n if ~strcmp(gplatmet, 'Laplace') && strcmp(splitnormal,'on')\n % splitnormal is applicable only with Laplace\n splitnormal='off';\n end\nend\n\n\nsampyt=[];\nif isstruct(gp) && numel(gp.jitterSigma2)==1\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 \n if (isfield(gp.lik.fh,'trcov') && ~isfield(gp,'lik_mono')) ...\n || isfield(gp, 'latentValues')\n % ====================================================\n % Gaussian likelihood or MCMC with latent values\n % ====================================================\n \n if nargout > 1\n [Eft, Covft, ~, Eyt, Covyt] ...\n = gp_jpred(gp,x,y,xt,'z',z,'predcf',predcf,'tstind',tstind);\n else\n [Eft, Covft] = gp_jpred(gp,x,y,xt,'z',z, ...\n 'predcf',predcf,'tstind',tstind);\n end\n rr = randn(size(Eft,1),nsamp);\n sampft = bsxfun(@plus, Eft, chol(Covft,'lower')*rr);\n if nargout > 1\n sampyt = bsxfun(@plus, Eyt, chol(Covyt,'lower')*rr);\n end\n \n else\n % =============================\n % non-Gaussian likelihood\n % =============================\n \n if nargout > 1\n warning('Sampling of yt is not implemented for non-Gaussian likelihoods');\n end\n if strcmp(splitnormal,'on') && isfield(gp,'meanf')\n warning('Split-Normal is not implemented for mean functions');\n splitnormal='off';\n end\n if strcmp(splitnormal,'on') && isfield(gp.lik, 'nondiagW')\n warning('Split-Normal is not implemented for likelihoods with nondiagonal Hessian')\n splitnormal='off';\n end\n if strcmp(splitnormal,'on') && ~isequal(fcorr, 'off')\n warning('Split-Normal is not used when latent marginal posterior corrections are used')\n splitnormal='off';\n end\n \n if strcmp(splitnormal,'on')\n % ------------------\n % Splitnormal on\n % ------------------\n \n switch gp.type\n \n % ---------------------------\n case 'FULL'\n \n [e,~,~, param] = gpla_e(gp_pak(gp), gp, x, y, 'z', z);\n if isnan(e)\n error('Laplace-algorithm returned NaN');\n end\n [Ef, L, W] = deal(param.f, param.L, param.La2);\n\n % Evaluate the covariance\n K = gp_trcov(gp,x);\n K_ss = gp_trcov(gp,xt,predcf);\n K_nf = gp_cov(gp,xt,x,predcf);\n if W >= 0\n % Likelihood is log concave\n if issparse(K) && issparse(L)\n if issparse(W)\n sqrtWK = sqrt(W)*K;\n else\n sqrtWK = sparse(1:tn,1:tn,sqrt(W),tn,tn)*K;\n end\n Covf = K - sqrtWK'*ldlsolve(L,sqrtWK);\n else\n V = linsolve(L,bsxfun(@times,sqrt(W),K),struct('LT',true));\n Covf = K - V'*V;\n end\n else\n % Likelihood is not log concave\n V = bsxfun(@times,L,W');\n Covf = K - K*(diag(W) - V'*V)*K;\n end\n \n % ---------------------------\n case 'FIC'\n \n if ~isempty(tstind) && length(tstind) ~= tn\n error('tstind (if provided) has to be of same length as x.')\n end\n\n % Ensure the direction of tstind\n tstind = tstind(:);\n\n [e,~,~, param] = gpla_e(gp_pak(gp), gp, x, y, 'z', z);\n if isnan(e)\n error('Laplace-algorithm returned NaN');\n end\n Ef = param.f;\n\n u = gp.X_u;\n K_uu = gp_trcov(gp,u,predcf);\n K_uu = (K_uu+K_uu')./2; % ensure the symmetry\n Luu = chol(K_uu, 'lower');\n\n B = Luu\\gp_cov(gp,u,x,predcf);\n B2 = Luu\\gp_cov(gp,u,xt,predcf);\n K = B'*B;\n K_ss = B2'*B2;\n K_nf = B2'*B;\n clear K_uu Luu B B2\n\n % If the prediction is made for training set, evaluate Lav\n % also for prediction points.\n if ~isempty(tstind)\n kss = gp_trvar(gp,xt,predcf);\n % Replace diagonals\n K(1:length(K)+1:numel(K)) = kss(tstind);\n K_ss(1:length(K_ss)+1:numel(K_ss)) = kss;\n % Replace common samples in K_nf\n K_nf(tstind+(0:size(xt,1):(tn-1)*size(xt,1))') = kss(tstind);\n clear kss\n else\n % Add lambda\n % Replace diagonals\n K(1:length(K)+1:numel(K)) = gp_trvar(gp,x,predcf);\n K_ss(1:length(K_ss)+1:numel(K_ss)) = gp_trvar(gp,xt,predcf);\n end\n\n Wsqrt = -gp.lik.fh.llg2(gp.lik, y, Ef, 'latent', z);\n if any(Wsqrt < 0)\n error('FIC not implemented for non-log-concave likelihoods')\n end\n Wsqrt = sqrt(Wsqrt);\n L = chol(eye(size(K)) + bsxfun(@times,bsxfun(@times,Wsqrt,K),Wsqrt'), 'lower');\n\n % Evaluate the covariance for the posterior of f\n V = linsolve(L,bsxfun(@times,Wsqrt,K),struct('LT',true));\n Covf = K - V'*V;\n \n % ---------------------------\n case {'PIC' 'PIC_BLOCK'}\n \n u = gp.X_u;\n K_fu = gp_cov(gp,x,u,predcf); % f x u\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 ind = gp.tr_index;\n Luu = chol(K_uu)';\n B=Luu\\(K_fu');\n B2 = Luu\\(gp_cov(gp,u,xt,predcf));\n clear Luu\n\n [e,~,~, p] = gpla_e(gp_pak(gp), gp, x, y, 'z', z);\n if isnan(e)\n error('Laplace-algorithm returned NaN');\n end\n [Ef, La2] = deal(p.f, p.La2);\n\n % Evaluate the variance\n sqrtW = -gp.lik.fh.llg2(gp.lik, y, Ef, 'latent', z);\n if any(sqrtW < 0)\n error('PIC not implemented for non-log-concave likelihoods')\n end\n sqrtW = sqrt(sqrtW);\n % Components for (I + W^(1/2)*(Qff + La2)*W^(1/2))^(-1) = Lahat^(-1) - L2*L2'\n Lahat = cell(length(ind),1);\n for i=1:length(ind)\n Lahat{i} = eye(length(ind{i})) + bsxfun(@times,bsxfun(@times,sqrtW(ind{i}),La2{i}),sqrtW(ind{i})');\n end\n sKfu = bsxfun(@times, sqrtW, K_fu);\n iLasKfu = zeros(size(K_fu));\n for i=1:length(ind)\n iLasKfu(ind{i},:) = Lahat{i}\\sKfu(ind{i},:);\n end\n A2 = K_uu + sKfu'*iLasKfu; A2=(A2+A2')./2;\n L2 = iLasKfu/chol(A2);\n\n % NOTE!\n % This is done with full matrices at the moment.\n % Needs to be rewritten.\n K_ss = B2'*B2;\n K_nf = B2'*B;\n K = B'*B;\n C = -L2*L2';\n for i=1:length(ind)\n % Originally \n % >> La = gp_trcov(gp, xt(tstind{i},:), predcf) - B2(:,tstind{i})'*B2(:,tstind{i});\n % >> K_ss(ind{i},ind{i}) = K_ss(ind{i},ind{i}) + La;\n % changed into (works if xt is not the same as x)\n % >> La = gp_trcov(gp, xt(tstind{i},:), predcf) - B2(:,tstind{i})'*B2(:,tstind{i});\n % >> K_ss(tstind{i},tstind{i}) = K_ss(tstind{i},tstind{i}) + La;\n % which is implemented in the line bellow\n K_ss(tstind{i},tstind{i}) = gp_trcov(gp, xt(tstind{i},:), predcf);\n K_nf(tstind{i},ind{i}) = gp_cov(gp, xt(tstind{i},:), x(ind{i},:),predcf);\n K(ind{i},ind{i}) = K(ind{i},ind{i}) + La2{i};\n C(ind{i},ind{i}) = C(ind{i},ind{i}) + inv(Lahat{i});\n end\n\n Covf = K - K * bsxfun(@times,bsxfun(@times,sqrtW,C),sqrtW') * K;\n \n % ---------------------------\n case 'CS+FIC'\n \n if ~isempty(tstind) && length(tstind) ~= tn\n error('tstind (if provided) has to be of same length as x.')\n end\n\n % Ensure the direction of tstind\n tstind = tstind(:);\n\n % Indexes to all non-compact support and compact support covariances.\n cscf = cellfun(@(x) isfield(x,'cs'), gp.cf);\n predcf1 = find(~cscf);\n predcf2 = find(cscf);\n if ~isempty(predcf)\n predcf1 = intersect(predcf1,predcf);\n predcf2 = intersect(predcf2,predcf);\n end\n\n % Laplace approximation\n [e,~,~, param] = gpla_e(gp_pak(gp), gp, x, y, 'z', z);\n if isnan(e)\n error('Laplace-algorithm returned NaN');\n end\n Ef = param.f;\n\n u = gp.X_u;\n\n K_uu = gp_trcov(gp,u,predcf1);\n K_uu = (K_uu+K_uu')./2;\n Luu = chol(K_uu)';\n\n B=Luu\\(gp_cov(gp,u,x,predcf1));\n B2=Luu\\(gp_cov(gp,u,xt,predcf1));\n K = B'*B;\n K_ss = B2'*B2;\n K_nf = B2'*B;\n clear K_uu Luu B B2\n\n if ~isempty(tstind)\n % Add Lambda\n kss = gp_trvar(gp,xt,predcf1);\n % Replace diagonals\n K(1:length(K)+1:numel(K)) = kss(tstind);\n K_ss(1:length(K_ss)+1:numel(K_ss)) = kss;\n % Replace common samples in K_nf\n K_nf(tstind+(0:size(xt,1):(tn-1)*size(xt,1))') = kss(tstind);\n\n % Add CS covariance\n kss = gp_trcov(gp, xt, predcf2);\n K = K + kss(tstind,tstind);\n K_ss = K_ss + kss;\n clear kss\n\n else\n % Add lambda\n % Replace diagonals\n K(1:length(K)+1:numel(K)) = gp_trvar(gp,x,predcf1);\n K_ss(1:length(K_ss)+1:numel(K_ss)) = gp_trvar(gp,xt,predcf1);\n\n % Add CS covariance\n K = K + gp_trcov(gp, x, predcf2);\n K_ss = K_ss + gp_trcov(gp, xt, predcf2);\n\n end\n\n % Add CS covariance for K_nf\n K_nf = K_nf + gp_cov(gp, xt, x, predcf2);\n\n sqrtW = -gp.lik.fh.llg2(gp.lik, y, Ef, 'latent', z);\n if any(sqrtW < 0)\n error('CS+FIC not implemented for non-log-concave likelihoods')\n end\n sqrtW = sqrt(sqrtW);\n L = chol(eye(size(K)) + bsxfun(@times,bsxfun(@times,sqrtW,K),sqrtW'), 'lower');\n V = linsolve(L,bsxfun(@times,sqrtW,K),struct('LT',true));\n Covf = K - V'*V;\n \n otherwise\n error('Split-Normal not implemented for %s', gp.type)\n \n end\n \n % Scaling n_scale principal component directions\n % Split-normal approximation: Geweke (1989)\n\n % N.B. svd of sparse matrix is not generally sparse (unless Covf is\n % block diagonal or can be made such by reordering the dimensions).\n % Scaling using the Cholesky factorisation could possibly be done\n % sparsely but the directions would be different (not split-Normal).\n % Thus full matrices has to be used.\n [V, D, ~] = svd(full(Covf));\n T = real(V) * sqrt(real(D)); % Ensuring the real\n\n L = chol(K,'lower');\n\n % Optimise the skewness\n delta = [-6:0.5:-0.5, 0.5:0.5:6];\n D = bsxfun(@plus, kron(delta,T(:,1:n_scale)), Ef);\n ll = zeros(1,n_scale*length(delta)); % Here looping is faster than cellfun\n for i = 1:n_scale*length(delta)\n ll(i) = 2*gp.lik.fh.ll(gp.lik,y,D(:,i),z);\n end\n ll = ll - sum(D.*(L'\\(L\\D)));\n ll0 = 2*gp.lik.fh.ll(gp.lik, y, Ef, z) - Ef'*(L'\\(L\\Ef));\n ll(ll >= ll0) = NaN;\n f = bsxfun(@rdivide, abs(delta), reshape(sqrt(ll0-ll),n_scale,length(delta)));\n clear D V ll ll0\n q = max(f(:,delta>0),[],2);\n r = max(f(:,delta<0),[],2);\n q(isnan(q)) = 1;\n r(isnan(r)) = 1;\n % Safety limits [1/10, 10]\n q = min(max(q,0.1),10);\n r = min(max(r,0.1),10);\n if n_scale < tn\n q = [q;ones(tn-n_scale,1)];\n r = [r;ones(tn-n_scale,1)];\n end\n \n % Draw samples from split-Normal approximated posterior of f and\n % sample from the conditional distribution of ft for each sample of f\n u = rand(tn,nsamp);\n c = r./(r+q);\n Covft = K_ss - K_nf*(L'\\(L\\K_nf'));\n Covft_ind = find(diag(Covft)>gp.jitterSigma2);\n if length(Covft_ind) == size(xt,1)\n % The following evaluates samples of ft directly by\n % Eft + chol(Covft)*randn,\n % where Eft = K_nf*K\\f and Covft = K_ss - K_nf*K\\K_nf'\n sampft = K_nf*(L'\\(L\\ ...\n bsxfun(@plus,Ef,T*((bsxfun(@times,q,double(bsxfun(@ge,u,c))) ...\n +bsxfun(@times,-r,double(bsxfun(@lt,u,c)))).*abs(randn(tn,nsamp)))) ...\n )) + chol(Covft,'lower')*randn(size(xt,1),nsamp);\n else\n % Zero variance dimensions in p(ft|X,xt,f)\n % Evaluate first Eft for each f\n sampft = K_nf*(L'\\(L\\ ...\n bsxfun(@plus,Ef,T*((bsxfun(@times,q,double(bsxfun(@ge,u,c))) ...\n +bsxfun(@times,-r,double(bsxfun(@lt,u,c)))).*abs(randn(tn,nsamp)))) ));\n % Add variability only from non-zero variance dimensions\n sampft(Covft_ind,:) = sampft(Covft_ind,:) ...\n + chol(Covft(Covft_ind,Covft_ind),'lower')*randn(length(Covft_ind),nsamp);\n end\n \n else\n % -------------------\n % split-Normal off\n % -------------------\n [Eft, Covft] = gp_jpred(gp,x,y,xt,'z',z, ...\n 'predcf',predcf, 'tstind',tstind, 'fcorr','off');\n sampft = bsxfun(@plus, Eft, chol(Covft,'lower')*randn(size(xt,1),nsamp));\n \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 cdf\n cumsumpc = cumsum(pc_pred)/sum(pc_pred);\n % Remove non-unique values from grid vector & distribution\n [cumsumpc, inds] = unique(cumsumpc);\n fvec = fvec(inds);\n % use inverse cdf to make marginal transformation\n fsnc = normcdf(sampft(i,:), Eft(i,1), sqrt(diag(Covft(i,i))));\n sampft(i,:) = interp1(cumsumpc,fvec,fsnc);\n end\n end\n end\n \n \n \n end\n\nelseif isstruct(gp) && numel(gp.jitterSigma2)>1\n % MCMC\n nmc=size(gp.jitterSigma2,1);\n % resample nsamp cases from nmc samples\n % deterministic resampling has low variance and small bias for\n % equal weights\n gi=resampdet(ones(nmc,1),nsamp,1);\n sampft = zeros(size(xt,1),nsamp);\n if nargout>=2\n sampyt = zeros(size(xt,1),nsamp);\n end\n for i1=1:nmc\n sampind = find(gi==i1);\n nsampi = length(sampind);\n if nsampi>0\n Gp = take_nth(gp,i1);\n if isfield(Gp,'latent_method') && isequal(Gp.latent_method,'MCMC')\n Gp = rmfield(Gp,'latent_method');\n end\n if isfield(gp, 'latentValues') && ~isempty(gp.latentValues)\n % Non-Gaussian likelihood. The latent variables should be used in\n % place of observations\n for ni=1:nsampi\n if ni==1\n % use stored latent values\n f = gp.latentValues(i1,:);\n else\n % need to resample latent values\n opt=scaled_mh();\n f=scaled_mh(f, opt, Gp, x, y, z);\n end\n if nargout<2\n sampft(:,sampind(ni)) = gp_rnd(Gp, x, f', xt, 'nsamp', 1, ...\n 'z', z, 'zt', zt, 'predcf', predcf, ...\n 'tstind', tstind);\n else\n [tsampft, tsampyt] = gp_rnd(Gp, x, f', xt, 'nsamp', ...\n 1, 'z', z, 'zt', zt, ...\n 'predcf', predcf, 'tstind', tstind);\n \n sampft(:,sampind(ni)) = tsampft;\n sampyt(:,sampind(ni)) = tsampyt;\n end\n\n \n end\n else \n % Gaussian likelihood\n if nargout<2\n sampft(:,sampind) = gp_rnd(Gp, x, y, xt, 'nsamp', nsampi, ...\n 'z', z, 'zt', zt, 'predcf', predcf, ...\n 'tstind', tstind);\n else\n [tsampft, tsampyt] = gp_rnd(Gp, x, y, xt, 'nsamp', ...\n nsampi, 'z', z, 'zt', zt, ...\n 'predcf', predcf, 'tstind', tstind);\n sampft(:,sampind) = tsampft;\n sampyt(:,sampind) = tsampyt;\n end\n end\n end\n end\nelseif iscell(gp)\n % gp_ia\n ngp=length(gp);\n if isfield(gp{1},'ia_weight')\n gw = zeros(ngp,1);\n for i1=1:ngp\n gw(i1)=gp{i1}.ia_weight;\n end\n else\n gw=ones(ngp,1);\n end\n % resample nsamp cases from nmc samples\n % stratified resampling has has higher variance than deterministic\n % resampling, but has a smaller bias, and thus it should be more\n % suitable for unequal weights\n gi=resampstr(gw,nsamp,1);\n sampft = zeros(size(xt,1),nsamp);\n if nargout>=2\n sampyt = zeros(size(xt,1),nsamp);\n end\n for i1 = 1:ngp\n nsampi=sum(gi==i1);\n if nsampi>0\n if nargout<2\n sampft(:,gi==i1) = gp_rnd(gp{i1}, x, y, xt, 'nsamp', nsampi, ...\n 'z', z, 'zt', zt, 'predcf', predcf, ...\n 'tstind', tstind, 'fcorr', fcorr);\n else\n [tsampft, tsampyt] = gp_rnd(gp{i1}, x, y, xt, 'nsamp', nsampi, ...\n 'z', z, 'zt', zt, 'predcf', predcf, ...\n 'tstind', tstind, 'fcorr', fcorr);\n sampft(:,gi==i1) = tsampft;\n sampyt(:,gi==i1) = tsampyt;\n end\n end\n end\nend\n", "meta": {"author": "gpstuff-dev", "repo": "gpstuff", "sha": "114937ec0a201306489a66cbba38283e722fb998", "save_path": "github-repos/MATLAB/gpstuff-dev-gpstuff", "path": "github-repos/MATLAB/gpstuff-dev-gpstuff/gpstuff-114937ec0a201306489a66cbba38283e722fb998/gp/gp_rnd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.3486451217982255, "lm_q1q2_score": 0.19867634705933052}} {"text": "% EASY6 computes a baseline vector. With given code and carrier\n% phase observations we estimate the ambiguities using integer\n%\t least-squares (ILS) or Goad algorithms and estimate the baseline\n% components by a Kalman filter. The code does not handle\n%\t outliers.\n\n\n% RINEX version3.03\n\n%Kai Borre 27-07-2002\n%Copyright (c) by Kai Borre\n%$Revision: 1.1 $ $Date: 2005/01/20 $\n%Total revision 2.0, February 15, 2016\n\n% The following code is general, but with the following limitations\n\n% 1. We assume the observational columns are identical and ordered in the\n% same sequence in master and rover files. The present observations just\n% by chance contain identical satellites which are ordered in the same\n% sequence. So sats1 and sats2 are the same. Alternatively, we need to\n% establish a matching between sats1 and sats2 and likewise for Obs1\n% and Obs2\n\n% 2. There are no satellites with elevation angle less than 10 degrees.\n% Minimum is 12 degrees. There are no rising or setting satellites during\n% the observation period\n\n% 3. The satellite having highest elevation angle at the start becomes the\n% second highest about the middle of the observation file.\n\n% 4. We do not apply tropospheric correction as it is very small in case\n% master and rover stations only are about 1 meter apart\n\n% 5. the actual baseline lenght was measured as 0.645 meter.\n\n% Initial setting and computation of constants\nv_light = 299792458;\t % vacuum speed of light m/s\nf1 = 154*10.23E6;\t\t % L1 frequency Hz\nf2 = 120*10.23E6;\t\t\t % L2 frequency Hz\nlambda1 = v_light/f1;\t % wavelength on L1: .19029367 m\nlambda2 = v_light/f2;\t % wavelength on L2: .244210213 m\n\n% Read RINEX ephemerides file and convert to internal Matlab format\nrinexe('log_24h.15n','eph.dat');\nEph = get_eph('eph.dat');\n\n% Selection of observation type\n% ss = 'C1W L1W C2W L2W' %; % pseudorange and carrier phase\nss = 'C1C L1C C2X L2X'; % just to test other obsrervation types\nfprintf('\\n %s', ss)\n\n% Open the master observation file\nofile1 = 'log_24h.15o';\nfid1 = fopen(ofile1,'rt');\n\n% Open the rover observation file\nofile2 = 'log_r.15o';\nfid2 = fopen(ofile2,'rt');\n\ncoo = [];\nant_delta = [];\nlinjer = 0;\nij = [];\nOBS1 = [];\nOBS2 = [];\nx = zeros(3,1);\n\n% Gobbling the master file header, and collecting useful information\nwhile 1\n linjer = linjer +1;\n line = fgetl(fid1);\n answer = strfind(line,'END OF HEADER');\n if ~isempty(answer), break; end;\n if (line == -1), eof = 1; break; end;\n \n answer = strfind(line,'REC #');\n if ~isempty(answer)\n var = textscan(fid1,'%s %d14','Delimiter','\\n');\n var1 = var{1}{1};\n cox = str2double(var1(1:14));\n coy = str2double(var1(15:28));\n coz = str2double(var1(29:42));\n end\n \n answer = strfind(line,'ANT #');\n if ~isempty(answer)\n var = textscan(fid1,'%s %d14','Delimiter','\\n');\n var1 = var{1}{1};\n ax = str2double(var1(1:14));\n ay = str2double(var1(15:28));\n az = str2double(var1(29:42));\n end\n \n answer = strfind(line,'SYS / # / OBS TYPES');\n if ~isempty(answer)\n tline1 = strsplit(line);\n line = fgetl(fid1);\n tline2 = strsplit(line);\n tt1 = horzcat(tline1,tline2);\n for qq = 1:4\n if qq == 1, i = strcmp(tt1,ss(1:3)); end\n if qq == 2, i = strcmp(tt1,ss(5:7)) ; end\n if qq == 3, i = strcmp(tt1,ss(9:11)); end\n if qq == 4, i = strcmp(tt1,ss(13:15)); end\n ii = find(i == 1) ;\n ii = ii-2;\n if ii > 15, ii = ii-7; end;\n ij = [ij ii];\n end\n % the cell array of strings tline1 includes two strings in the start\n % which describe the system and number of observation types.\n % Both tline1 and tline2 termintes with six additional strings.\n % An extra string appears at the start of tline2; it originates\n % from concatenation of the two lines. The indexing does not\n % change even if you empty the cells. They remain as empty\n % cells and keep a place\n obs_col = ij;\n end;\n answer = strfind(line,'INTERVAL');\n if ~isempty(answer)\n interval = strtok(line);\n int = str2double(interval);\n end;\n answer = strfind(line,'# OF SATELLITES');\n if ~isempty(answer)\n NumberSV = strtok(line);\n numSV = str2double(NumberSV) ;\n end\nend % end reading master header\n\n% the string arrays for the tline1 and tline2 contain an integer after the\n% carrier phase observation. We must account for this by the following\n% correctional table.\n\n% the following code may be done more elegantly\nfor qq = 1:4\n if qq == 1, a0 = 6; b0 = 7; end\n if qq == 2, a0 = 6; b0 = 7; end\n if qq == 3, a0 = 14; b0 =15; end\n if qq == 4, a0 =14; b0 =15; end\n if strcmp(ss(a0:b0), '1C'), obs_col(1,qq) = obs_col(1,qq)+1;\n elseif strcmp(ss(a0:b0), '1W'), obs_col(1,qq) = obs_col(1,qq)+2;\n elseif strcmp(ss(a0:b0), '2X'), obs_col(1,qq) = obs_col(1,qq) +3;\n elseif strcmp(ss(a0:b0), '2W'), obs_col(1,qq) = obs_col(1,qq) +4;\n else strcmp(ss(a0:b0), '5X'), obs_col(1,qq) = obs_col(1,qq) +5;\n end;\nend;\n\nPos = [];\nOmc = [];\nbase = [];\nx_acc = [];\ninnov = [];\n\n[time,post] = textscan(fid1,'%s %d8','Delimiter','\\n');\ntid = time{1}{1};\nyear = str2double(tid(3:6));\nmonth = str2double(tid(8:9));\nday = str2double(tid(11:12));\nhour = str2double(tid(14:15));\nminute = str2double(tid(17:18));\nsecond = str2double(tid(20:29));\n% static = str2double(tid(31:32));\nNoSvs1 = str2double(tid(34:36));\ndt1 = str2double(tid(38:56));\nh = hour+minute/60+second/3600;\njd = julday(year, month, day, h);\n[~, sec_of_week] = gps_time(jd);\ntime1 = sec_of_week; % sow1\n\nObs1 = zeros(NoSvs1,length(obs_col));\nfor i = 1:NoSvs1\n [obs1,~] = textscan(fid1,'%s %d8','Delimiter','\\n');\n obs1x = obs1{1}{1} ;\n obs1y = strsplit(obs1x);\n sat1 = obs1y{1} ;\n sats1(i) = str2double(sat1(2:3));\n Obs1(i,:) = str2double(obs1y(obs_col));\nend\n\n% Gobbling the rover file header, and collecting useful information\n% the whole story repated for the rover with index 2\n% we start by gobbeling the header\nfor qq = 1:linjer +3 % 1 plus 2 from applying textscan twice\n aa = fgetl(fid2);\nend\n\n% Reading header of observation record in rover file\n[time,pos] = textscan(fid2,'%s %d8','Delimiter','\\n');\ntid = time{1}{1};\nyear = str2double(tid(3:6));\nmonth = str2double(tid(8:9));\nday = str2double(tid(11:12));\nhour = str2double(tid(14:15));\nminute = str2double(tid(17:18));\nsecond = str2double(tid(20:29));\nstatic = str2double(tid(31:32));\nNoSvs2 = str2double(tid(34:36));\ndt2 = str2double(tid(38:56));\nh = hour+minute/60+second/3600;\njd = julday(year, month, day, h);\n[~, sec_of_week] = gps_time(jd);\ntime2 = sec_of_week; % sow2\n\nObs2 = zeros(NoSvs2,length(obs_col));\nfor i = 1:NoSvs2\n [obs2,pos] = textscan(fid2,'%s %d8','Delimiter','\\n');\n obs2y = obs2{1}{1};\n obs2 = strsplit(obs2y);\n sat2 = obs2{1};\n sats2(i,:) = str2double(sat2(2:3));\n Obs2(i,:) = str2double(obs2(obs_col));\nend\n\n% Establish synchronous reading of fid1 and fid2\n% The epoch interval is int seconds\nif time1 > time2\n for j = 1:round(time1-time2)\n [time,pos] = textscan(fid2,'%s %d8','Delimiter','\\n');\n tid = time{1}{1};\n year = str2double(tid(3:6));\n month = str2double(tid(8:9));\n day = str2double(tid(11:12));\n hour = str2double(tid(14:15));\n minute = str2double(tid(17:18));\n second = str2double(tid(20:29));\n static = str2double(tid(31:32));\n NoSvs2 = str2double(tid(34:36));\n dt2 = str2double(tid(38:56));\n h = hour+minute/60+second/3600;\n jd = julday(year, month, day, h);\n [~, sec_of_week] = gps_time(jd);\n time2 = sec_of_week; % sow2\n \n Obs2 = zeros(NoSvs2,length(obs_col));\n for i = 1:NoSvs2\n [obs2,pos] = textscan(fid2,'%s %d8','Delimiter','\\n');\n obs2y = obs2{1}{1};\n obs2 = strsplit(obs2y);\n sat2 = obs2{1};\n sats2(i,:) = str2double(sat2(2:3));\n Obs2(i,:) = str2double(obs2(obs_col));\n end\n end\nend\n\nif time1 < time2\n for j = 1:round(time2-time1)\n [time,pos] = textscan(fid1,'%s %d8','Delimiter','\\n');\n tid = time{1}{1};\n year = str2double(tid(3:6));\n month = str2double(tid(8:9));\n day = str2double(tid(11:12));\n hour = str2double(tid(14:15));\n minute = str2double(tid(17:18));\n second = str2double(tid(20:29));\n static = str2double(tid(31:32));\n NoSvs1 = str2double(tid(34:36));\n dt1 = str2double(tid(38:56));\n h = hour+minute/60+second/3600;\n jd = julday(year, month, day, h);\n [~, sec_of_week] = gps_time(jd);\n time1 = sec_of_week; % sow1\n Obs1 = zeros(NoSvs1,length(obs_col));\n for i = 1:NoSvs1\n [obs1,pos] = textscan(fid1,'%s %d8','Delimiter','\\n');\n obs1x = obs1{1}{1};\n obs1y = strsplit(obs1x);\n sat1 = obs1y{1};\n sats1(i) = str2double(sat1(2:3));\n Obs1(i,:) = str2double(obs1y(obs_col));\n end\n end\nend % synchronization\n\nfprintf('\\nFirst Common Epoch Time1 : %8.0f', time1)\nfprintf('\\nFirst Common Epoch Time2 : %8.0f\\n', time2)\n\nb_acc = [];\ninnov_acc = [];\nbk_acc = [];\nepoch = 0;\n\ndisp(' ')\ndisp(' ... Now wait a few minutes for further results and a plot!')\n\nwhile 1\n epoch = epoch +1;\n % Reading header of observation block at Master\n [time,post] = textscan(fid1,'%s %d8','Delimiter','\\n');\n tid = time{1}{1};\n year = str2double(tid(3:6));\n month = str2double(tid(8:9));\n day = str2double(tid(11:12));\n hour = str2double(tid(14:15));\n minute = str2double(tid(17:18));\n second = str2double(tid(20:29));\n % static = str2double(tid(31:32));\n NoSvs1 = str2double(tid(34:36));\n dt1 = str2double(tid(38:56));\n h = hour+minute/60+second/3600;\n jd = julday(year, month, day, h);\n [~, sec_of_week] = gps_time(jd);\n time1 = sec_of_week; % sow1\n \n % Reading observation block at Master\n Obs1 = zeros(NoSvs1,length(obs_col));\n for i = 1:NoSvs1\n obs1 = textscan(fid1,'%s %d8','Delimiter','\\n');\n obs1x = obs1{1}{1} ;\n obs1y = strsplit(obs1x);\n sat1 = obs1y{1} ;\n sats1(i) = str2double(sat1(2:3));\n Obs1(i,:) = str2double(obs1y(obs_col));\n end\n \n % Reading header of observation record in rover file\n [time,pos] = textscan(fid2,'%s %d8','Delimiter','\\n');\n tid = time{1}{1};\n year = str2double(tid(3:6));\n month = str2double(tid(8:9));\n day = str2double(tid(11:12));\n hour = str2double(tid(14:15));\n minute = str2double(tid(17:18));\n second = str2double(tid(20:29));\n static = str2double(tid(31:32));\n NoSvs2 = str2double(tid(34:36));\n dt2 = str2double(tid(38:56));\n h = hour+minute/60+second/3600;\n jd = julday(year, month, day, h);\n [~, sec_of_week] = gps_time(jd);\n time2 = sec_of_week; % sow2\n \n Obs2 = zeros(NoSvs2,length(obs_col));\n for i = 1:NoSvs2\n [obs2,pos] = textscan(fid2,'%s %d8','Delimiter','\\n');\n obs2y = obs2{1}{1};\n obs2 = strsplit(obs2y);\n sat2 = obs2{1};\n sats2(i,:) = str2double(sat2(2:3));\n Obs2(i,:) = str2double(obs2(obs_col));\n end\n \n % Next we test if all observed SVs have an ephemeris.\n % sats1 contains the SVs as read in the observation lines\n % The intersect command delivers Sats in sorted order!\n % Therefore we must be careful in the follwing manipulations\n Sats = intersect(sats1,Eph(1,:));\n \n % The command ismember does not change the sequence of entries in sats1\n lia = ismember(sats1,Sats);\n % A 0 (zero) in lia indicates that a SV has been deleted. We delete the\n % corresponding row in the observations\n sats1(lia==0) = [];\n Obs1(lia==0,:) = []; % modfied because of two columns\n NoSV1 = length(sats1);\n \n % Next we test if all observed sats have an ephemeris.\n % sats contains the SVs as read in the observation lines.\n % The intersect command delivers Sats in sorted order!\n % Therefore we must be careful in the following manipulations\n Sats = intersect(sats2,Eph(1,:));\n \n % The command ismember does not change the sequence of entries in sats\n lia = ismember(sats2,Sats);\n % A 0 (zero) in lia indicates that a SV has been deleted. We delete the\n % corresponding row in the observations\n sats2(lia==0) = [];\n Obs2(lia==0, :) = [];\n NoSV2 = length(sats2);\n % end reading first record in rover file\n \n % By chance sats1 and sats 2 are the same in the sample data. Otherwise\n % we need to establish a matching between sats1 and sats2 and\n % likewise for Obs1 and Obs2\n \n % We compute elevation angles for all sats1 and sats2\n [X_i, el] = recpo_ls(Obs1(:,3), sats1, time1, Eph);\n [X_j0,~] = recpo_ls(Obs2(:,3), sats2, time1, Eph);\n if epoch == 1\n X_j = X_j0(1:3,1);\n end\n % if epoch == 1\n % forcing the choice of reference satellite to be the second highest\n % at the start\n % sats1\n % refSV = 5\n % sats1(refSV) = [];\n % end\n \n if epoch == 1\n % The SV with largest elevation is taken as reference SV\n [y,refSV] = max(el) ;\n old_refSV = refSV;\n fprintf('\\n Reference satellite is chosen as PRN %3.0f\\n', sats1(refSV))\n if refSV ~= old_refSV\n fprintf('\\n New reference satellite is chosen as PRN %3.0f\\n\\n', sats1(refSV))\n sats1 = union(sats1, old_refSV);\n % no PRN 12 must be inserted at the entry from where it was deleted!!!\n end\n end\n %The refSV is PRN 12 has index 6 in sats1\n % Finding columns in Eph for each SV\n m = NoSV1;\n col_Eph = zeros(1,m);\n for t = 1:m\n col_Eph(t) = find_eph(Eph,sats1(t),time1+dt1);\n end\n \n m1 = m-1; % m1 is all sv.s minus refSV\n X_a = [];\n X = zeros(3+2*m1,1);\n \n % creating a row of indices for all Svs minus the refSV\n t = 1: NoSV1;\n t1 = setdiff(t,refSV);\n % Computation of covariance matrix Sigma for double differenced observations\n D = [ones(m1,1) -eye(m1) -ones(m1,1) eye(m1)];\n Sigma = D*D';\n \n % A block for estimation of AMBIGUITIES\n % we accumulate the normals for the first 10 epochs\n switch(epoch)\n \n case {1, 2, 3, 4, 5, 6, 7, 8, 9,10}\n \n N = zeros(3+2*m1,3+2*m1);\t % initialization of normals\n rs = zeros(3+2*m1,1);\t % initialization of right side\n \n % Computing rho for refSV\n [~,rhok_j,~] = get_rho(time1, Obs2(refSV,1), Eph(:,col_Eph(refSV)), X_j);\n [~,rhok_i,Xk_ECF] = get_rho(time1, Obs1(refSV,1), Eph(:,col_Eph(refSV)), X_i);\n \n tt = 0;\n ts = length(t1);\n b = zeros(ts,1);\n bk = zeros(ts,1);\n A1 = [];\n for t = t1\n tt = tt+1;\n [~,rhol_j, ~] = get_rho(time1,Obs2(t,1), Eph(:,col_Eph(t)), X_j);\n [~,rhol_i, Xl_ECF] = get_rho(time1,Obs1(t,1), Eph(:,col_Eph(t)), X_i);\n A0 = [(Xk_ECF(1)-X_j(1))/rhok_j - (Xl_ECF(1)-X_j(1))/rhol_j ...\n (Xk_ECF(2)-X_j(2))/rhok_j - (Xl_ECF(2)-X_j(2))/rhol_j ...\n (Xk_ECF(3)-X_j(3))/rhok_j - (Xl_ECF(3)-X_j(3))/rhol_j];\n A1 = [A1; A0];\n Phi1 = (Obs1(refSV,2)-Obs1(t,2)-Obs2(refSV,2)+Obs2(t,2))*lambda1;\n Phi2 = (Obs1(refSV,4)-Obs1(t,4)-Obs2(refSV,4)+Obs2(t,4))*lambda2;\n b(tt,:) = Phi1-lambda1*X(3+tt,1);\n b(length(t1)+tt,:) = Phi2-lambda2*X(3+length(t1)+tt,1);\n bk(tt,:) = rhok_i-rhok_j-rhol_i+rhol_j;\n bk(length(t1)+tt,:) = rhok_i-rhok_j-rhol_i+rhol_j;\n end;\n A_modi = eye(m1);\t \t % modified coefficient matrix\n A_modi(:,refSV) = -ones(m1,1);\n A_aug = [A1 lambda1*A_modi 0*eye(m1); A1 0*eye(m1) lambda2*A_modi];\n N = N+A_aug'*kron(eye(2),Sigma)*A_aug;\n rs = rs+A_aug'*kron(eye(2),Sigma)*(b-bk);\n \n \n case 11\n \n PP = pinv(N);\n % X contains the three baseline components and next the float ambiguities\n X = PP*rs;\n % The next step is to convert the real ambiguities in X (all entries below the\n % fourth component and to the end) into integers. We indicate two algorithms:\n \n % the Integer Least-Squares (ILS) algorithm\n PP = 0.5*(PP+PP'); %to make PP symmetric\n %[a, sqnorm] = ILS( X(4:4+2*m1-1,1), PP(4:4+2*m1-1,4:4+2*m1-1),2);\n % Correcting to baseline vector as consequence of changing float ambiguities\n % to fixed ones\n % X(1:3,1) = X(1:3,1)-PP(1:3,4:4+2*m1-1)*inv(PP(4:4+2*m1-1,4:4+2*m1-1))*...\n % (X(4:4+2*m1-1,1)-a(:,1)); %select SECOND first set of candidates\n % X(4:4+2*m1-1,1) = a(:,1);\n %a = a(:,2); % forces the second set of N values in use\n \n % the Goad algorithm\n for j = 1:tt\n K1 = round(X(3+tt)-X(3+m1+tt));\n K2 = round(60*X(3+tt)-77*X(3+m1+tt));\n trueN2 = round((60*K1-K2)/17); % (15.10)\n trueN1 = round(trueN2+K1); % (15.11)\n amb(j,1:2) = [trueN1 trueN2];\n end\n a = [amb(:,1); amb(:,2) ];\n \n fprintf('\\n N1 for PRN %3.0f: %3.0f',[sats1(t1); a(1:m1,1)'])\n fprintf('\\n')\n fprintf('\\n N2 for PRN %3.0f: %3.0f',[sats1(t1); a(m1+1:2*m1,1)'])\n fprintf('\\n')\n \n % Setting covariances for the Kalman filter; the state vector contains (x,y,z)\n P = 10^8*eye(3);\t \t\t % covariances of state vector\n Q = 0.1*eye(3);\t\t\t % covariances of system\n R = 0.1*kron(eye(2),inv(Sigma));\t % covariances of observations\n [phi_j,lambda_j,h_j] = togeod(63781137, 298.257223563, X_j(1), X_j(2), X_j(3));\n h_i = h_j;\n \n otherwise\n \n % estimate of baseline components\n tt = 0; % a counter\n A = zeros(m1,3); %zeros(2*m1,3);\n % Computing rho for refsv\n [torr2,rhok_j,~] = get_rho(time2, Obs2(refSV,3), Eph(:,col_Eph(refSV)), X_j);\n [torr1,rhok_i,Xk_ECF] = get_rho(time1, Obs1(refSV,3), Eph(:,col_Eph(refSV)), X_i);\n for t = t1\n tt = tt+1;\n [torr4,rhol_j, ~] = get_rho(time2,Obs2(t,3), Eph(:,col_Eph(t)), X_j);\n [torr3,rhol_i,Xl_ECF] = get_rho(time1,Obs1(t,3), Eph(:,col_Eph(t)), X_i);\n A0 = [(Xk_ECF(1)-X_j(1))/rhok_j - (Xl_ECF(1)-X_j(1))/rhol_j ...\n (Xk_ECF(2)-X_j(2))/rhok_j - (Xl_ECF(2)-X_j(2))/rhol_j ...\n (Xk_ECF(3)-X_j(3))/rhok_j - (Xl_ECF(3)-X_j(3))/rhol_j];\n A(tt,:) = A0;\n A(m1+tt,:) = A0;\n %time_corr = (torr1-torr2-torr3-torr4);\n % Composing the right side\n \n % Tropospheric correction using standard meteorological parameters\n %[ ~,el_ki, ~] = topocent(X_i(1:3),Xk_ECF-X_i(1:3));\n %[ ~,el_li,~] = topocent(X_i(1:3),Xl_ECF-X_i(1:3));\n %[ ~,el_kj, ~] = topocent(X_j(1:3),Xk_ECF-X_j(1:3));\n %[az,el_lj,d] = topocent(X_j(1:3),Xl_ECF-X_j(1:3));\n %%el_ki, el_li, el_kj, el_lj\n %t_corr = tropo(sin(el_lj*pi/180),...\n % h_j*1.e-3,1013,293,50,0,0,0)...\n % -tropo(sin(el_li*pi/180),....\n % h_i*1.e-3,1013,293,50,0,0,0)...\n % -tropo(sin(el_kj*pi/180),...\n % h_j*1.e-3,1013,293,50,0,0,0)...\n % +tropo(sin(el_ki*pi/180),...\n % h_i*1.e-3,1013,293,50,0,0,0);\n t_corr = 0;\n b(tt,:) = (Obs1(refSV,2)-Obs1(t,2)-Obs2(refSV,2)+Obs2(t,2) ...\n -a(tt,1))*lambda1-t_corr;\n b(m1+tt,:) = (Obs1(refSV,4)-Obs1(t,4)-Obs2(refSV,4)+Obs2(t,4) ...\n -a(m1+tt,1))*lambda2-t_corr;\n bk(tt,:) = ( rhok_i-rhok_j-rhol_i+rhol_j);\n bk(m1+tt,:) = (rhok_i-rhok_j-rhol_i+rhol_j);\n end; % t\n \n % Kalman filter, see Table 8.2 on page 223 in Borre & Strang (2012):\n % Algorithms for Global Positioning, Wellesley-Cambridge Press\n P = P+Q;\n K = P*A'*inv(A*P*A'+R);\n x = x+ K*(b-A*x);\n P = (eye(3)-K*A)*P;\n b_old = b;\n b_acc = [b_acc b];\n x_acc = [x_acc x];\n X_j = X_i(1:3,:)+x;\n end % switch\n if feof(fid1) == 1, break, end;\n if feof(fid2) == 1, break; end;\nend % while\n\n% Transformation of geocentric baseline coordinates into topocentric coordinates\ne = zeros(1,epoch-11);\nn = zeros(1,epoch-11);\nu = zeros(1,epoch-11);\nfor i = 1:epoch-11\n [e(i),n(i),u(i)] = xyz2enu(phi_j,lambda_j,x_acc(1,i),x_acc(2,i),x_acc(3,i));\nend\n\nfprintf('\\n\\nBaseline Components\\n')\nfprintf('\\nX: %8.3f m, Y: %8.3f m, Z: %8.3f m\\n', ...\n x_acc(1,end), x_acc(2,end), x_acc(3,end))\nfprintf('\\nE: %8.3f m, N: %8.3f m, U: %8.3f m\\n',mean(e,2),mean(n,2),mean(u,2))\n\nfigure(1);\n% we subtract e-, n-, and u-values for epoch 15 to start close to zero!\nplot([(e-e(15))' (n-n(15))' (u-u(15))' ]*1000,'linewidth', .1)\ntitle('Baseline Components from Kalman Filter')\nylabel('Baseline Relative to Initial Epoch [mm]','fontsize',14)\nxlabel('Epochs [1 s interval]','fontsize',14)\nlegend('East','North','Up')\nset(gca,'fontsize',14)\nlegend\n\nprint -dpdf easy61\n\nfigure(2);\nplot(x_acc'*1000)\ntitle('Baseline components {\\it(X}, {\\itY}, {\\itZ})')\n\nylabel('Absolute components [mm]','fontsize',14)\n\nprint -dpdf easy62\n\n%%%%%%%%%% end easy6.m %%%%%%%", "meta": {"author": "yandld", "repo": "nav_matlab", "sha": "da70cb2083de407409ebe1ec1096a308611cf063", "save_path": "github-repos/MATLAB/yandld-nav_matlab", "path": "github-repos/MATLAB/yandld-nav_matlab/nav_matlab-da70cb2083de407409ebe1ec1096a308611cf063/example/gps_spp_test/easysuite/easy6.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6442251201477016, "lm_q2_score": 0.3073580295544412, "lm_q1q2_score": 0.1980077635180707}} {"text": "function obj = eq_pnp_func_new(in1,in2,in3,in4,in5)\ncoef_f0_q_sym1 = in1(:,1);\ncoef_f0_q_sym2 = in1(:,2);\ncoef_f1_q_sym1 = in2(:,1);\ncoef_f0_q_sym3 = in1(:,3);\ncoef_f1_q_sym2 = in2(:,2);\ncoef_f2_q_sym1 = in3(:,1);\ncoef_f0_q_sym4 = in1(:,4);\ncoef_f1_q_sym3 = in2(:,3);\ncoef_f2_q_sym2 = in3(:,2);\ncoef_f3_q_sym1 = in4(:,1);\ncoef_f0_q_sym5 = in1(:,5);\ncoef_f1_q_sym4 = in2(:,4);\ncoef_f2_q_sym3 = in3(:,3);\ncoef_f3_q_sym2 = in4(:,2);\ncoef_f0_q_sym6 = in1(:,6);\ncoef_f1_q_sym5 = in2(:,5);\ncoef_f2_q_sym4 = in3(:,4);\ncoef_f3_q_sym3 = in4(:,3);\ncoef_f0_q_sym7 = in1(:,7);\ncoef_f1_q_sym6 = in2(:,6);\ncoef_f2_q_sym5 = in3(:,5);\ncoef_f3_q_sym4 = in4(:,4);\ncoef_f0_q_sym8 = in1(:,8);\ncoef_f1_q_sym7 = in2(:,7);\ncoef_f2_q_sym6 = in3(:,6);\ncoef_f3_q_sym5 = in4(:,5);\ncoef_f0_q_sym9 = in1(:,9);\ncoef_f1_q_sym8 = in2(:,8);\ncoef_f2_q_sym7 = in3(:,7);\ncoef_f3_q_sym6 = in4(:,6);\ncoef_f1_q_sym9 = in2(:,9);\ncoef_f2_q_sym8 = in3(:,8);\ncoef_f3_q_sym7 = in4(:,7);\ncoef_f2_q_sym9 = in3(:,9);\ncoef_f3_q_sym8 = in4(:,8);\ncoef_f3_q_sym9 = in4(:,9);\ncoef_f0_q_sym10 = in1(:,10);\ncoef_f0_q_sym11 = in1(:,11);\ncoef_f0_q_sym20 = in1(:,20);\ncoef_f1_q_sym10 = in2(:,10);\ncoef_f0_q_sym12 = in1(:,12);\ncoef_f0_q_sym21 = in1(:,21);\ncoef_f1_q_sym11 = in2(:,11);\ncoef_f1_q_sym20 = in2(:,20);\ncoef_f2_q_sym10 = in3(:,10);\ncoef_f0_q_sym13 = in1(:,13);\ncoef_f0_q_sym22 = in1(:,22);\ncoef_f1_q_sym12 = in2(:,12);\ncoef_f1_q_sym21 = in2(:,21);\ncoef_f2_q_sym11 = in3(:,11);\ncoef_f2_q_sym20 = in3(:,20);\ncoef_f3_q_sym10 = in4(:,10);\ncoef_f0_q_sym14 = in1(:,14);\ncoef_f0_q_sym23 = in1(:,23);\ncoef_f1_q_sym13 = in2(:,13);\ncoef_f1_q_sym22 = in2(:,22);\ncoef_f2_q_sym12 = in3(:,12);\ncoef_f2_q_sym21 = in3(:,21);\ncoef_f3_q_sym11 = in4(:,11);\ncoef_f3_q_sym20 = in4(:,20);\ncoef_f0_q_sym15 = in1(:,15);\ncoef_f0_q_sym24 = in1(:,24);\ncoef_f1_q_sym14 = in2(:,14);\ncoef_f1_q_sym23 = in2(:,23);\ncoef_f2_q_sym13 = in3(:,13);\ncoef_f2_q_sym22 = in3(:,22);\ncoef_f3_q_sym12 = in4(:,12);\ncoef_f3_q_sym21 = in4(:,21);\ncoef_f0_q_sym16 = in1(:,16);\ncoef_f1_q_sym15 = in2(:,15);\ncoef_f1_q_sym24 = in2(:,24);\ncoef_f2_q_sym14 = in3(:,14);\ncoef_f2_q_sym23 = in3(:,23);\ncoef_f3_q_sym13 = in4(:,13);\ncoef_f3_q_sym22 = in4(:,22);\ncoef_f0_q_sym17 = in1(:,17);\ncoef_f1_q_sym16 = in2(:,16);\ncoef_f2_q_sym15 = in3(:,15);\ncoef_f2_q_sym24 = in3(:,24);\ncoef_f3_q_sym14 = in4(:,14);\ncoef_f3_q_sym23 = in4(:,23);\ncoef_f0_q_sym18 = in1(:,18);\ncoef_f1_q_sym17 = in2(:,17);\ncoef_f2_q_sym16 = in3(:,16);\ncoef_f3_q_sym15 = in4(:,15);\ncoef_f3_q_sym24 = in4(:,24);\ncoef_f0_q_sym19 = in1(:,19);\ncoef_f1_q_sym18 = in2(:,18);\ncoef_f2_q_sym17 = in3(:,17);\ncoef_f3_q_sym16 = in4(:,16);\ncoef_f1_q_sym19 = in2(:,19);\ncoef_f2_q_sym18 = in3(:,18);\ncoef_f3_q_sym17 = in4(:,17);\ncoef_f2_q_sym19 = in3(:,19);\ncoef_f3_q_sym18 = in4(:,18);\ncoef_f3_q_sym19 = in4(:,19);\nq0 = in5(1,:);\nq1 = in5(2,:);\nq2 = in5(3,:);\nq3 = in5(4,:);\nt92 = q0.^2;\nt93 = q1.^2;\nt94 = q2.^2;\nt95 = q3.^2;\nt96 = t92.^2;\nobj = [-coef_f1_q_sym11.*t92+coef_f0_q_sym18.*t93-coef_f1_q_sym1.*t96+coef_f0_q_sym12.*t93.^2+coef_f0_q_sym11.*q0.*q1-coef_f1_q_sym18.*q0.*q1-coef_f1_q_sym22.*q0.*q2+coef_f0_q_sym22.*q1.*q2-coef_f1_q_sym24.*q0.*q3+coef_f0_q_sym24.*q1.*q3+coef_f0_q_sym2.*t92.*t93-coef_f1_q_sym5.*t92.*t93-coef_f1_q_sym8.*t92.*t94-coef_f1_q_sym10.*t92.*t95+coef_f0_q_sym15.*t93.*t94+coef_f0_q_sym17.*t93.*t95+coef_f0_q_sym1.*q0.*q1.*t92-coef_f1_q_sym2.*q0.*q1.*t92+coef_f0_q_sym5.*q0.*q1.*t93-coef_f1_q_sym12.*q0.*q1.*t93+coef_f0_q_sym8.*q0.*q1.*t94-coef_f1_q_sym15.*q0.*q1.*t94+coef_f0_q_sym10.*q0.*q1.*t95-coef_f1_q_sym17.*q0.*q1.*t95-coef_f1_q_sym3.*q0.*q2.*t92+coef_f0_q_sym6.*q0.*q2.*t93-coef_f1_q_sym13.*q0.*q2.*t93-coef_f1_q_sym19.*q0.*q2.*t94-coef_f1_q_sym21.*q0.*q2.*t95+coef_f0_q_sym3.*q1.*q2.*t92-coef_f1_q_sym4.*q0.*q3.*t92-coef_f1_q_sym6.*q1.*q2.*t92+coef_f0_q_sym7.*q0.*q3.*t93+coef_f0_q_sym13.*q1.*q2.*t93-coef_f1_q_sym14.*q0.*q3.*t93-coef_f1_q_sym20.*q0.*q3.*t94+coef_f0_q_sym19.*q1.*q2.*t94+coef_f0_q_sym21.*q1.*q2.*t95-coef_f1_q_sym23.*q0.*q3.*t95+coef_f0_q_sym4.*q1.*q3.*t92-coef_f1_q_sym7.*q1.*q3.*t92+coef_f0_q_sym14.*q1.*q3.*t93+coef_f0_q_sym20.*q1.*q3.*t94+coef_f0_q_sym23.*q1.*q3.*t95-coef_f1_q_sym9.*q2.*q3.*t92+coef_f0_q_sym16.*q2.*q3.*t93+coef_f0_q_sym9.*q0.*q1.*q2.*q3-coef_f1_q_sym16.*q0.*q1.*q2.*q3;-coef_f2_q_sym11.*t92+coef_f0_q_sym22.*t94-coef_f2_q_sym1.*t96+coef_f0_q_sym19.*t94.^2-coef_f2_q_sym18.*q0.*q1+coef_f0_q_sym11.*q0.*q2-coef_f2_q_sym22.*q0.*q2-coef_f2_q_sym24.*q0.*q3+coef_f0_q_sym18.*q1.*q2+coef_f0_q_sym24.*q2.*q3-coef_f2_q_sym5.*t92.*t93+coef_f0_q_sym3.*t92.*t94-coef_f2_q_sym8.*t92.*t94-coef_f2_q_sym10.*t92.*t95+coef_f0_q_sym13.*t93.*t94+coef_f0_q_sym21.*t94.*t95-coef_f2_q_sym2.*q0.*q1.*t92-coef_f2_q_sym12.*q0.*q1.*t93+coef_f0_q_sym6.*q0.*q1.*t94-coef_f2_q_sym15.*q0.*q1.*t94-coef_f2_q_sym17.*q0.*q1.*t95+coef_f0_q_sym1.*q0.*q2.*t92-coef_f2_q_sym3.*q0.*q2.*t92+coef_f0_q_sym5.*q0.*q2.*t93-coef_f2_q_sym13.*q0.*q2.*t93+coef_f0_q_sym8.*q0.*q2.*t94-coef_f2_q_sym19.*q0.*q2.*t94+coef_f0_q_sym10.*q0.*q2.*t95-coef_f2_q_sym21.*q0.*q2.*t95+coef_f0_q_sym2.*q1.*q2.*t92-coef_f2_q_sym4.*q0.*q3.*t92-coef_f2_q_sym6.*q1.*q2.*t92+coef_f0_q_sym12.*q1.*q2.*t93-coef_f2_q_sym14.*q0.*q3.*t93+coef_f0_q_sym9.*q0.*q3.*t94-coef_f2_q_sym20.*q0.*q3.*t94+coef_f0_q_sym15.*q1.*q2.*t94-coef_f2_q_sym23.*q0.*q3.*t95+coef_f0_q_sym17.*q1.*q2.*t95-coef_f2_q_sym7.*q1.*q3.*t92+coef_f0_q_sym16.*q1.*q3.*t94+coef_f0_q_sym4.*q2.*q3.*t92-coef_f2_q_sym9.*q2.*q3.*t92+coef_f0_q_sym14.*q2.*q3.*t93+coef_f0_q_sym20.*q2.*q3.*t94+coef_f0_q_sym23.*q2.*q3.*t95+coef_f0_q_sym7.*q0.*q1.*q2.*q3-coef_f2_q_sym16.*q0.*q1.*q2.*q3;-coef_f3_q_sym11.*t92+coef_f0_q_sym24.*t95-coef_f3_q_sym1.*t96+coef_f0_q_sym23.*t95.^2-coef_f3_q_sym18.*q0.*q1-coef_f3_q_sym22.*q0.*q2+coef_f0_q_sym11.*q0.*q3-coef_f3_q_sym24.*q0.*q3+coef_f0_q_sym18.*q1.*q3+coef_f0_q_sym22.*q2.*q3-coef_f3_q_sym5.*t92.*t93-coef_f3_q_sym8.*t92.*t94+coef_f0_q_sym4.*t92.*t95-coef_f3_q_sym10.*t92.*t95+coef_f0_q_sym14.*t93.*t95+coef_f0_q_sym20.*t94.*t95-coef_f3_q_sym2.*q0.*q1.*t92-coef_f3_q_sym12.*q0.*q1.*t93-coef_f3_q_sym15.*q0.*q1.*t94+coef_f0_q_sym7.*q0.*q1.*t95-coef_f3_q_sym17.*q0.*q1.*t95-coef_f3_q_sym3.*q0.*q2.*t92-coef_f3_q_sym13.*q0.*q2.*t93-coef_f3_q_sym19.*q0.*q2.*t94+coef_f0_q_sym9.*q0.*q2.*t95-coef_f3_q_sym21.*q0.*q2.*t95+coef_f0_q_sym1.*q0.*q3.*t92-coef_f3_q_sym4.*q0.*q3.*t92-coef_f3_q_sym6.*q1.*q2.*t92+coef_f0_q_sym5.*q0.*q3.*t93-coef_f3_q_sym14.*q0.*q3.*t93+coef_f0_q_sym8.*q0.*q3.*t94-coef_f3_q_sym20.*q0.*q3.*t94+coef_f0_q_sym10.*q0.*q3.*t95+coef_f0_q_sym16.*q1.*q2.*t95-coef_f3_q_sym23.*q0.*q3.*t95+coef_f0_q_sym2.*q1.*q3.*t92-coef_f3_q_sym7.*q1.*q3.*t92+coef_f0_q_sym12.*q1.*q3.*t93+coef_f0_q_sym15.*q1.*q3.*t94+coef_f0_q_sym17.*q1.*q3.*t95+coef_f0_q_sym3.*q2.*q3.*t92-coef_f3_q_sym9.*q2.*q3.*t92+coef_f0_q_sym13.*q2.*q3.*t93+coef_f0_q_sym19.*q2.*q3.*t94+coef_f0_q_sym21.*q2.*q3.*t95+coef_f0_q_sym6.*q0.*q1.*q2.*q3-coef_f3_q_sym16.*q0.*q1.*q2.*q3;t92+t93+t94+t95-1.0];\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/eq_pnp_func_new.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.3451052844289767, "lm_q1q2_score": 0.1966591613488892}} {"text": "function [massImbalance, imBalancedMass, imBalancedCharge, imBalancedRxnBool, elements, missingFormulaeBool, balancedMetBool] = checkMassChargeBalance(model, printLevel, modelName)\n% Tests for a list of reactions if these reactions are\n% mass-balanced by adding all elements on left hand side and comparing them\n% with the sums of elements on the right hand side of the reaction.\n% A reaction is considered elementally imbalanced if any of the molecular\n% species involved is missing a chemical formula.\n%\n% USAGE:\n%\n% [massImbalance, imBalancedMass, imBalancedCharge, imBalancedRxnBool, elements, missingFormulaeBool, balancedMetBool] = checkMassChargeBalance(model, printLevel, modelName)\n%\n% INPUT:\n% model: COBRA model structure:\n%\n% * .S - `m` x `n` stoichiometric matrix\n% * .metForumlas - `m` x 1 cell array of metabolite formulas\n% * .metCharges - `m` x 1 double array of charges\n% * model.SIntRxnBool - Boolean of reactions heuristically though to be mass balanced. (optional)\n%\n% OPTIONAL INPUTS:\n% printLevel: {-1, (0), 1} where:\n%\n% -1 = print out diagnostics on problem reactions to a file,\n% 0 = silent,\n% 1 = print elements as they are checked (display progress),\n% 2 = also print out diagnostics on problem reactions to screen\n% modelName: name of the file\n%\n% OUTPUTS:\n% massImbalance: `nRxn` x `nElement` matrix with mass imbalance\n% for each element checked. 0 if balanced.\n% imBalancedMass: `nRxn` x 1 cell with mass imbalance\n% e.g. -3 H means three hydrogens disappear in the reaction.\n% imBalancedCharge: `nRxn` x 1 vector with charge imbalance, empty if no imbalanced reactions\n% imBalancedRxnBool: boolean vector indicating imbalanced reactions (including exchange reactions!)\n% elements: `nElement` x 1 cell array of element abbreviations checked\n% missingFormulaeBool: `nMet` x 1 boolean vector indicating metabolites without formulae\n% balancedMetBool: boolean vector indicating metabolites exclusively involved in balanced reactions\n%\n%\n% OPTIONAL OUTPUT FILES:\n% modelName_mass_imbalanced_reactions.txt provides a human readable summary\n% for each mass imbalanced reaction. \n%\n% For each reaction it contains:\n% j the index of the column of the stoichiometric matrix corresponding to the reaction\n% rxns{j} the abbreviation of the reaction\n% imbalance the number of each element that is unbalanced\n% equation the reaction equation\n%\n% For each metabolite involved in a reaction it contains\n% i the index of the row of the stoichiometric matrix corresponding to the metabolite\n% mets{i} the abbreviation of the reaction\n% S(i,j) the stoichiometric coefficient\n% metFormulas{i} the chemical formula of the metabolite\n% \n% Example\n% #Rxn;rxnAbbr;imbalance;equation\n% 32;2AMACSULT;3 O, 1 S;2amac[c] + nadph[c] + paps[c] -> nadp[c] + Lcyst[c] + pap[c] \n% 58\t 2amac[c]\t-1\tC3H5NO2\n% 60\t nadph[c]\t-1\tC21H26N7O17P3\n% 61\t nadp[c]\t1\tC21H25N7O17P3\n% 62\t paps[c]\t-1\tC10H11N5O10P2\n% 63\t Lcyst[c]\t1\tC3H6NO5S\n% 64\t pap[c]\t1\tC10H11N5O10P2\n% \n% .. Authors:\n% - Ines Thiele 12/09\n% - IT, 06/10, Corrected some bugs and improved speed.\n% - RF, 09/09/10, Support for very large models and printing to file.\n% - RF, 18/12/14, Default is now to check balancing of all reactions.\n\n[nMet, nRxn]=size(model.S);\n\nif ~exist('printLevel', 'var')\n printLevel=0;\nend\n\nif ~isfield(model,'SIntRxnBool')\n model.SIntRxnBool=true(nRxn,1);%assume all reactions are supposed to be internal if no other info provided\nend\n\nif ~exist('modelName','var')\n modelName='';\nend\nif ~isfield(model,'rxns')\n for i=1:nRxn\n model.rxns{i,1}=['rxn' int2str(i)];\n end\nend\n% List of elements\nelements = {'H','C', 'O', 'P', 'S', 'N', 'Mg','X','Fe','Zn','Co','Ca','Y','I','Na','Cl','K','R','FULLR'};\n\nE=sparse(nMet, length(elements));\nmassImbalance=zeros(nRxn, length(elements));\nmissingFormulaeBool=cellfun(@isempty, model.metFormulas);\nfor j = 1 : length(elements)\n if j==1\n [dE, E_el, missingFormulaeBool]=checkBalance(model, elements{j}, printLevel,[],missingFormulaeBool);\n massImbalance(:, j)=dE;\n E(:, j)=E_el;\n if printLevel>0\n fprintf('%s\\n', ['Checked element ' elements{j}]);\n end\n else\n %no need to print out for each element which metabolites have no\n %formula\n [massImbalance(:, j), E(:, j)]=checkBalance(model, elements{j}, 0);\n if printLevel>0\n fprintf('%s\\n', ['Checking element ' elements{j}]);\n end\n end\nend\n\n%ignore mass imbalance of exchange reactions if the internal reactions have\n%been identified at the input\nif any(~model.SIntRxnBool)\n massImbalance(~model.SIntRxnBool,:)=1;\nend\n\nE=full(E);\n\n% A reaction is considered elementally imbalanced if any of the molecular\n% species involved is missing a chemical formula.\nimBalancedRxnBool=any(massImbalance, 2) | any(model.S(missingFormulaeBool, :),1)';\n\nimBalancedMass=cell(nRxn, 1);\nfor i = 1 : nRxn\n imBalancedMass{i, 1}='';\n if imBalancedRxnBool(i)\n for j = 1 : length(elements)\n if massImbalance(i, j) ~= 0\n if ~strcmp(imBalancedMass{i, 1}, '')\n imBalancedMass{i, 1} = [imBalancedMass{i, 1} ', ' int2str(massImbalance(i, j)) ' ' elements{j}];\n else\n imBalancedMass{i, 1} = [int2str(massImbalance(i, j)) ' ' elements{j}];\n end\n end\n end\n if strfind(imBalancedMass{i, 1}, 'NaN')\n imBalancedMass{i, 1}='NaN';\n end\n end\n if mod(i, 1000)==0\n fprintf('%n\\t%s\\n', i, ['reactions checked for ' elements{j} ' balance']);\n end\nend\nif printLevel==-1\n firstMissing=0;\n for p=1:nRxn\n %only print out for reactions supposed to be mass balanced\n if model.SIntRxnBool(p) && ~strcmp(imBalancedMass{p,1},'')\n %at the moment, ignore reactions with a metabolite that have\n %no formula\n if ~strcmp(imBalancedMass{p, 1}, 'NaN')\n if ~firstMissing\n fid=fopen([modelName 'mass_imbalanced_reactions.txt'],'w');\n fprintf(fid, '%s;%s;%s;%s\\n', 'j', 'rxns{j}', 'imbalance', 'equation');\n fprintf(fid, '%s;%s;%s;%s\\n\\n', 'i', 'mets{i}', 'S(i,j)', 'metFormulas{i}');\n fprintf('%s\\n',['There are mass imbalanced reactions, see ' modelName 'mass_imbalanced_reactions.txt'])\n firstMissing=1;\n end\n equation=printRxnFormula(model, model.rxns(p), 0);\n fprintf(fid, '%s;%s;%s;%s\\n', int2str(p), model.rxns{p}, imBalancedMass{p, 1}, equation{1});\n for m=1:size(model.S, 1)\n if model.S(m, p) ~= 0\n fprintf(fid,'%5u\\t%15s\\t%g\\t%s\\n',m,model.mets{m},full(model.S(m,p)),model.metFormulas{m});\n end\n end\n end\n end\n end\n if firstMissing\n fclose(fid);\n end\nend\nif printLevel==2\n for p=1:nRxn\n %only print out for reactions supposed to be mass balanced\n if model.SIntRxnBool(p) && ~strcmp(imBalancedMass{p,1},'')\n %at the moment, ignore reactions with a metabolite that have\n %no formula\n if ~strcmp(imBalancedMass{p, 1}, 'NaN')\n equation=printRxnFormula(model, model.rxns(p), 0);\n fprintf('%6s\\t%30s\\t%10s\\t%s\\n', int2str(p), model.rxns{p}, imBalancedMass{p, 1}, equation{1});\n % for m=1:size(model.S, 1)\n % if model.S(m, p) ~= 0\n % fprintf('%5u\\t%15s\\t%g\\t%s\\n',m,model.mets{m},full(model.S(m,p)),model.metFormulas{m});\n % end\n % end\n\n end\n end\n end\nend\n\n%\nif nnz(strcmp('', imBalancedMass))==nRxn\n imBalancedMass=[];\nend\n\n% Check for charge balance (initialize with NaN, if the fields are not set\n% this will make it clear.\nimBalancedCharge = NaN * ones(nRxn, 1);\nfirstMissing=0;\nif isfield(model, 'metCharges')\n for m=1:nMet\n if isnan(model.metCharges(m)) && ~isempty(model.metFormulas{m})\n if printLevel==2\n fprintf('%s\\t%s\\n', int2str(m), [model.mets{m} ' has no charge but has formula.'])\n if ~firstMissing\n warning('model structure must contain model.metCharges field for each metabolite');\n end\n firstMissing=1;\n end\n if printLevel==-1\n if ~firstMissing\n fid=fopen([modelName 'metabolites_without_charge.txt'],'w');\n end\n firstMissing=1;\n fprintf(fid, '%s\\t%s\\n', int2str(m), model.mets{m});\n end\n end\n end\n\n imBalancedCharge = model.S' * double(model.metCharges); % Matlab does not support this operation on two int values - one needs to be converted to double. The smaller matrix is selected.\nend\n\nif printLevel==-1 && isfield(model,'SIntRxnBool')\n firstMissing=0;\n if any(imBalancedCharge)\n for q=1:nRxn\n if model.SIntRxnBool(q) && strcmp(imBalancedMass{q, 1}, '') && imBalancedCharge(q) ~= 0\n if ~firstMissing\n fid=fopen([modelName 'mass_balanced_charge_imbalanced_reactions.txt'],'w');\n fprintf('%s\\n',['There are mass balanced, but charge imbalanced reactions, see ' modelName 'charge_imbalanced_reactions.txt'])\n firstMissing=1;\n end\n equation=printRxnFormula(model, model.rxns(q), 0);\n fprintf(fid, '%s\\t%s\\t%s\\n', int2str(q), model.rxns{q}, equation{1});\n % for m=1:size(model.S, 1)\n % if model.S(m, q) ~= 0\n % fprintf(fid,'%5u\\t%15s\\t%g\\t%g\\t%s\\n',m,model.mets{m},full(model.S(m,q)),model.metCharges(m),model.metFormulas{m});\n % end\n % end\n end\n end\n if firstMissing\n fclose(fid);\n end\n end\nend\n\nif printLevel==2 && isfield(model,'SIntRxnBool')\n if any(imBalancedCharge)\n fprintf('%s\\n', 'Mass balanced, but charged imbalanced reactions:')\n for q=1:nRxn\n if model.SIntRxnBool(q) && strcmp(imBalancedMass{p, 1}, '') && imBalancedCharge(q) ~= 0\n equation=printRxnFormula(model, model.rxns(q), 0);\n fprintf('%s\\t%s\\t%s\\n', int2str(q), model.rxns{q}, equation{1});\n for m=1:size(model.S, 1)\n if model.S(m, q) ~= 0\n fprintf('%5u\\t%15s\\t%g\\t%g\\t%s\\n',m,model.mets{m},full(model.S(m,q)),model.metCharges(m),model.metFormulas{m});\n end\n end\n end\n end\n end\nend\n\n%If the field is set we should assume, that all values are defined.\nif isfield(model, 'metCharges')\n imBalancedRxnBool = imBalancedRxnBool | imBalancedCharge ~= 0;\nend\n\nif isfield(model,'SIntRxnBool')\n imBalancedRxnBool = imBalancedRxnBool | ~model.SIntRxnBool;\nend\n\n%nonzero rows corresponding to completely mass balanced reactions\nbalancedMetBool = getCorrespondingRows(model.S,true(nMet,1),~imBalancedRxnBool,'exclusive');\nmassImbalance = sparse(massImbalance);\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/src/reconstruction/modelGeneration/massBalance/checkMassChargeBalance.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5851011397337391, "lm_q2_score": 0.334589441253186, "lm_q1q2_score": 0.1957686634201141}} {"text": "function DVH_out = DVHwithShifts(planC,structNum,doseNum)\n%function DVH_out = DVHwithShifts(planC,structNum,doseNum)\n%\n%APA, 11/09/2010\n%\n% Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team.\n% \n% This file is part of The Computational Environment for Radiotherapy Research (CERR).\n% \n% CERR development has been led by: Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy.\n% \n% CERR has been financially supported by the US National Institutes of Health under multiple grants.\n% \n% CERR is distributed under the terms of the Lesser GNU Public License. \n% \n% This version of CERR is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% CERR is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;\n% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n% See the GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with CERR. If not, see .\n\n%Number of Fractions and Trials\nnumFractions = 30;\nnumTrials = 100;\n\n% Systematic Shifts in cm (Inter-treatment)\nXdispSys_Std = 0;\nYdispSys_Std = 0;\nZdispSys_Std = 0;\n\n% Random Shifts in cm (inter-fraction)\nXdispRnd_Std = 1;\nYdispRnd_Std = 1;\nZdispRnd_Std = 1;\n\nindexS = planC{end};\n\n%Distances are in cm\nXpdfMean = 0;\n\nYpdfMean = 0;\n\nZpdfMean = 0;\n\n%Get scan associated with doseNum\nscanNum = getAssociatedScan(planC{indexS.dose}(doseNum).assocScanUID, planC);\n\nif isempty(scanNum) %Assume dose is associated with this scan\n scanNum = getStructureAssociatedScan(structNum,planC);\nend\n\n%Get reference transformation matrix for doseNum\nif ~isempty(scanNum) && isempty(planC{indexS.dose}(doseNum).transM)\n referenceTransM = planC{indexS.scan}(scanNum).transM;\nelse\n referenceTransM = planC{indexS.dose}(doseNum).transM;\nend\n\n%Store the reference doseArray\nreferenceDoseArray = planC{indexS.dose}(doseNum).doseArray;\n\n%Try and get a binWidth from stateS. If it doesnt exist, get it from\n%the CERROptions file (allows this function to be called outside CERR)\nglobal stateS;\nif ~isempty(stateS) && isfield(stateS, 'optS') && isfield(stateS.optS, 'DVHBinWidth') && ~isempty(stateS.optS.DVHBinWidth)\n binWidth = stateS.optS.DVHBinWidth;\nelse\n optS = CERROptions;\n binWidth = optS.DVHBinWidth;\nend\n\n%Compute DVH at given dose\n[dosesCurrentV, volsV] = getDVH(structNum, doseNum, planC);\n[doseBinsCurrentV, volsHistCurrentV] = doseHist(dosesCurrentV, volsV, binWidth);\n\n%Divide doseArray into fractions\nplanC{indexS.dose}(doseNum).doseArray = planC{indexS.dose}(doseNum).doseArray / numFractions;\n\n%Get systematic errors\ndeltaX_systematic = randn(1, numTrials) * XdispSys_Std + XpdfMean;\ndeltaY_systematic = randn(1, numTrials) * YdispSys_Std + YpdfMean;\ndeltaZ_systematic = randn(1, numTrials) * ZdispSys_Std + ZpdfMean;\n\nhWait = waitbar(0,'Computing plan robustness...');\n\nif isempty(referenceTransM)\n referenceTransM_matrix = eye(4);\nelse\n referenceTransM_matrix = referenceTransM;\nend\n\n\n%Obtain DVH calculation points in blocks\noptS = planC{indexS.CERROptions};\n\nROIImageSize = [planC{indexS.scan}(scanNum).scanInfo(1).sizeOfDimension1 planC{indexS.scan}(scanNum).scanInfo(1).sizeOfDimension2];\n\ndeltaY = planC{indexS.scan}(scanNum).scanInfo(1).grid1Units;\n\n%Get raster segments for structure.\n[segmentsM, planC, isError] = getRasterSegments(structNum, planC);\n\nif isempty(segmentsM)\n isError = 1;\nend\nnumSegs = size(segmentsM,1);\n\n%Relative sampling of ROI voxels in this place, compared to CT spacing.\n%Set when rasterSegments are generated (usually on import).\nsampleRate = optS.ROISampleRate;\n\n%Sample the rows\nindFullV = 1 : numSegs;\nif sampleRate ~= 1\n rV = 1 : length(indFullV);\n rV([rem(rV+sampleRate-1,sampleRate)~=0]) = [];\n indFullV = rV;\nend\n\n%Block process to avoid swamping on large structures\nif isfield(optS, 'DVHBlockSize') & ~isempty(optS.DVHBlockSize)\n DVHBlockSize = optS.DVHBlockSize;\nelse\n DVHBlockSize = 5000; \nend\n\nblocks = ceil(length(indFullV)/DVHBlockSize);\n\nstart = 1;\n\nfor b = 1 : blocks\n\n %Build the interpolation points matrix\n\n dummy = zeros(1,DVHBlockSize * ROIImageSize(1));\n x1V = dummy;\n y1V = dummy;\n z1V = dummy;\n volsSectionV = dummy;\n\n if start+DVHBlockSize > length(indFullV)\n stop = length(indFullV);\n else\n stop = start + DVHBlockSize - 1;\n end\n\n indV = indFullV(start:stop);\n\n mark = 1;\n for i = indV\n\n tmpV = segmentsM(i,1:10);\n delta = tmpV(5) * sampleRate;\n xV = tmpV(3): delta : tmpV(4);\n len = length(xV);\n rangeV = ones(1,len);\n yV = tmpV(2) * rangeV;\n zV = tmpV(1) * rangeV;\n sliceThickness = tmpV(10);\n %v = delta^2 * sliceThickness;\n v = delta * (deltaY*sampleRate) * sliceThickness;\n x1V(mark : mark + len - 1) = xV;\n y1V(mark : mark + len - 1) = yV;\n z1V(mark : mark + len - 1) = zV;\n volsSectionV(mark : mark + len - 1) = v;\n mark = mark + len;\n\n end\n\n %cut unused matrix elements\n x1V = x1V(1:mark-1);\n y1V = y1V(1:mark-1);\n z1V = z1V(1:mark-1);\n volsSectionV = volsSectionV(1:mark-1);\n\n %Get transformation matrices for both dose and structure.\n transMDose = getTransM('dose', doseNum, planC);\n transMStruct = getTransM('struct', structNum, planC); \n \n %Forward transform the structure's coordinates.\n if ~isempty(transMStruct)\n [x1V, y1V, z1V] = applyTransM(transMStruct, x1V, y1V, z1V);\n end\n\n dvhCalcPtsC{b} = [x1V', y1V', z1V'];\n \n %Interpolate.\n% [dosesSectionV] = getDoseAt(doseNum, x1V, y1V, z1V, planC);\n\n% dosesV = [dosesV, dosesSectionV];\n% volsV = [volsV, volsSectionV];\n\n start = stop + 1;\n\nend\n\n\n%Loop over to generate DVH\nfor iTrial = 1:numTrials\n\n deltaX = deltaX_systematic(iTrial) + randn(1, numFractions) * XdispRnd_Std + XpdfMean;\n deltaY = deltaY_systematic(iTrial) + randn(1, numFractions) * YdispRnd_Std + YpdfMean;\n deltaZ = deltaZ_systematic(iTrial) + randn(1, numFractions) * ZdispRnd_Std + ZpdfMean;\n \n tmpDoseV = zeros(1,length(dosesCurrentV));\n \n for iFraction = 1:numFractions\n\n waitbar(((iTrial-1)*numFractions + iFraction)/(numTrials*numFractions),hWait)\n \n transM = referenceTransM_matrix;\n transM(1:3,4) = transM(1:3,4) + [deltaX(iFraction); deltaY(iFraction); deltaZ(iFraction)];\n\n %Apply the new transM to dose\n planC{indexS.dose}(doseNum).transM = transM;\n\n %Get doses and volumes of points in structure.\n %[dosesV, volsV] = getDVH(structNum, doseNum, planC);\n\n volsV = [];\n dosesV = [];\n \n for b = 1 : blocks\n x1V = dvhCalcPtsC{b}(:,1);\n y1V = dvhCalcPtsC{b}(:,2);\n z1V = dvhCalcPtsC{b}(:,3);\n\n %Back transform the coordinates into the doses' coordinate system. \n [x1V, y1V, z1V] = applyTransM(inv(transM), x1V, y1V, z1V);\n \n %Interpolate.\n [dosesSectionV] = getDoseAt(doseNum, x1V, y1V, z1V, planC);\n\n dosesV = [dosesV, dosesSectionV];\n volsV = [volsV, volsSectionV];\n end\n \n tmpDoseV = tmpDoseV + dosesV;\n\n end\n\n DVHm(:,iTrial) = single(tmpDoseV(:));\n\n %Compute Mean and Std for binned dose\n %for iTrial=1:numTrials\n doseTrialV = DVHm(:,iTrial);\n [doseBinsV, volsHistV] = doseHist(doseTrialV, volsV, binWidth);\n doseBinsTmpV = doseBinsV;\n volsHistTmpV = volsHistV;\n if iTrial > 1\n AddToCurrent = ~ismember(doseBins{1},doseBinsV);\n AddToPrevious = ~ismember(doseBinsV,doseBins{1});\n doseBinsV = [doseBinsV doseBins{1}(AddToCurrent)];\n volsHistV = [volsHistV volsHist{1}(AddToCurrent)];\n for jTrial = 1:iTrial-1\n doseBins{jTrial} = [doseBins{jTrial} doseBinsTmpV(AddToPrevious)];\n volsHist{jTrial} = [volsHist{jTrial} volsHistTmpV(AddToPrevious)];\n [doseBins{jTrial},indSort] = sort(doseBins{jTrial});\n volsHist{jTrial} = volsHist{jTrial}(indSort);\n end\n end\n doseBins{iTrial} = doseBinsV;\n volsHist{iTrial} = volsHistV;\n [doseBins{iTrial},indSort] = sort(doseBins{iTrial});\n volsHist{iTrial} = volsHist{iTrial}(indSort);\n %end\n\n\nend\n\nclose(hWait)\n\n%Compute Std of binned volumes\nblockSize = 100;\nfor iBlock = 1:ceil(length(volsHist{1})/blockSize)\n if iBlock == ceil(length(volsHist{1})/blockSize)\n indicesV = (iBlock-1)*blockSize+1:length(volsHist{1});\n else\n indicesV = (iBlock-1)*blockSize+1:iBlock*blockSize;\n end\n volsHistStdM = [];\n for iTrial = 1:length(volsHist)\n volsHistStdM(:,iTrial) = volsHist{iTrial}(indicesV);\n end\n volsHistStdV(indicesV) = std(volsHistStdM,0,2)';\nend\n\n%Reassign reference transM and doseArray to doseNum\nplanC{indexS.dose}(doseNum).transM = referenceTransM;\nplanC{indexS.dose}(doseNum).doseArray = referenceDoseArray;\n\n\n%Compute Mean and Std Dev in blocks\nnumVoxels = length(volsV);\nDVHBlockSize = 5000;\nblocks = ceil(numVoxels/DVHBlockSize);\nstart = 1;\n\nfor b = 1 : blocks\n\n if start+DVHBlockSize > numVoxels\n stop = numVoxels;\n else\n stop = start + DVHBlockSize - 1;\n end\n\n DVH_block = DVHm(start:stop,:);\n \n meanDoseV(start:stop) = mean(DVH_block,2);\n stdDoseV(start:stop) = std(DVH_block,0,2);\n \n start = stop + 1;\n\nend\n\nDVH_out = [meanDoseV(:)'; volsV(:)'];\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_Data_Extraction/DVHwithShifts.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.3557748935136304, "lm_q1q2_score": 0.19451570780216507}} {"text": "function isodoseClosedContour = getBeamCrossSection()\n%isodoseClosedContour50 = getBeamCrossSection()\n%\n%Output: isodoseClosedContour - representation of beam contour\n%dimension (3xN). 1st, 2nd and 3rd row represent x, y and z-coords of the\n%contour respectively. It is assumed that the ray starts at (0,0,0) and\n%moves along +(ve) x-axis. If collimatorType does not match the list, an\n%empty isodoseClosedContour50 is returned.\n%\n%APA 01/21/09\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% Get a 10x10 section at 100cm distance. In future, these points should\n% come from Leaf-sequences or beamlet-fluence map.\nisodoseClosedContour(3,:) = [-10 10 10 -10 -10]/2;\nisodoseClosedContour(2,:) = [-10 -10 10 10 -10]/2;\nisodoseClosedContour(1,:) = [100 100 100 100 100];\nreturn\n", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/IMRTP/getBeamCrossSection.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.36658974324230986, "lm_q1q2_score": 0.19188053132436728}} {"text": "function rtk=udclk_ppp(rtk)\n\nglobal glc\nopt=rtk.opt; VAR_CLK=60^2; CLIGHT=glc.CLIGHT; tt=abs(rtk.tt);\nnavsys=opt.navsys; mask=rtk.mask; prn=0;\n\n% for single-system except GPS\nif strcmp(navsys,'R')\n dtr=rtk.sol.dtr(2);\n if abs(dtr)<=1e-16,dtr=1e-16;end\n rtk=initx(rtk,CLIGHT*dtr,VAR_CLK,rtk.ic+2);\n \n % for GLONASS icb\n if opt.gloicb==glc.GLOICB_LNF\n if rtk.x(rtk.iicb+1)==0\n rtk=initx(rtk,0.1,VAR_CLK,rtk.iicb+1);\n end\n elseif opt.gloicb==glc.GLOICB_QUAD\n if rtk.x(rtk.iicb+1)==0\n rtk=initx(rtk,0.1,VAR_CLK,rtk.iicb+1);\n end\n if rtk.x(rtk.iicb+2)==0\n rtk=initx(rtk,0.1,VAR_CLK,rtk.iicb+2);\n end\n end\n return\nelseif strcmp(navsys,'E')\n dtr=rtk.sol.dtr(3);\n if abs(dtr)<=1e-16,dtr=1e-16;end\n rtk=initx(rtk,CLIGHT*dtr,VAR_CLK,rtk.ic+3);\n return\nelseif strcmp(navsys,'C')\n dtr=rtk.sol.dtr(4);\n if abs(dtr)<=1e-16,dtr=1e-16;end\n rtk=initx(rtk,CLIGHT*dtr,VAR_CLK,rtk.ic+4);\n return\nelseif strcmp(navsys,'J')\n dtr=rtk.sol.dtr(5);\n if abs(dtr)<=1e-16,dtr=1e-16;end\n rtk=initx(rtk,CLIGHT*dtr,VAR_CLK,rtk.ic+5);\n return\nend\n\n% for GPS or multi-system\ndtr=rtk.sol.dtr(1);\nif abs(dtr)<=1e-16,dtr=1e-16;end\nrtk=initx(rtk,CLIGHT*dtr,VAR_CLK,rtk.ic+1);\nfor i=2:glc.NSYS\n if mask(i)==0,continue;end\n if i==glc.SYS_GLO\n dtr=rtk.sol.dtr(2);\n if rtk.x(rtk.ic+2)==0\n if abs(dtr)<=1e-16,dtr=1e-16;end\n rtk=initx(rtk,CLIGHT*dtr,VAR_CLK,rtk.ic+2);\n else\n rtk.P(rtk.ic+i,rtk.ic+i)=rtk.P(rtk.ic+i,rtk.ic+i)+prn^2*tt;\n end\n % for GLONASS icb\n if opt.gloicb==glc.GLOICB_LNF\n if rtk.x(rtk.iicb+1)==0\n rtk=initx(rtk,0.1,VAR_CLK,rtk.iicb+1);\n end\n elseif opt.gloicb==glc.GLOICB_QUAD\n if rtk.x(rtk.iicb+1)==0\n rtk=initx(rtk,0.1,VAR_CLK,rtk.iicb+1);\n end\n if rtk.x(rtk.iicb+2)==0\n rtk=initx(rtk,0.1,VAR_CLK,rtk.iicb+2);\n end\n end\n else\n dtr=rtk.sol.dtr(i);\n if rtk.x(rtk.ic+i)==0\n if abs(dtr)<=1e-16,dtr=1e-16;end\n rtk=initx(rtk,CLIGHT*dtr,VAR_CLK,rtk.ic+i);\n else\n rtk.P(rtk.ic+i,rtk.ic+i)=rtk.P(rtk.ic+i,rtk.ic+i)+prn^2*tt;\n end\n end \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/udclk_ppp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953797290153, "lm_q2_score": 0.33111973962899144, "lm_q1q2_score": 0.19122011977281708}} {"text": "%%*******************************************************************\n%% NTrhsfun: 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] = NTrhsfun(blk,At,par,X,Z,rp,Rd,sigmu,hRd,dX,dZ)\n\nspdensity = par.spdensity;\nm = length(rp);\nif (nargin > 8)\n corrector = 1;\nelse\n corrector = 0;\n hRd = zeros(m,1);\nend\nhEinvRc = zeros(m,1);\nEinvRc = cell(size(blk,1),1);\nrhsfree = [];\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 iscell(sigmu)\n EinvRc{p} = sigmu{p}./Z{p} -X{p};\n 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 EinvRc{p} = EinvRc{p} - Rq;\n tmp2 = mexMatvec(At{p},EinvRc{p},1);\n hEinvRc = hEinvRc + tmp2;\n elseif strcmp(pblk{1},'q')\n if iscell(sigmu)\n EinvRc{p} = qops(pblk,-sigmu{p}./(par.gamz{p}.*par.gamz{p}),Z{p},4) -X{p};\n else\n EinvRc{p} = qops(pblk,-sigmu./(par.gamz{p}.*par.gamz{p}),Z{p},4) -X{p};\n end\n Rq = sparse(n,1);\n if (corrector) && (norm(par.parbarrier{p})==0)\n w = sqrt(par.gamz{p}./par.gamx{p});\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 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} = EinvRc{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 iscell(sigmu)\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 tmp = spdiags(sigmuvec./par.sv{p} -par.sv{p},0,n,n);\n else\n tmp = spdiags(sigmu./par.sv{p} -par.sv{p},0,n,n);\n end\n EinvRc{p} = Prod3(pblk,par.G{p}',tmp,par.G{p},1);\n Rq = sparse(n,n);\n if (corrector) && (norm(par.parbarrier{p})==0)\n hdZ = Prod3(pblk,par.G{p},dZ{p},par.G{p}',1);\n hdX = spdiags(qops(pblk,par.parbarrier{p}',1./par.sv{p},3)-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 ss = [0, cumsum(pblk{2})];\n for i = 1:numblk\n pos = ss(i)+1 : ss(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 Rq = Prod3(pblk,par.G{p}',Rq,par.G{p},1);\n else\n tmp = Prod3(pblk,par.W{p},Rd{p},par.W{p},1,par.nzlistAy{p});\n tmp2 = AXfun(pblk,At(p,:),par.permA(p,:),{tmp});\n hRd = hRd + tmp2;\n end\n 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}]; %#ok\n end\nend\n%%\nrhs = rp + hRd - hEinvRc;\nrhs = full([rhs; rhsfree]);\n%%*******************************************************************\n", "meta": {"author": "zarathustr", "repo": "LibQPEP", "sha": "99e5c23e746ace0bac4a86742c31db6fcf7297ba", "save_path": "github-repos/MATLAB/zarathustr-LibQPEP", "path": "github-repos/MATLAB/zarathustr-LibQPEP/LibQPEP-99e5c23e746ace0bac4a86742c31db6fcf7297ba/MATLAB/sdpt3/Solver/NTrhsfun.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3557748866829643, "lm_q1q2_score": 0.18621981533037832}} {"text": "function [position0,position,messages]= delineateP3D(heasig,w1,w2,w3,timenew,position0,position,intervalo,samp,ultimo_anot,messages)\n%\n% [position0,position,A,V,A2,V2]=% delineateP3D(heasig,w1,w2,w3,intreg,scale,timenew,position0,position,intervalo,samp,figuresoff,sig)\n%\n% Input Parameters:\n% heasig: struct vector with header information\n% w1: matrix with WT scales 1 to 5 for lead 1\n% w2: matrix with WT scales 1 to 5 for lead 2\n% w3: matrix with WT scales 1 to 5 for lead 1\n% intreg: interval to be considered in fitting the optimal direction\n% scale to use in delineation\n% timenew: QRS times in inedexes refering the interval included in the current excerpt (borders excluded)\n% position0: struct vector with the detected points for 3D multilead step1\n% position: struct vector with the detected points for 3D multilead step2\n% position1: struct vector with the detected points for lead1 - to be replaced for multilead marks\n% samp: samples included in the current excerpt (borders excluded)\n% intervalo: numeration of the beats processed in this segment\n%\n%Output Parameters:\n% actualized parameters: position, position0\n% A - points of fitted lines in step 1\n% A2 - points of fitted lines in step 2\n% V- vectors director to the fitted line\n% V2- vectors director to the fitted line\n%\n% Rute Almeida: trabalho de doutoramento\n% Last update: 07FEB2012 Rute Almeida\n%\n% MATLAB Version 6.5.0.180913a (R13)\n\nif nargin<11\n messages = new_empty_mesg;\nelseif nargin<10\n messages.errors=[messages.errors {'Fatal error in wavedet_3D\\delineate3D: not enough inputs.'}];\n warning(char(messages.errors(end)))\n messages.errors_desc=[messages.errors_desc 'Mandatory inputs not defined.'];\n messages.status=0;\n return\nend\nif ~isfield(messages,'setup'), messages.setup.wavedet=[]; end\nif ~isfield(messages,'errors'), messages.errors=[]; end\nif ~isfield(messages,'errors_desc'), messages.errors_desc=[]; end\nif ~isfield(messages,'warnings'), messages.warnings=[]; end\nif isfield(messages,'status')\n if messages.status~=1\n messages.warnings=[messages.warnings {['Initial status=' num2str(messages.status) '. status changed to 1']}];\n end\nend\nmessages.status=1;\n\nglobal recursioncount OPT\n\n%Threshols for onset and offset detection\n%%%%%% Constants and Thresholds !!!!!!!!!!!!!!!!!!!!!!!!!\nif ~isfield(messages.setup.wavedet,'inivent_tol_P')\n messages.setup.wavedet.inivent_tol_P = 0.34;\nend\nif ~isfield(messages.setup.wavedet,'finvent_tol_P')\n messages.setup.wavedet.finvent_tol_P = 0.1;\nend\nif ~isfield(messages.setup.wavedet,'P_CSE_tol')\n messages.setup.wavedet.P_CSE_tol=10.2*2/1000; % based on CSE tolerance\nend\nif ~isfield(messages.setup.wavedet,'Pconvergence_crit')\n messages.setup.wavedet.Pconvergence_crit=0; % 1 maks are acepted as the same if they difer by Tconvergence_crit\nend\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nA2=[];\nif ~isempty(w3)\n V=NaN*ones(size(timenew,2),3);\n A=NaN*ones(size(timenew,2),3);\nelse\n V=NaN*ones(size(timenew,2),2);\n A=NaN*ones(size(timenew,2),2);\nend\nV2=[];\nintervalo=intervalo(1):intervalo(end);\nfor i=1:size(timenew,2)\n \n if ~isnan(position.QRSon(i+intervalo(1)-1))\n qrson = position.QRSon(i+intervalo(1)-1)-samp(1)+1;\n else\n qrson = timenew(i) - messages.setup.wavedet.finvent_tol_P*messages.setup.wavedet.freq;\n end\n \n ultimo_anot = ultimo_anot - samp(1)+1;\n % last anotation of the previous segment can overlap with the present one\n if (i==1 && ultimo_anot>=1), % Protection in case it is the first beat\n begwin = max([1 qrson-round(messages.setup.wavedet.inivent_tol_P*messages.setup.wavedet.freq)+1 ultimo_anot+1]);\n else\n begwin = max(1, qrson-round(messages.setup.wavedet.inivent_tol_P*messages.setup.wavedet.freq)+1);\n end\n endwin = qrson- round(messages.setup.wavedet.finvent_tol_P*messages.setup.wavedet.freq)+1;\n \n if begwin>=endwin % empty search window: ultimo_anot should be too close to qrson\n position.Ptipoon(intervalo(i))=NaN;\n position.Ppicon(intervalo(i))=NaN;\n position.PscalePon(intervalo(i))=NaN;\n position.Pon(intervalo(i))=NaN;\n recursioncount.Pon(intervalo(i))=NaN;\n position.contadorPon(intervalo(i))=NaN;\n position.PscalePoff(intervalo(i))=NaN;\n position.Ppicoff(intervalo(i))=NaN;\n position.Poff(intervalo(i))=NaN;\n position.Ptipooff(intervalo(i))=NaN;\n recursioncount.Poff(intervalo(i))=NaN;\n position.contadorPoff(intervalo(i))=NaN; %Rute\n position.P(intervalo(i))=NaN;\n else\n \n scale=4;\n if ~isempty(w3)\n pontos=[w1(begwin:min(endwin,length(w1)),scale) w2(begwin:min(endwin,length(w2)),scale) w3(begwin:min(endwin,length(w3)),scale)];\n else\n pontos=[w1(begwin:min(endwin,length(w1)),scale) w2(begwin:min(endwin,length(w2)),scale)];\n end\n weight=ones(size(pontos,1),1);\n [a,v] = optimline(pontos, weight,OPT);\n A(i,:)=a;\n V(i,:)=v;\n %WT projected: from the previous QRS complex to the following QRS complex\n newleadbeat=[];\n if ~isempty(w3)\n if i>1,\n interval=timenew(i-1):timenew(i);\n else % if first beat of the segment\n interval=1:timenew(i);\n end\n \n newleadbeat(interval,3)=(w1(interval,3).*v(1)+w2(interval,3)*v(2)+w3(interval,3)*v(3))./norm(v); %#ok\n newleadbeat(interval,4)=(w1(interval,4).*v(1)+w2(interval,4)*v(2)+w3(interval,4)*v(3))./norm(v); %#ok\n newleadbeat(interval,5)=(w1(interval,5).*v(1)+w2(interval,5)*v(2)+w3(interval,5)*v(3))./norm(v); %#ok\n %signew(interval)=(sig(interval,1).*v(1)+sig(interval,2)*v(2)+sig(interval,3)*v(3))./norm(v);\n else\n if i>1,\n interval=timenew(i-1):timenew(i);\n else % if first beat of the segment\n interval=1:timenew(i);\n end\n % newleadbeat=NaN*ones(length(interval),5);\n newleadbeat(:,3)=(w1(interval,3).*v(1)+w2(timenew(i):timenew(i+1),3)*v(2))./norm(v);\n newleadbeat(:,4)=(w1(interval,4).*v(1)+w2(timenew(i):timenew(i+1),4)*v(2))./norm(v);\n newleadbeat(:,5)=(w1(interval,5).*v(1)+w2(timenew(i):timenew(i+1),5)*v(2))./norm(v);\n %signew=(sig(timenew(i):timenew(i+1),1).*v(1)+sig(timenew(i):timenew(i+1),2)*v(2))./norm(v);\n end\n if i>1,\n pos.qrs=position.qrs([i-1 i]);\n pos.QRSon=position.QRSon([i-1 i]);\n pos.QRSoff=position.QRSoff([i-1 i]);\n pos.Toff=position.Toff([i-1 i]);\n [pos,picon,picoff]= pwavef(heasig,samp,timenew([i i]),position,newleadbeat,[intervalo(i) intervalo(i)],ultimo_anot,messages);\n else\n pos.qrs=position.qrs(i);\n pos.QRSon=position.QRSon(i);\n pos.QRSoff=position.QRSoff(i);\n pos.Toff=position.Toff(i);\n [pos,picon,picoff]= pwavef(heasig,samp,timenew(i),position,newleadbeat,[intervalo(i) intervalo(i)] ,ultimo_anot,messages);\n end\n \n position0.Pscale(intervalo(i))=pos.Pscale(intervalo(i));\n position0.Pon(intervalo(i))=pos.Pon(intervalo(i));\n position0.Poff(intervalo(i))=pos.Poff(intervalo(i));\n position0.Ptipo(intervalo(i))=pos.Ptipo(intervalo(i));\n position0.direccionPonopt(:,intervalo(i))=NaN*ones(size(intervalo(i)));\n %position0.P(intervalo(i))=pos.P(intervalo(i));\n %position0.Pprima(intervalo(i))=pos.Pprima(intervalo(i));\n \n \n %%%%% P wave onset\n if ~isnan(picon)\n \n begaux=max([(position0.Pon(intervalo(i))-samp(1)+1-round(messages.setup.wavedet.P_CSE_tol*messages.setup.wavedet.freq)) 1]);\n if ~isempty(w3)\n pontos2on=[w1(begaux:picon,scale) w2(begaux:picon,scale) w3(begaux:picon,scale)];\n else\n pontos2on=[w1(begaux:picon,scale) w2(begaux:picon,scale)];\n end\n if size(pontos2on,1)<=1 % unable to do another step: empty search window\n position.contadorPon(intervalo(i))=-1;\n position.PscalePon(intervalo(i))=position0.Pscale(intervalo(i));\n position.Pon(intervalo(i))=position0.Pon(intervalo(i));\n position.Ppicon=picon+samp(1)-1;\n %position.P(intervalo(i))= position0.P(intervalo(i));\n %position.Pprima(intervalo(i))=position0.Pprima(intervalo(i));\n position.direccionPonopt(intervalo(i),:)=V(end,:)';\n position.Ptipoon(intervalo(i))=position0.Ptipo(intervalo(i));\n else\n weight2=ones(size(pontos2on,1),1);\n [a,v] = optimline(pontos2on, weight2,OPT);\n A2=[A2;a]; %#ok\n V2=[V2;v]; %#ok\n newleadbeat2on = [];\n if ~isempty(w3)\n newleadbeat2on(interval,3)=(w1(interval,3).*v(1)+w2(interval,3)*v(2)+w3(interval,3)*v(3))./norm(v);%#ok\n newleadbeat2on(interval,4)=(w1(interval,4).*v(1)+w2(interval,4)*v(2)+w3(interval,4)*v(3))./norm(v);%#ok\n newleadbeat2on(interval,5)=(w1(interval,5).*v(1)+w2(interval,5)*v(2)+w3(interval,5)*v(3))./norm(v);%#ok\n % signew2on(interval)=(sig(interval,1).*v(1)+sig(interval,2)*v(2)+sig(interval,3)*v(3))./norm(v);\n else\n newleadbeat2on(interval,3)=(w1(interval,3).*v(1)+w2(timenew(i):timenew(i+1),3)*v(2))./norm(v);%#ok\n newleadbeat2on(interval,4)=(w1(interval,4).*v(1)+w2(timenew(i):timenew(i+1),4)*v(2))./norm(v);%#ok\n newleadbeat2on(interval,5)=(w1(interval,5).*v(1)+w2(timenew(i):timenew(i+1),5)*v(2))./norm(v);%#ok\n %signew2on(interval)=(sig(timenew(i):timenew(i+1),1).*v(1)+sig(timenew(i):timenew(i+1),2)*v(2))./norm(v);\n end\n \n if i>1,\n [pos2,picon2,picoff2]= pwavef(heasig,samp,timenew([i i]),pos,newleadbeat2on,[intervalo(i) intervalo(i)],ultimo_anot,messages); %#ok\n else\n [pos2,picon2,picoff2]= pwavef(heasig,samp,timenew(i),pos,newleadbeat2on,[intervalo(i) intervalo(i)] ,ultimo_anot,messages); %#ok\n end\n piconall=[picon picon2];\n if isnan(picon2)\n amppiconall=[abs(newleadbeat(picon,scale)) NaN];\n else\n amppiconall=[abs(newleadbeat(picon,scale)) abs(newleadbeat2on(picon2,scale))];\n end\n if (amppiconall(end)messages.setup.wavedet.Pconvergence_crit) && (amppiconall(end)>amppiconall(end-1))\n position.contadorPon(intervalo(i))=position.contadorPon(intervalo(i))+1;\n begaux=max([(position0.Pon(intervalo(i))-samp(1)+1-round(messages.setup.wavedet.P_CSE_tol*messages.setup.wavedet.freq)) 1]);\n if ~isempty(w3)\n pontosnewon=[w1( begaux:piconall(end),scale) w2( begaux:piconall(end),scale) w3( begaux:piconall(end),scale)];\n else\n pontosnewon=[w1(begaux:piconall(end),scale) w2( begaux:piconall(end),scale)];\n end\n if size(pontosnewon,1)<=1 % unable to do another step: empty search window\n posnewon.Pon(intervalo(i))=newPon(end-1); % previous step\n posnewon.Pscale(intervalo(i))=pos2.Pscale(intervalo(i));\n posnewon.Ptipo(intervalo(i))=pos2.Ptipo(intervalo(i));\n position.contadorPon(intervalo(i))=position.contadorPon(intervalo(i))-1;\n piconall=[piconall NaN]; %#ok\n amppiconall=[amppiconall NaN]; %#ok\n else\n weight2=ones(size(pontosnewon,1),1);\n [a,v] = optimline(pontosnewon, weight2,OPT);\n A2=[A2;a]; %#ok\n V2=[V2;v]; %#ok\n newleadbeatnewon = [];\n if ~isempty(w3)\n % newleadbeatnewon=NaN*ones(interval(end),5);\n newleadbeatnewon(interval,3)=(w1(interval,3).*v(1)+w2(interval,3)*v(2)+w3(interval,3)*v(3))./norm(v);%#ok\n newleadbeatnewon(interval,4)=(w1(interval,4).*v(1)+w2(interval,4)*v(2)+w3(interval,4)*v(3))./norm(v);%#ok\n newleadbeatnewon(interval,5)=(w1(interval,5).*v(1)+w2(interval,5)*v(2)+w3(interval,5)*v(3))./norm(v);%#ok\n %signewon(interval)=(sig(interval,1).*v(1)+sig(interval,2)*v(2)+sig(interval,3)*v(3))./norm(v);\n else\n % newleadbeatnewon=NaN*ones(interval(end),5);\n newleadbeatnewon(interval,3)=(w1(interval,3).*v(1)+w2(timenew(i):timenew(i+1),3)*v(2))./norm(v);%#ok\n newleadbeatnewon(interval,4)=(w1(interval,4).*v(1)+w2(timenew(i):timenew(i+1),4)*v(2))./norm(v);%#ok\n newleadbeatnewon(interval,5)=(w1(interval,5).*v(1)+w2(timenew(i):timenew(i+1),5)*v(2))./norm(v);%#ok\n %signewon(interval)=(sig(timenew(i):timenew(i+1),1).*v(1)+sig(timenew(i):timenew(i+1),2)*v(2))./norm(v);\n end\n if i>1,\n [posnewon,piconnew,picoffnew]= pwavef(heasig,samp,timenew([i i]),pos,newleadbeatnewon,[intervalo(i) intervalo(i)],ultimo_anot,messages); %#ok\n else\n [posnewon,piconnew,picoffnew]= pwavef(heasig,samp,timenew(i),pos,newleadbeatnewon,[intervalo(i) intervalo(i)] ,ultimo_anot,messages); %#ok\n end\n newPon=[newPon posnewon.Pon(intervalo(i))]; %#ok\n if isnan(piconnew)\n amppiconall=[amppiconall NaN]; %#ok\n else\n amppiconall=[amppiconall abs(newleadbeatnewon(piconnew,scale))]; %#ok\n end\n piconall=[piconall piconnew]; %#ok\n \n if isnan(posnewon.Pon(intervalo(i))) || (amppiconall(end)1\n end %while\n position.PscalePon(intervalo(i))=posnewon.Pscale(intervalo(i));\n position.Pon(intervalo(i))=posnewon.Pon(intervalo(i));\n position.Ptipoon(intervalo(i))=posnewon.Ptipo(intervalo(i));\n end % more steps\n end %size(pontosnewon,1)>1\n else % isnan(picon)\n position.Ptipoon(intervalo(i))=NaN;\n position.Ppicon(intervalo(i))=NaN;\n position.PscalePon(intervalo(i))=NaN;\n position.Pon(intervalo(i))=NaN;\n recursioncount.Pon(intervalo(i))=NaN;\n position.contadorPon(intervalo(i))=NaN; %Rute\n end\n %%%%%% P wave onset\n %%%%% P wave end\n if ~isnan(picoff)\n \n endaux=min([(position0.Poff(intervalo(i))-samp(1)+1+round(messages.setup.wavedet.P_CSE_tol*messages.setup.wavedet.freq)) length(w1)]);\n if ~isempty(w3)\n pontos2off=[w1(picoff:endaux,scale) w2(picoff:endaux,scale) w3(picoff:endaux,scale)];\n else\n pontos2off=[w1(picoff:endaux,scale) w2(picoff:endaux,scale)];\n end\n if size(pontos2off,1)<=1 % unable to do another step: empty search window\n position.contadorPoff(intervalo(i))=-1;\n position.PscalePoff(intervalo(i))=position0.Pscale(intervalo(i));\n position.Poff(intervalo(i))=position0.Poff(intervalo(i));\n position.Ppicoff=picoff+samp(1)-1;\n %position.P(intervalo(i))= position0.P(intervalo(i));\n %position.Pprima(intervalo(i))=position0.Pprima(intervalo(i));\n position.direccionPoffopt(:,intervalo(i))=V(end,:);\n position.Ptipooff(intervalo(i))=position0.Ptipo(intervalo(i));\n else\n weight2=ones(size(pontos2off,1),1);\n [a,v] = optimline(pontos2off, weight2,OPT);\n A2=[A2;a]; %#ok\n V2=[V2;v]; %#ok\n newleadbeat2off = [];\n if ~isempty(w3)\n % newleadbeat2off=NaN*ones(interval(end),5);\n newleadbeat2off(interval,3)=(w1(interval,3).*v(1)+w2(interval,3)*v(2)+w3(interval,3)*v(3))./norm(v);%#ok\n newleadbeat2off(interval,4)=(w1(interval,4).*v(1)+w2(interval,4)*v(2)+w3(interval,4)*v(3))./norm(v);%#ok\n newleadbeat2off(interval,5)=(w1(interval,5).*v(1)+w2(interval,5)*v(2)+w3(interval,5)*v(3))./norm(v);%#ok\n %signew2off(interval)=(sig(interval,1).*v(1)+sig(interval,2)*v(2)+sig(interval,3)*v(3))./norm(v);\n else\n % newleadbeat2off=NaN*ones(interval(end),5);\n newleadbeat2off(interval,3)=(w1(interval,3).*v(1)+w2(timenew(i):timenew(i+1),3)*v(2))./norm(v);%#ok\n newleadbeat2off(interval,4)=(w1(interval,4).*v(1)+w2(timenew(i):timenew(i+1),4)*v(2))./norm(v);%#ok\n newleadbeat2off(interval,5)=(w1(interval,5).*v(1)+w2(timenew(i):timenew(i+1),5)*v(2))./norm(v);%#ok\n %signew2off(interval)=(sig(timenew(i):timenew(i+1),1).*v(1)+sig(timenew(i):timenew(i+1),2)*v(2))./norm(v);\n end\n \n if i>1,\n [pos2off,picon2off,picoff2]= pwavef(heasig,samp,timenew([i i]),pos,newleadbeat2off,[intervalo(i) intervalo(i)],ultimo_anot,messages); %#ok\n else\n [pos2off,picon2off,picoff2]= pwavef(heasig,samp,timenew(i),pos,newleadbeat2off,[intervalo(i) intervalo(i)] ,ultimo_anot,messages); %#ok\n end\n \n picoffall=[picoff picoff2];\n if isnan(picoff2)\n amppicoffall=[abs(newleadbeat(picoff,scale)) NaN];\n else\n amppicoffall=[abs(newleadbeat(picoff,scale)) abs(newleadbeat2off(picoff2,scale))];\n end\n if (amppicoffall(end)messages.setup.wavedet.Pconvergence_crit ) && (amppicoffall(end)>amppicoffall(end-1))\n position.contadorPoff(intervalo(i))=position.contadorPoff(intervalo(i))+1;\n endaux=min([(position0.Poff(intervalo(i))-samp(1)+1+round(messages.setup.wavedet.P_CSE_tol*messages.setup.wavedet.freq)) length(w1)]);\n if ~isempty(w3)\n pontosnewoff=[w1(picoffall(end):endaux,scale) w2(picoffall(end):endaux,scale) w3(picoffall(end):endaux,scale)];\n else\n pontosnewoff=[w1(picoffall(end):endaux,scale) w2(picoffall(end):endaux,scale)];\n end\n if size(pontosnewoff,1)<=1 % unable to do another step: empty search window\n posnewoff.Poff(intervalo(i))=newPoff(end-1); % previous step\n posnewoff.Pscale(intervalo(i))=pos2off.Pscale(intervalo(i));\n posnewoff.Ptipo(intervalo(i))=pos2off.Ptipo(intervalo(i));\n %posnew.P=pos2off.P;\n %posnew.Pprima=pos2off.Pprima;\n position.contadorPoff(intervalo(i))=position.contadorPoff(intervalo(i))-1;\n picoffall=[picoffall NaN]; %#ok\n amppicoffall=[amppicoffall NaN]; %#ok\n else\n weight2=ones(size(pontosnewoff,1),1);\n [a,v] = optimline(pontosnewoff, weight2,OPT);\n A2=[A2;a]; %#ok\n V2=[V2;v]; %#ok\n newleadbeatnewoff = [];\n if ~isempty(w3)\n %newleadbeatnewoff=NaN*ones(interval(end),5);\n newleadbeatnewoff(interval,3)=(w1(interval,3).*v(1)+w2(interval,3)*v(2)+w3(interval,3)*v(3))./norm(v);%#ok\n newleadbeatnewoff(interval,4)=(w1(interval,4).*v(1)+w2(interval,4)*v(2)+w3(interval,4)*v(3))./norm(v);%#ok\n newleadbeatnewoff(interval,5)=(w1(interval,5).*v(1)+w2(interval,5)*v(2)+w3(interval,5)*v(3))./norm(v);%#ok\n %signewoff(interval)=(sig(interval,1).*v(1)+sig(interval,2)*v(2)+sig(interval,3)*v(3))./norm(v);\n else\n %newleadbeatnewoff=NaN*ones(interval(end),5);\n newleadbeatnewoff(interval,3)=(w1(interval,3).*v(1)+w2(timenew(i):timenew(i+1),3)*v(2))./norm(v);%#ok\n newleadbeatnewoff(interval,4)=(w1(interval,4).*v(1)+w2(timenew(i):timenew(i+1),4)*v(2))./norm(v);%#ok\n newleadbeatnewoff(interval,5)=(w1(interval,5).*v(1)+w2(timenew(i):timenew(i+1),5)*v(2))./norm(v);%#ok\n %signewoff(interval)=(sig(timenew(i):timenew(i+1),1).*v(1)+sig(timenew(i):timenew(i+1),2)*v(2))./norm(v);\n end\n if i>1,\n [posnewoff,piconnew,picoffnew]= pwavef(heasig,samp,timenew([i i]),pos,newleadbeatnewoff,[intervalo(i) intervalo(i)],ultimo_anot,messages); %#ok\n else\n [posnewoff,piconnew,picoffnew]= pwavef(heasig,samp,timenew(i),pos,newleadbeatnewoff,[intervalo(i) intervalo(i)] ,ultimo_anot,messages); %#ok\n end\n newPoff=[newPoff posnewoff.Poff(intervalo(i))]; %#ok\n if isnan(picoffnew)\n amppicoffall=[amppicoffall NaN]; %#ok\n else\n amppicoffall=[amppicoffall abs(newleadbeatnewoff(picoffnew,scale))]; %#ok\n end\n picoffall=[picoffall picoffnew]; %#ok\n \n \n if isnan(posnewoff.Poff(intervalo(i))) || (amppicoffall(end)1\n end %while\n position.PscalePoff(intervalo(i))=posnewoff.Pscale(intervalo(i));\n position.Poff(intervalo(i))=posnewoff.Poff(intervalo(i));\n position.Ptipooff(intervalo(i))=posnewoff.Ptipo(intervalo(i));\n % position.P(intervalo(i))= posnewoff.P(intervalo(i));\n % position.Pprima(intervalo(i))=posnewoff.Pprima(intervalo(i));\n end % more steps\n end %size(pontosnewoff,1)>1\n else % isnan(picoff)\n position.PscalePoff(intervalo(i))=NaN;\n position.Ppicoff(intervalo(i))=NaN;\n position.Poff(intervalo(i))=NaN;\n position.Ptipooff(intervalo(i))=NaN;\n %position.P(intervalo(i))=NaN;\n %position.Pprima(intervalo(i))=NaN;\n recursioncount.Poff(intervalo(i))=NaN;\n position.contadorPoff(intervalo(i))=NaN; %Rute\n end\n %%%%%% P wave end\n \n %P peak\n if ~isnan(position.Ppicon(intervalo(i))) && ~isnan(position.Ppicoff(intervalo(i))) && position.Ppicon(intervalo(i)) % main P peak\n position.P(intervalo(i))=m2+position.Ppicon(intervalo(i));\n else\n position.P(intervalo(i))=position0.P(intervalo(i));\n end\n %%\n %writennot protection: at least one sample between peak and border\n if (position.P(intervalo(i))-position.Pon(intervalo(i)))<1\n position.P(intervalo(i))=NaN;\n end\n if (position.Poff(intervalo(i))-position.P(intervalo(i)))<1\n position.P(intervalo(i))=NaN;\n end\n clear pos pos2 pontos pontos2on pontos2off posnew pos2off posnewoff\n end\nend % for\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/delineateP3D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.32423541204073586, "lm_q1q2_score": 0.18600685481923762}} {"text": "function obj = Jacob_pTop_func_new(in1,in2,in3,in4,in5)\ncoef_f0_q_sym1 = in1(:,1);\ncoef_f0_q_sym2 = in1(:,2);\ncoef_f0_q_sym3 = in1(:,3);\ncoef_f0_q_sym4 = in1(:,4);\ncoef_f0_q_sym5 = in1(:,5);\ncoef_f0_q_sym6 = in1(:,6);\ncoef_f0_q_sym7 = in1(:,7);\ncoef_f0_q_sym8 = in1(:,8);\ncoef_f0_q_sym9 = in1(:,9);\ncoef_f0_q_sym10 = in1(:,10);\ncoef_f0_q_sym11 = in1(:,11);\ncoef_f1_q_sym1 = in2(:,1);\ncoef_f0_q_sym12 = in1(:,12);\ncoef_f1_q_sym2 = in2(:,2);\ncoef_f0_q_sym13 = in1(:,13);\ncoef_f1_q_sym3 = in2(:,3);\ncoef_f0_q_sym14 = in1(:,14);\ncoef_f1_q_sym4 = in2(:,4);\ncoef_f0_q_sym15 = in1(:,15);\ncoef_f1_q_sym5 = in2(:,5);\ncoef_f0_q_sym16 = in1(:,16);\ncoef_f1_q_sym6 = in2(:,6);\ncoef_f0_q_sym17 = in1(:,17);\ncoef_f1_q_sym7 = in2(:,7);\ncoef_f0_q_sym18 = in1(:,18);\ncoef_f1_q_sym8 = in2(:,8);\ncoef_f0_q_sym19 = in1(:,19);\ncoef_f1_q_sym9 = in2(:,9);\ncoef_f0_q_sym20 = in1(:,20);\ncoef_f0_q_sym21 = in1(:,21);\ncoef_f2_q_sym1 = in3(:,1);\ncoef_f0_q_sym22 = in1(:,22);\ncoef_f2_q_sym2 = in3(:,2);\ncoef_f0_q_sym23 = in1(:,23);\ncoef_f2_q_sym3 = in3(:,3);\ncoef_f0_q_sym24 = in1(:,24);\ncoef_f2_q_sym4 = in3(:,4);\ncoef_f2_q_sym5 = in3(:,5);\ncoef_f2_q_sym6 = in3(:,6);\ncoef_f2_q_sym7 = in3(:,7);\ncoef_f2_q_sym8 = in3(:,8);\ncoef_f2_q_sym9 = in3(:,9);\ncoef_f3_q_sym1 = in4(:,1);\ncoef_f3_q_sym2 = in4(:,2);\ncoef_f3_q_sym3 = in4(:,3);\ncoef_f3_q_sym4 = in4(:,4);\ncoef_f3_q_sym5 = in4(:,5);\ncoef_f3_q_sym6 = in4(:,6);\ncoef_f3_q_sym7 = in4(:,7);\ncoef_f3_q_sym8 = in4(:,8);\ncoef_f3_q_sym9 = in4(:,9);\ncoef_f1_q_sym10 = in2(:,10);\ncoef_f1_q_sym11 = in2(:,11);\ncoef_f1_q_sym12 = in2(:,12);\ncoef_f1_q_sym13 = in2(:,13);\ncoef_f1_q_sym14 = in2(:,14);\ncoef_f1_q_sym15 = in2(:,15);\ncoef_f1_q_sym16 = in2(:,16);\ncoef_f1_q_sym17 = in2(:,17);\ncoef_f1_q_sym18 = in2(:,18);\ncoef_f1_q_sym19 = in2(:,19);\ncoef_f1_q_sym20 = in2(:,20);\ncoef_f1_q_sym21 = in2(:,21);\ncoef_f1_q_sym22 = in2(:,22);\ncoef_f1_q_sym23 = in2(:,23);\ncoef_f1_q_sym24 = in2(:,24);\ncoef_f2_q_sym10 = in3(:,10);\ncoef_f2_q_sym11 = in3(:,11);\ncoef_f2_q_sym12 = in3(:,12);\ncoef_f2_q_sym13 = in3(:,13);\ncoef_f2_q_sym14 = in3(:,14);\ncoef_f2_q_sym15 = in3(:,15);\ncoef_f2_q_sym16 = in3(:,16);\ncoef_f2_q_sym17 = in3(:,17);\ncoef_f2_q_sym18 = in3(:,18);\ncoef_f2_q_sym19 = in3(:,19);\ncoef_f2_q_sym20 = in3(:,20);\ncoef_f2_q_sym21 = in3(:,21);\ncoef_f2_q_sym22 = in3(:,22);\ncoef_f2_q_sym23 = in3(:,23);\ncoef_f2_q_sym24 = in3(:,24);\ncoef_f3_q_sym10 = in4(:,10);\ncoef_f3_q_sym11 = in4(:,11);\ncoef_f3_q_sym12 = in4(:,12);\ncoef_f3_q_sym13 = in4(:,13);\ncoef_f3_q_sym14 = in4(:,14);\ncoef_f3_q_sym15 = in4(:,15);\ncoef_f3_q_sym16 = in4(:,16);\ncoef_f3_q_sym17 = in4(:,17);\ncoef_f3_q_sym18 = in4(:,18);\ncoef_f3_q_sym19 = in4(:,19);\ncoef_f3_q_sym20 = in4(:,20);\ncoef_f3_q_sym21 = in4(:,21);\ncoef_f3_q_sym22 = in4(:,22);\ncoef_f3_q_sym23 = in4(:,23);\ncoef_f3_q_sym24 = in4(:,24);\nq0 = in5(1,:);\nq1 = in5(2,:);\nq2 = in5(3,:);\nq3 = in5(4,:);\nt2 = coef_f0_q_sym11.*q0;\nt3 = coef_f0_q_sym18.*q1;\nt4 = coef_f0_q_sym22.*q2;\nt5 = coef_f0_q_sym24.*q3;\nt6 = q0.^2;\nt7 = q0.^3;\nt8 = q1.^2;\nt9 = q1.^3;\nt10 = q2.^2;\nt11 = q2.^3;\nt12 = q3.^2;\nt13 = q3.^3;\nt24 = coef_f0_q_sym6.*q0.*q1.*q2.*2.0;\nt25 = coef_f0_q_sym7.*q0.*q1.*q3.*2.0;\nt26 = coef_f0_q_sym9.*q0.*q2.*q3.*2.0;\nt27 = coef_f0_q_sym16.*q1.*q2.*q3.*2.0;\nt14 = coef_f0_q_sym1.*t7;\nt15 = coef_f0_q_sym12.*t9;\nt16 = coef_f0_q_sym19.*t11;\nt17 = coef_f0_q_sym23.*t13;\nt18 = coef_f0_q_sym2.*q1.*t6;\nt19 = coef_f0_q_sym3.*q2.*t6;\nt20 = coef_f0_q_sym5.*q0.*t8;\nt21 = coef_f0_q_sym4.*q3.*t6;\nt22 = coef_f0_q_sym8.*q0.*t10;\nt23 = coef_f0_q_sym10.*q0.*t12;\nobj = reshape([coef_f0_q_sym11.*q1-coef_f1_q_sym11.*q0.*2.0-coef_f1_q_sym18.*q1-coef_f1_q_sym22.*q2-coef_f1_q_sym24.*q3+coef_f0_q_sym5.*t9-coef_f1_q_sym1.*t7.*4.0-coef_f1_q_sym12.*t9-coef_f1_q_sym19.*t11-coef_f1_q_sym23.*t13+coef_f0_q_sym1.*q1.*t6.*3.0+coef_f0_q_sym2.*q0.*t8.*2.0+coef_f0_q_sym6.*q2.*t8+coef_f0_q_sym7.*q3.*t8+coef_f0_q_sym8.*q1.*t10-coef_f1_q_sym2.*q1.*t6.*3.0-coef_f1_q_sym3.*q2.*t6.*3.0+coef_f0_q_sym10.*q1.*t12-coef_f1_q_sym4.*q3.*t6.*3.0-coef_f1_q_sym5.*q0.*t8.*2.0-coef_f1_q_sym8.*q0.*t10.*2.0-coef_f1_q_sym10.*q0.*t12.*2.0-coef_f1_q_sym13.*q2.*t8-coef_f1_q_sym14.*q3.*t8-coef_f1_q_sym15.*q1.*t10-coef_f1_q_sym17.*q1.*t12-coef_f1_q_sym20.*q3.*t10-coef_f1_q_sym21.*q2.*t12+coef_f0_q_sym3.*q0.*q1.*q2.*2.0+coef_f0_q_sym4.*q0.*q1.*q3.*2.0+coef_f0_q_sym9.*q1.*q2.*q3-coef_f1_q_sym6.*q0.*q1.*q2.*2.0-coef_f1_q_sym7.*q0.*q1.*q3.*2.0-coef_f1_q_sym9.*q0.*q2.*q3.*2.0-coef_f1_q_sym16.*q1.*q2.*q3,coef_f0_q_sym11.*q2-coef_f2_q_sym11.*q0.*2.0-coef_f2_q_sym18.*q1-coef_f2_q_sym22.*q2-coef_f2_q_sym24.*q3+coef_f0_q_sym8.*t11-coef_f2_q_sym1.*t7.*4.0-coef_f2_q_sym12.*t9-coef_f2_q_sym19.*t11-coef_f2_q_sym23.*t13+coef_f0_q_sym1.*q2.*t6.*3.0+coef_f0_q_sym3.*q0.*t10.*2.0+coef_f0_q_sym5.*q2.*t8+coef_f0_q_sym6.*q1.*t10+coef_f0_q_sym9.*q3.*t10+coef_f0_q_sym10.*q2.*t12-coef_f2_q_sym2.*q1.*t6.*3.0-coef_f2_q_sym3.*q2.*t6.*3.0-coef_f2_q_sym4.*q3.*t6.*3.0-coef_f2_q_sym5.*q0.*t8.*2.0-coef_f2_q_sym8.*q0.*t10.*2.0-coef_f2_q_sym10.*q0.*t12.*2.0-coef_f2_q_sym13.*q2.*t8-coef_f2_q_sym14.*q3.*t8-coef_f2_q_sym15.*q1.*t10-coef_f2_q_sym17.*q1.*t12-coef_f2_q_sym20.*q3.*t10-coef_f2_q_sym21.*q2.*t12+coef_f0_q_sym2.*q0.*q1.*q2.*2.0+coef_f0_q_sym4.*q0.*q2.*q3.*2.0+coef_f0_q_sym7.*q1.*q2.*q3-coef_f2_q_sym6.*q0.*q1.*q2.*2.0-coef_f2_q_sym7.*q0.*q1.*q3.*2.0-coef_f2_q_sym9.*q0.*q2.*q3.*2.0-coef_f2_q_sym16.*q1.*q2.*q3,coef_f0_q_sym11.*q3-coef_f3_q_sym11.*q0.*2.0-coef_f3_q_sym18.*q1-coef_f3_q_sym22.*q2-coef_f3_q_sym24.*q3+coef_f0_q_sym10.*t13-coef_f3_q_sym1.*t7.*4.0-coef_f3_q_sym12.*t9-coef_f3_q_sym19.*t11-coef_f3_q_sym23.*t13+coef_f0_q_sym1.*q3.*t6.*3.0+coef_f0_q_sym4.*q0.*t12.*2.0+coef_f0_q_sym5.*q3.*t8+coef_f0_q_sym7.*q1.*t12+coef_f0_q_sym8.*q3.*t10+coef_f0_q_sym9.*q2.*t12-coef_f3_q_sym2.*q1.*t6.*3.0-coef_f3_q_sym3.*q2.*t6.*3.0-coef_f3_q_sym4.*q3.*t6.*3.0-coef_f3_q_sym5.*q0.*t8.*2.0-coef_f3_q_sym8.*q0.*t10.*2.0-coef_f3_q_sym10.*q0.*t12.*2.0-coef_f3_q_sym13.*q2.*t8-coef_f3_q_sym14.*q3.*t8-coef_f3_q_sym15.*q1.*t10-coef_f3_q_sym17.*q1.*t12-coef_f3_q_sym20.*q3.*t10-coef_f3_q_sym21.*q2.*t12+coef_f0_q_sym2.*q0.*q1.*q3.*2.0+coef_f0_q_sym3.*q0.*q2.*q3.*2.0+coef_f0_q_sym6.*q1.*q2.*q3-coef_f3_q_sym6.*q0.*q1.*q2.*2.0-coef_f3_q_sym7.*q0.*q1.*q3.*2.0-coef_f3_q_sym9.*q0.*q2.*q3.*2.0-coef_f3_q_sym16.*q1.*q2.*q3,q0.*2.0,t2+t3.*2.0+t4+t5+t14+t15.*4.0+t16+t17+t18.*2.0+t19+t20.*3.0+t21+t22+t23+t24+t25+t27-coef_f1_q_sym18.*q0-coef_f1_q_sym2.*t7-coef_f1_q_sym5.*q1.*t6.*2.0+coef_f0_q_sym13.*q2.*t8.*3.0-coef_f1_q_sym6.*q2.*t6+coef_f0_q_sym14.*q3.*t8.*3.0+coef_f0_q_sym15.*q1.*t10.*2.0-coef_f1_q_sym7.*q3.*t6+coef_f0_q_sym17.*q1.*t12.*2.0+coef_f0_q_sym20.*q3.*t10+coef_f0_q_sym21.*q2.*t12-coef_f1_q_sym12.*q0.*t8.*3.0-coef_f1_q_sym15.*q0.*t10-coef_f1_q_sym17.*q0.*t12+coef_f0_q_sym9.*q0.*q2.*q3-coef_f1_q_sym13.*q0.*q1.*q2.*2.0-coef_f1_q_sym14.*q0.*q1.*q3.*2.0-coef_f1_q_sym16.*q0.*q2.*q3,coef_f0_q_sym18.*q2-coef_f2_q_sym18.*q0+coef_f0_q_sym15.*t11-coef_f2_q_sym2.*t7+coef_f0_q_sym2.*q2.*t6+coef_f0_q_sym6.*q0.*t10+coef_f0_q_sym12.*q2.*t8.*3.0+coef_f0_q_sym13.*q1.*t10.*2.0+coef_f0_q_sym16.*q3.*t10+coef_f0_q_sym17.*q2.*t12-coef_f2_q_sym5.*q1.*t6.*2.0-coef_f2_q_sym6.*q2.*t6-coef_f2_q_sym7.*q3.*t6-coef_f2_q_sym12.*q0.*t8.*3.0-coef_f2_q_sym15.*q0.*t10-coef_f2_q_sym17.*q0.*t12+coef_f0_q_sym5.*q0.*q1.*q2.*2.0+coef_f0_q_sym7.*q0.*q2.*q3+coef_f0_q_sym14.*q1.*q2.*q3.*2.0-coef_f2_q_sym13.*q0.*q1.*q2.*2.0-coef_f2_q_sym14.*q0.*q1.*q3.*2.0-coef_f2_q_sym16.*q0.*q2.*q3,coef_f0_q_sym18.*q3-coef_f3_q_sym18.*q0+coef_f0_q_sym17.*t13-coef_f3_q_sym2.*t7+coef_f0_q_sym2.*q3.*t6+coef_f0_q_sym7.*q0.*t12+coef_f0_q_sym12.*q3.*t8.*3.0+coef_f0_q_sym14.*q1.*t12.*2.0+coef_f0_q_sym15.*q3.*t10+coef_f0_q_sym16.*q2.*t12-coef_f3_q_sym5.*q1.*t6.*2.0-coef_f3_q_sym6.*q2.*t6-coef_f3_q_sym7.*q3.*t6-coef_f3_q_sym12.*q0.*t8.*3.0-coef_f3_q_sym15.*q0.*t10-coef_f3_q_sym17.*q0.*t12+coef_f0_q_sym5.*q0.*q1.*q3.*2.0+coef_f0_q_sym6.*q0.*q2.*q3+coef_f0_q_sym13.*q1.*q2.*q3.*2.0-coef_f3_q_sym13.*q0.*q1.*q2.*2.0-coef_f3_q_sym14.*q0.*q1.*q3.*2.0-coef_f3_q_sym16.*q0.*q2.*q3,q1.*2.0,coef_f0_q_sym22.*q1-coef_f1_q_sym22.*q0-coef_f1_q_sym3.*t7+coef_f0_q_sym13.*t9+coef_f0_q_sym3.*q1.*t6+coef_f0_q_sym6.*q0.*t8-coef_f1_q_sym6.*q1.*t6+coef_f0_q_sym15.*q2.*t8.*2.0-coef_f1_q_sym8.*q2.*t6.*2.0+coef_f0_q_sym16.*q3.*t8-coef_f1_q_sym9.*q3.*t6+coef_f0_q_sym19.*q1.*t10.*3.0+coef_f0_q_sym21.*q1.*t12-coef_f1_q_sym13.*q0.*t8-coef_f1_q_sym19.*q0.*t10.*3.0-coef_f1_q_sym21.*q0.*t12+coef_f0_q_sym8.*q0.*q1.*q2.*2.0+coef_f0_q_sym9.*q0.*q1.*q3+coef_f0_q_sym20.*q1.*q2.*q3.*2.0-coef_f1_q_sym15.*q0.*q1.*q2.*2.0-coef_f1_q_sym16.*q0.*q1.*q3-coef_f1_q_sym20.*q0.*q2.*q3.*2.0,t2+t3+t4.*2.0+t5+t14+t15+t16.*4.0+t17+t18+t19.*2.0+t20+t21+t22.*3.0+t23+t24+t26+t27-coef_f2_q_sym22.*q0-coef_f2_q_sym3.*t7+coef_f0_q_sym13.*q2.*t8.*2.0+coef_f0_q_sym14.*q3.*t8+coef_f0_q_sym15.*q1.*t10.*3.0+coef_f0_q_sym17.*q1.*t12+coef_f0_q_sym20.*q3.*t10.*3.0-coef_f2_q_sym6.*q1.*t6+coef_f0_q_sym21.*q2.*t12.*2.0-coef_f2_q_sym8.*q2.*t6.*2.0-coef_f2_q_sym9.*q3.*t6-coef_f2_q_sym13.*q0.*t8-coef_f2_q_sym19.*q0.*t10.*3.0-coef_f2_q_sym21.*q0.*t12+coef_f0_q_sym7.*q0.*q1.*q3-coef_f2_q_sym15.*q0.*q1.*q2.*2.0-coef_f2_q_sym16.*q0.*q1.*q3-coef_f2_q_sym20.*q0.*q2.*q3.*2.0,coef_f0_q_sym22.*q3-coef_f3_q_sym22.*q0+coef_f0_q_sym21.*t13-coef_f3_q_sym3.*t7+coef_f0_q_sym3.*q3.*t6+coef_f0_q_sym9.*q0.*t12+coef_f0_q_sym13.*q3.*t8+coef_f0_q_sym16.*q1.*t12+coef_f0_q_sym19.*q3.*t10.*3.0+coef_f0_q_sym20.*q2.*t12.*2.0-coef_f3_q_sym6.*q1.*t6-coef_f3_q_sym8.*q2.*t6.*2.0-coef_f3_q_sym9.*q3.*t6-coef_f3_q_sym13.*q0.*t8-coef_f3_q_sym19.*q0.*t10.*3.0-coef_f3_q_sym21.*q0.*t12+coef_f0_q_sym6.*q0.*q1.*q3+coef_f0_q_sym8.*q0.*q2.*q3.*2.0+coef_f0_q_sym15.*q1.*q2.*q3.*2.0-coef_f3_q_sym15.*q0.*q1.*q2.*2.0-coef_f3_q_sym16.*q0.*q1.*q3-coef_f3_q_sym20.*q0.*q2.*q3.*2.0,q2.*2.0,coef_f0_q_sym24.*q1-coef_f1_q_sym24.*q0-coef_f1_q_sym4.*t7+coef_f0_q_sym14.*t9+coef_f0_q_sym4.*q1.*t6+coef_f0_q_sym7.*q0.*t8-coef_f1_q_sym7.*q1.*t6+coef_f0_q_sym16.*q2.*t8-coef_f1_q_sym9.*q2.*t6+coef_f0_q_sym17.*q3.*t8.*2.0+coef_f0_q_sym20.*q1.*t10+coef_f0_q_sym23.*q1.*t12.*3.0-coef_f1_q_sym10.*q3.*t6.*2.0-coef_f1_q_sym14.*q0.*t8-coef_f1_q_sym20.*q0.*t10-coef_f1_q_sym23.*q0.*t12.*3.0+coef_f0_q_sym9.*q0.*q1.*q2+coef_f0_q_sym10.*q0.*q1.*q3.*2.0+coef_f0_q_sym21.*q1.*q2.*q3.*2.0-coef_f1_q_sym16.*q0.*q1.*q2-coef_f1_q_sym17.*q0.*q1.*q3.*2.0-coef_f1_q_sym21.*q0.*q2.*q3.*2.0,coef_f0_q_sym24.*q2-coef_f2_q_sym24.*q0+coef_f0_q_sym20.*t11-coef_f2_q_sym4.*t7+coef_f0_q_sym4.*q2.*t6+coef_f0_q_sym9.*q0.*t10+coef_f0_q_sym14.*q2.*t8+coef_f0_q_sym16.*q1.*t10+coef_f0_q_sym21.*q3.*t10.*2.0-coef_f2_q_sym7.*q1.*t6+coef_f0_q_sym23.*q2.*t12.*3.0-coef_f2_q_sym9.*q2.*t6-coef_f2_q_sym10.*q3.*t6.*2.0-coef_f2_q_sym14.*q0.*t8-coef_f2_q_sym20.*q0.*t10-coef_f2_q_sym23.*q0.*t12.*3.0+coef_f0_q_sym7.*q0.*q1.*q2+coef_f0_q_sym10.*q0.*q2.*q3.*2.0+coef_f0_q_sym17.*q1.*q2.*q3.*2.0-coef_f2_q_sym16.*q0.*q1.*q2-coef_f2_q_sym17.*q0.*q1.*q3.*2.0-coef_f2_q_sym21.*q0.*q2.*q3.*2.0,t2+t3+t4+t5.*2.0+t14+t15+t16+t17.*4.0+t18+t19+t20+t21.*2.0+t22+t23.*3.0+t25+t26+t27-coef_f3_q_sym24.*q0-coef_f3_q_sym4.*t7+coef_f0_q_sym13.*q2.*t8+coef_f0_q_sym14.*q3.*t8.*2.0+coef_f0_q_sym15.*q1.*t10+coef_f0_q_sym17.*q1.*t12.*3.0+coef_f0_q_sym20.*q3.*t10.*2.0+coef_f0_q_sym21.*q2.*t12.*3.0-coef_f3_q_sym7.*q1.*t6-coef_f3_q_sym9.*q2.*t6-coef_f3_q_sym10.*q3.*t6.*2.0-coef_f3_q_sym14.*q0.*t8-coef_f3_q_sym20.*q0.*t10-coef_f3_q_sym23.*q0.*t12.*3.0+coef_f0_q_sym6.*q0.*q1.*q2-coef_f3_q_sym16.*q0.*q1.*q2-coef_f3_q_sym17.*q0.*q1.*q3.*2.0-coef_f3_q_sym21.*q0.*q2.*q3.*2.0,q3.*2.0],[4,4]);\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/Jacob_pTop_func_new.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632979641571, "lm_q2_score": 0.3415824927356586, "lm_q1q2_score": 0.18543259853329738}} {"text": "function [s, cfg] = ft_statfun_actvsblT(cfg, dat, design)\n\n% FT_STATFUN_ACTVSBLT calculates the activation-versus-baseline T-statistic on the\n% biological data (the dependent variable), using the information on the independent\n% variable (ivar) in design.\n%\n% Note that it does not make sense to use this test statistic when baseline\n% correction was performed by subtracting the mean of the baseline period from the\n% whole data (for ERP data) or by dividing by the mean (for TFR data). If baseline\n% correction is desired, you should subtract the full baseline and activation period.\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_actvsblT'\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 first condition, indicated by 1, corresponds to the\n% activation period and the second, indicated by 2, corresponds to the baseline period.\n% cfg.uvar = row number of design that contains the labels of the units-of-observation (subjects or trials)\n% (default=2). The labels are assumed to be integers ranging from 1 to\n% the number of units-of-observation.\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 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\n\n% calculate the number of time samples\nswitch cfg.dimord\n case 'chan_freq_time'\n nchan = cfg.dim(1);\n nfreq = cfg.dim(2);\n ntime = cfg.dim(3);\n [nsmpls,nrepl] = size(dat);\n otherwise\n ft_error('Inappropriate dimord for the statistics function FT_STATFUN_ACTVSBLT.');\nend\n\nsel1 = find(design(cfg.ivar,:)==1);\nsel2 = find(design(cfg.ivar,:)==2);\nn1 = length(sel1);\nn2 = length(sel2);\nif (n1+n2).\n%\n% $Id$\n\nif ~isfield(cfg, 'planaraxial'), cfg.planaraxial = 'yes'; end\nif ~isfield(cfg, 'baseline_axial'), cfg.baseline_axial = 5; end\nif ~isfield(cfg, 'baseline_planar'), cfg.baseline_planar = 0.5; end\n\nNchan = length(grad.label);\n\n% these will hold all the coil positions\nlo_posx = zeros(Nchan,3);\nlo_negx = zeros(Nchan,3);\nlo_posy = zeros(Nchan,3);\nlo_negy = zeros(Nchan,3);\nhi_posx = zeros(Nchan,3);\nhi_negx = zeros(Nchan,3);\nhi_posy = zeros(Nchan,3);\nhi_negy = zeros(Nchan,3);\n\nfor chan=1:Nchan\n % Attach a local coordinate system to this gradiometer:\n % the origin at the location of its bottom coil\n % the z-axis pointing outwards from the head\n % the x-axis pointing horizontal w.r.t. the head\n % the y-axis pointing vertical, i.e. approximately towards the vertex\n this_o = grad.chanpos(chan,:);\n this_z = grad.chanori(chan,:); \n this_z = this_z / norm(this_z);\n this_x = cross([0 0 1], this_z);\n if all(this_x==0)\n this_x = [1 0 0];\n else\n this_x = this_x / norm(this_x);\n end\n this_y = cross(this_z, this_x);\n\n % compute the position of all the 8 coils per channel\n lo_posx(chan,:) = this_o + (cfg.baseline_planar/2) * this_x;\n lo_negx(chan,:) = this_o - (cfg.baseline_planar/2) * this_x;\n lo_posy(chan,:) = this_o + (cfg.baseline_planar/2) * this_y;\n lo_negy(chan,:) = this_o - (cfg.baseline_planar/2) * this_y;\n hi_posx(chan,:) = lo_posx(chan,:) + cfg.baseline_axial * this_z;\n hi_negx(chan,:) = lo_negx(chan,:) + cfg.baseline_axial * this_z;\n hi_posy(chan,:) = lo_posy(chan,:) + cfg.baseline_axial * this_z;\n hi_negy(chan,:) = lo_negy(chan,:) + cfg.baseline_axial * this_z;\nend\n\n% start with an empty planar gradiometer definition\nplanar = [];\n\nif strcmp(cfg.planaraxial, 'yes')\n % combine all the 8 coils into a single sensor\n planar.coilpos = [\n lo_posx\n lo_negx\n lo_posy\n lo_negy\n hi_posx\n hi_negx\n hi_posy\n hi_negy\n ];\n\n % the orientation of all the coils of a single sensor should be the same\n planar.coilori = [\n grad.coilori(1:Nchan,:)\n grad.coilori(1:Nchan,:)\n grad.coilori(1:Nchan,:)\n grad.coilori(1:Nchan,:)\n grad.coilori(1:Nchan,:)\n grad.coilori(1:Nchan,:)\n grad.coilori(1:Nchan,:)\n grad.coilori(1:Nchan,:)\n ];\n\n e = eye(Nchan);\n z = zeros(Nchan);\n\n % the linear combination matrix should be 2*Nchan x 8*Nchan\n planar.tra = [\n e -e z z -e e z z % this is for the horizontal gradients\n z z e -e z z -e e % this is for the vertical gradients\n ];\n\nelse\n % combine only the 4 lower coils into a single sensor\n planar.coilpos = [\n posx\n negx\n posy\n negy\n ];\n\n % the orientation of all the coils of a single gradiometer should be the same\n planar.coilori = [\n grad.coilori(1:Nchan,:)\n grad.coilori(1:Nchan,:)\n grad.coilori(1:Nchan,:)\n grad.coilori(1:Nchan,:)\n ];\n\n e = eye(Nchan);\n z = zeros(Nchan);\n\n % the linear combination matrix should be 2*Nchan x 4*Nchan\n planar.tra = [\n e -e z z % this is for the horizontal gradients\n z z e -e % this is for the vertical gradients\n ];\n\nend\n\nfor chan=1:Nchan\n planar.label{chan } = [grad.label{chan} '_dH'];\n planar.label{chan+Nchan} = [grad.label{chan} '_dV'];\nend\n\nplanar.label = planar.label(:);\nplanar.tra = planar.tra / cfg.baseline_planar;\nplanar.chanpos = [grad.chanpos; grad.chanpos];\nplanar.chanori = [grad.chanori; grad.chanori];\n\ntry\n planar.unit = grad.unit;\nend\n\n% add information about the version of this function to the configuration\ncfg.version.name = mfilename('fullpath');\ncfg.version.id = '$Id$';\n\n% rememember the exact configuration details in the output\nplanar.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/constructplanargrad.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5195213368305399, "lm_q2_score": 0.34864513533394575, "lm_q1q2_score": 0.181128586788156}} {"text": "% 2021 EDIT: This function is now deprecated. The current version of the shaped PRESS \n% simulation is run_simPressShaped.m. The current version employs coherence selection, \n% resulting in a 4x simulation speed increase.\n%\n% run_simPressShaped_fast_phCyc.m\n% Jamie Near, McGill University 2018.\n% \n% USAGE:\n% out=run_simPressShaped_fast_phCyc(spinSys);\n% \n% DESCRIPTION:\n% This script simulates a PRESS experiment with fully shaped refocusing \n% pulses. Phase cycling of refocusing pulses is performed. Furthermore, \n% simulations are run at various locations in space to account for the \n% within-voxel spatial variation of the metabolite signal. Summation \n% across phase cycles and spatial positions is performed. To achieve \n% faster perfomance compared to the original 'run_simPressShaped.m' function,\n% this code uses the method described by Yan Zhang et al. Med Phys 2017;44(8): \n% 4169-78. Some additional acceleration is currently performed using parfor \n% loops in both x and y directions. To enable the use of the MATLAB\n% parallel computing toolbox, initialize the multiple worked nodes using\n% \"matlabpool size X\" where \"X\" is the number of available processing\n% nodes. If the parallel processing toolbox is not available, then replace\n% the \"parfor\" loop with a \"for\" loop.\n% \n% INPUTS:\n% To run this script, there is technically only one input argument:\n% spinSys = spin system to simulate \n%\n% However, the user should also edit the following parameters as \n% desired before running the function:\n% refocWaveform = name of refocusing pulse waveform.\n% refTp = duration of refocusing pulses[ms]\n% Bfield = Magnetic field strength in [T]\n% Npts = number of spectral points\n% sw = spectral width [Hz]\n% Bfield = magnetic field strength [Tesla]\n% lw = linewidth of the output spectrum [Hz]\n% thkX = slice thickness of x refocusing pulse [cm]\n% thkY = slice thickness of y refocusing pulse [cm]\n% fovX = full simulation FOV in the x direction [cm]\n% fovY = full simulation FOV in the y direction [cm]\n% nX = number of spatial grid points to simulate in x-direction\n% nY = number of spatial grid points to simulate in y-direction\n% taus = vector of pulse sequence timings [ms]\n% refPhCyc1 = vector of phase cycling steps for 1st refocusing pulse [degrees]\n% refPhCyc2 = vector of phase cycling steps for 2nd refocusing pulse [degrees]\n%\n% OUTPUTS:\n% out = Simulation results, summed over all space.\n\nfunction out=run_simPressShaped_fast_phCyc(spinSys)\n\n% ************INPUT PARAMETERS**********************************\nrefocWaveform='sampleRefocPulse.pta'; %name of refocusing pulse waveform.\nrefTp=3.5; %duration of refocusing pulses[ms]\nflipAngle=137; %Flip Angle of the refocusing pulses [degrees] (e.g. Use 180 for Siemens PRESS. Use 137 for GE PRESS).\nNpts=2048; %number of spectral points\nsw=2000; %spectral width [Hz]\nBfield=3; %magnetic field strength [Tesla]\nlw=2; %linewidth of the output spectrum [Hz]\nthkX=1.66; %slice thickness of x refocusing pulse [cm]\nthkY=1.66; %slice thickness of y refocusing pulse [cm]\nfovX=2.4; %size of the full simulation Field of View in the x-direction [cm]\nfovY=2.4; %size of the full simulation Field of View in the y-direction [cm]\nnX=32; %Number of grid points to simulate in the x-direction\nnY=32; %Number of grid points to simulate in the y-direction\ntau1=30; %TE1 for first spin echo [ms]\ntau2=105; %TE2 for second spin echo [ms]\nrefPhCyc1=[0,90]; %phase cycling steps for 1st refocusing pulse [degrees]\nrefPhCyc2=[0,90]; %phase cycling steps for 2nd refocusing pulse [degrees]\n% ************END OF INPUT PARAMETERS**********************************\n\n%set up spatial grid\nx=linspace(-fovX/2,fovX/2,nX); %X positions to simulate [cm]\ny=linspace(-fovY/2,fovY/2,nY); %y positions to simulate [cm]\n\n%Load RF waveform\nrefRF=io_loadRFwaveform(refocWaveform,'ref',0);\n\ngamma=42577000; %gyromagnetic ratio\n\n%Load spin systems\nload spinSystems\nsys=eval(['sys' spinSys]);\n\n%Resample refocusing RF pulse from 400 pts to 100 pts to reduce\n%computational workload\nrefRF=rf_resample(refRF,100);\n\nGx=(refRF.tbw/(refTp/1000))/(gamma*thkX/10000); %[G/cm]\nGy=(refRF.tbw/(refTp/1000))/(gamma*thkY/10000); %[G/cm]\n\n%Initialize structures:\nd_temp=cell(length(x),length(refPhCyc1));\nd=cell(length(refPhCyc1));\n\n%loop through space: If you are using the parfor loops below, and you are \n%using an older version of MATLAB (e.g.R2012), don't forget to initialize \n%the parallel processing toolbox workers using 'matlabpool open N' (for N \n%workers, 12 max). I don't think this is necessary for newer version of \n%MATLAB. \n\n%First loop through all x-positions, simulating only the first refocusing\n%pulse. \n%First loop through x direction (first refoc pulse only);\n\n%for X=1:length(x) %Use this if you don't have the MATLAB parallel processing toolbox\nparfor X=1:length(x) %Use this if you have the MATLAB parallel processing toolbox\n for RP1=1:length(refPhCyc1)\n disp(['Executing X-position ' num2str(X) ' of ' num2str(length(x)) ', '...\n 'First Refoc phase cycle ' num2str(RP1) ' of ' num2str(length(refPhCyc1)) '!!!']);\n d_temp{X}{RP1}=sim_press_shaped_fastRef1(Bfield,sys,tau1,tau2,refRF,refTp,x(X),Gx,refPhCyc1(RP1),flipAngle);\n end\nend\n\n%calculate the average density matrix (Doing this inside a separate for \n%loop because I couldn't figure out how to do this inside the parfor loop): \nfor X=1:length(x)\n for RP1=1:length(refPhCyc1)\n d{RP1}=sim_dAdd(d{RP1},d_temp{X}{RP1});\n end\nend\n\n\n% %Initialize structures:\nout_temp=cell(length(y),length(refPhCyc1),length(refPhCyc2));\nout=struct([]);\n\n%Now loop through y direction (second refoc pulse only);\n%for Y=1:length(y) %Use this if you don't have the MATLAB parallel processing toolbox\nparfor Y=1:length(y) %Use this if you do have the MATLAB parallel processing toolbox\n for RP1=1:length(refPhCyc1)\n for RP2=1:length(refPhCyc2)\n disp(['Executing Y-position ' num2str(Y) ' of ' num2str(length(y)) ', '...\n 'First Refoc phase cycle ' num2str(RP1) ' of ' num2str(length(refPhCyc1)) ', '...\n 'Second Refoc phase cycle ' num2str(RP2) ' of ' num2str(length(refPhCyc2)) '!!!']);\n out_temp{Y}{RP1}{RP2}=sim_press_shaped_fastRef2(d{RP1},Npts,sw,Bfield,lw,sys,tau1,tau2,...\n refRF,refTp,y(Y),Gy,refPhCyc2(RP2),flipAngle);\n end\n end\nend\n\n%Now combine the outputs; Again, doing this inside a separate for loop\n%becuase I can't figure out how to do this inside the parfor loop:\nfor Y=1:length(y) \n for RP1=1:length(refPhCyc1)\n for RP2=1:length(refPhCyc2)\n out=op_addScans(out,out_temp{Y}{RP1}{RP2},xor(RP1-1,RP2-1));\n end\n end\nend\n\n%For consistent scaling across different shaped simulations, we need to :\n%1. Scale down by the total number of simulations run (since these were\n% all added together.\nnumSims=(nX*nY*length(refPhCyc1)*length(refPhCyc2));\nout=op_ampScale(out,1/numSims);\n\n%2. Scale by the total size of the simulated region, relative to the size\n% of the voxel.\nvoxRatio=(thkX*thkY)/(fovX*fovY);\nout=op_ampScale(out,1/voxRatio);\n\n\nend\n\n\n\n\n\n\n\n\n%Nested Function #1\nfunction d = sim_press_shaped_fastRef1(Bfield,sys,tau1,tau2,RF,tp,dx,Gx,phCyc1,flipAngle)\n% \n% USAGE:\n% d = sim_press_shaped_fastRef1(n,sw,Bfield,linewidth,sys,tau1,tau2,RF,tp,dx,Gx,phCyc1,flipAngle)\n% \n% DESCRIPTION:\n% This function simulates only the first bit of the PRESS experiment, up to \n% the beginning of the second refocusing pulse. The excitation is\n% simulated as an instantaneous rotation, and the refocusing pulse is\n% simulated as a shaped rotation.\n%\n% This code is designed to be used in highly-accelerated shaped simulations,\n% using the method described by Yan Zhang et al. Med Phys 2017;44(8): \n% 4169-78.\n%\n% This code enables the choice of the phase of the refocusing pulse. This \n% enables phase cycling of the refocusing pulses by repeating simulations \n% with different editing pulse phases, which is necessary to remove phase \n% artefacts from the editing pulses. A four step phase cycling scheme is typically\n% sufficient, where both refocusing pulses are phase cycled by 0 and 90 degrees, and\n% the phase are combined in the following way:\n% \n% signal = ([0 90] - [0 0]) + ([90 0] - [90 90]);\n% \n% where, in [X Y], X is the phase of the first refocusing pulse and Y is\n% the phase of the second refocusing pulse\n% \n% Finally, this code simulates the spectrum at a given point in space (x),\n% given the values of the slice selection gradient (Gx). 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), followed by \n% sim_press_shaped_fastRef2.m, at all points in space (y). \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% phCycl = initial phase of the first refocusing pulse in [degrees];\n% phCycl2 = initial phase of the second refocusing pulse in [degrees];\n% flipAngle = flip angle of refocusing pulses [degrees] (Optional. Default = 180 deg)\n%\n% OUTPUTS:\n% out = simulated spectrum, in FID-A structure format, using PRESS \n% sequence.\n\nif nargin<10\n flipAngle=180;\nend\n \nif tau1 5;\n% Y = Y(:, wh);\n% whos Y\n% [bayes_model, Y] = classify_naive_bayes('setup', Y, Xi);\n% bayes_model = classify_naive_bayes('apparent', Y, bayes_model);\n% bayes_model.apparent.prop_correct, bayes_model.apparent.confusion_mtx\n% bayes_model.xval = classify_naive_bayes('xval', Y, Xi);\n% bayes_model.xval.prop_correct, bayes_model.xval.confusion_mtx\n%\n% :Example 3:\n% create_figure('hist'); hist(bayes_model.pa1_given_t, 100);\n% xval = classify_naive_bayes('xval', Y, Xi, .05, .3);\n%\n% Get results from key regions and run classifier only on those regions:\n% ::\n%\n% cl = classify_naive_bayes('plot', bayes_model, 'lr', .10, {[1 .7 0] [0 0 1]});\n% [studybyroi,studybyset] = Meta_cluster_tools('getdata',cl{1},dat',volInfo);\n% bayes_model_regions = classify_naive_bayes('setup', studybyroi, Xi);\n% bayes_model_regions = classify_naive_bayes('apparent', studybyroi,bayes_model_regions);\n% disp('Apparent confusion')\n% disp(bayes_model_regions.apparent.confusion_mtx)\n%\n% bayes_model_regions.xval = classify_naive_bayes('xval', studybyroi, Xi);\n% disp('Cross-validated confusion')\n% disp(bayes_model_regions.xval.confusion_mtx)\n%\n% fprintf('Proportion correct: Apparent: %3.0f%% Xval: %3.0f%%\\n', 100*bayes_model_regions.apparent.prop_correct, 100*bayes_model_regions.xval.prop_correct);\n% fprintf('Proportion correct by class: \\t'); fprintf('%3.0f%%\\t', 100*bayes_model_regions.xval.prop_correct_by_class);\n% fprintf('\\n');\n\n% sz = cat(1,cl{1}(:).numVox);\n% cl{1}(sz < 10) = [];\n%\n% subcl = subclusters_from_local_max(cl{1}, 10);\n%\n% ..\n% Tor Wager, Sept 2007\n% ..\n\nswitch meth\n\n\n case 'setup'\n Y = full(varargin{1});\n Xi = varargin{2};\n\n activation_cutoff = [];\n selectivity_cutoff = [];\n return_full_ps = 1; % for faster processing if not all fields are needed (i.e., in xval)\n\n if length(varargin) > 2\n\n activation_cutoff = varargin{3};\n selectivity_cutoff = varargin{4};\n\n end\n\n if length(varargin) > 4\n return_full_ps = varargin{5};\n end\n\n k = 1; % default k regularization param\n if length(varargin) > 5\n k = varargin{6};\n end\n \n\n % setup\n [Y, whkeep] = eliminate_empty_Y(Y);\n\n [bayes_model, Y] = classify_naive_bayes_setup(Y, Xi, activation_cutoff, selectivity_cutoff, whkeep, return_full_ps, k);\n\n gam = 1; % default gam prior weighting param\n if length(varargin) > 6\n gam = varargin{7};\n end\n bayes_model.params.gam = gam;\n\n varargout{1} = bayes_model;\n varargout{2} = Y;\n\n\n case 'apparent'\n\n Y = full(varargin{1});\n bayes_model = varargin{2};\n\n bayes_model.true_class = indic2condf(bayes_model.Xi);\n\n % test apparent classification rate\n [bayes_model.apparent.class_est bayes_model.apparent.log_joint bayes_model.apparent.best_log bayes_model.apparent.map bayes_model.apparent.pact_given_task] = ...\n classify_naive_bayes_test(Y, bayes_model);\n\n [bayes_model.apparent.prop_correct, bayes_model.apparent.confusion_mtx, bayes_model.apparent.misclass, ...\n bayes_model.apparent.prop_correct_by_class, bayes_model.apparent.chance, bayes_model.apparent.chance_95_ci] = ...\n classify_naive_bayes_eval(bayes_model.true_class, bayes_model.apparent.class_est);\n\n\n varargout{1} = bayes_model;\n\n\n\n case 'test'\n Y = full(varargin{1});\n bayes_model = varargin{2};\n\n [class_est log_joint best_log map p_obs_act_given_class] = classify_naive_bayes_test(Y, bayes_model);\n\n varargout{1} = class_est;\n varargout{2} = log_joint;\n varargout{3} = best_log;\n varargout{4} = map;\n varargout{5} = p_obs_act_given_class;\n\n case 'eval'\n bayes_model = varargin{1};\n class_est = varargin{2};\n wh_obs = [];\n if length(varargin) > 2, wh_obs = varargin{3}; end\n\n [prop_correct, confusion_mtx, misclass, prop_correct_by_class, chance, chance_95_ci] = classify_naive_bayes_eval(bayes_model, class_est, wh_obs);\n\n varargout{1} = prop_correct;\n varargout{2} = confusion_mtx;\n varargout{3} = misclass;\n varargout{4} = prop_correct_by_class;\n varargout{5} = chance;\n varargout{6} = chance_95_ci;\n\n \n \n case 'abstract'\n %bayes_model = classify_naive_bayes('abstract', Y, thresh, bayes_model, volInfo); \n \n Y = full(varargin{1});\n thresh = varargin{2};\n\n bayes_model = varargin{3};\n volInfo = varargin{4};\n \n reducedY = bayes_meta_feature_abstract(Y, thresh, bayes_model, volInfo);\n \n [bayes_model, Y] = classify_naive_bayes('setup', reducedY, bayes_model.Xi, bayes_model.params.activation_cutoff, bayes_model.params.selectivity_cutoff, 1, bayes_model.params.k);\n \n varargout{1} = bayes_model;\n varargout{2} = Y;\n \n case 'xval'\n Y = full(varargin{1});\n Xi = varargin{2};\n\n activation_cutoff = [];\n selectivity_cutoff = [];\n if length(varargin) > 2\n\n activation_cutoff = varargin{3};\n selectivity_cutoff = varargin{4};\n\n end\n\n k = .5;\n gam = 1;\n if length(varargin) > 4\n\n k = varargin{5};\n gam = varargin{6};\n\n end\n \n if length(varargin) > 6\n volInfo = varargin{7};\n do_feature_abstract = 1;\n end\n\n \n % initialize\n if do_feature_abstract, Yorig = Y; end\n \n [Y, whkeep] = eliminate_empty_Y(Y);\n\n Y = sparse(Y);\n\n nobs = size(Y, 1);\n fprintf('\\nCross-validating %3.0f observations: 00000', nobs);\n\n log_joint = zeros(nobs, size(Xi, 2));\n map = zeros(nobs, size(Xi, 2));\n class_est = zeros(nobs, 1);\n best_log = zeros(nobs, 1);\n\n true_class = indic2condf(Xi);\n\n % Update volinfo for feature abstraction\n% % volInfo.wh_inmask = double(whkeep');\n% % volInfo.n_inmask = sum(whkeep);\n% % volInfo.image_indx(volInfo.image_indx) = whkeep';\n% % volInfo.xyzlist(~whkeep',:) = [];\n\n % run\n for i = 1:nobs\n\n if mod(i,10) == 0, fprintf(1,'\\b\\b\\b\\b\\b%05d',i); end\n\n include_in_training = true(nobs, 1);\n include_in_training(i) = 0;\n\n % setup: does feature-selection as well, if requested; no\n % need to return Y, because ...\n bayes_model = classify_naive_bayes_setup(Y(include_in_training, :), Xi(include_in_training, :), activation_cutoff, selectivity_cutoff, whkeep, 0, k);\n\n bayes_model.params.k = k;\n bayes_model.params.gam = gam;\n\n testdata = Y(i, bayes_model.whkeep_from_notempty);\n \n % feature abstraction step\n if do_feature_abstract\n [reducedY, cl, cluster_indx] = bayes_meta_feature_abstract(Yorig(include_in_training, :), .1, .1, bayes_model, volInfo, 0);\n cluster_indx = cluster_indx(bayes_model.whkeep);\n \n bayes_model = classify_naive_bayes('setup', reducedY, Xi(include_in_training, :), 0, 0, gam, k);\n \n wh_cl = cluster_indx(testdata);\n wh_cl = unique(wh_cl); wh_cl(wh_cl == 0) = [];\n testdata = false(1, bayes_model.nfeatures);\n testdata(wh_cl) = 1;\n\n end\n \n [class_est(i) log_joint(i,:) best_log(i) map(i,:)] = classify_naive_bayes_test(testdata, bayes_model);\n end\n\n fprintf(1, '\\n');\n\n [prop_correct, confusion_mtx, misclass, prop_correct_by_class, chance, chance_95_ci] = classify_naive_bayes_eval(true_class, class_est);\n\n varargout{1} = struct('class_est', class_est, 'log_joint', log_joint, 'best_log', best_log, 'map', map, ...\n 'prop_correct', prop_correct, 'prop_correct_by_class', prop_correct_by_class, 'confusion_mtx', confusion_mtx, ...\n 'misclass', misclass, 'chance', chance, 'chance_95_ci', chance_95_ci, 'params', bayes_model.params);\n\n\n case {'write', 'images', 'write_images'}\n bayes_model = varargin{1};\n Y = varargin{2};\n volInfo = varargin{3};\n conditionnames = varargin{4};\n\n bayes_model = write_images(bayes_model, Y, volInfo, conditionnames);\n varargout{1} = bayes_model;\n\n\n case {'plot', 'output'}\n bayes_model = varargin{1};\n disptype = varargin{2};\n\n cl = display_output(bayes_model, disptype, varargin{3:end});\n\n varargout{1} = cl;\n\n otherwise\n error('Unknown method (invalid first argument).');\nend\n\n\n\n\n\n\nend % end main function\n\n\n\n\n\n\n\n\n\n\nfunction [bayes_model, Y] = classify_naive_bayes_setup(Y, Xi, activation_cutoff, selectivity_cutoff, whkeep, return_full_ps, k)\n\n% Y is data matrix, nobs observations x nfeatures variables\n% in a meta-analysis, e.g., this is studies x voxels\n%\n% Each row of Y is an observation; if Y has one row, we're classifying an\n% observation (e.g., one brain map)\n%\n% Xi are indicators for tasks (classes), ntasks columns of nobs elements\n% (i.e., an nobs x ntasks matrix)\n\n% eliminate features with no 'on' values (activations)\n\n\n% k is regularization param, biases towards 0.5\nif nargin < 7, k = 1; end\n\nwhkeep_from_notempty = whkeep; % indicator of features after feature-selection, in index of not-empties\n\n% feature selection, if requested\nif ~isempty(selectivity_cutoff) && ~isempty(activation_cutoff)\n\n [Y, whkeep, whkeep_from_notempty] = select_features(Y, Xi, activation_cutoff, selectivity_cutoff, whkeep);\n\nend\n\n[nobs, nfeatures] = size(Y);\nnclasses = size(Xi, 2);\n\nif return_full_ps\n [priors, pa1_given_t, pa0_given_t, pt_given_act1, pt_given_act0, pa1_given_not_t] = ...\n bayes_get_probabilities(Y, Xi, k);\n\nelse\n % key results (not all) only; saves computation time in\n % crossvalidation.\n [priors, pa1_given_t, pa0_given_t] = bayes_get_probabilities(Y, Xi, k);\n\nend\n\ntrue_class = indic2condf(Xi);\n\n\nbayes_model = struct('nobs', nobs, 'nfeatures', nfeatures, 'nclasses', nclasses, ...\n 'whkeep', whkeep, 'whkeep_from_notempty', whkeep_from_notempty, ...\n 'params', [], ...\n 'priors', priors, 'pa1_given_t', pa1_given_t, 'pa0_given_t', pa0_given_t, ...\n 'Xi', Xi, 'true_class', true_class);\n\nbayes_model.params.gam = 1; % gamma, weighting on prior vs. joint evidence\nbayes_model.params.k = k; % k, regularization of pa|t, bias towards 0.5.\nbayes_model.params.activation_cutoff = activation_cutoff;\nbayes_model.params.selectivity_cutoff = selectivity_cutoff;\n\nif return_full_ps\n bayes_model.pt_given_act1 = pt_given_act1;\n bayes_model.pt_given_act0 = pt_given_act0;\n bayes_model.pa1_given_not_t = pa1_given_not_t;\n\nend\n\n\nend\n\n\n\n\nfunction [class_est log_joint best_log map p_obs_act_given_class] = classify_naive_bayes_test(Y, bayes_model)\n\n% Estimate classes, log joint p, and MAP estimates for a test data set\n\n% P(task | act)\n% The var. below is all that is needed to choose the best class.\n% argmax log_joint\n% do this for each observation\n\n[nobs, nfeatures] = size(Y);\n\nif nfeatures ~= bayes_model.nfeatures\n % try eliminating zero voxels\n Y = Y(:, bayes_model.whkeep);\n [nobs, nfeatures] = size(Y);\nend\n\nif nfeatures ~= bayes_model.nfeatures\n error('Number of features (i.e., voxels/regions) in Y must equal that in bayes_model structure or that of original training data.');\nend\n\nlog_joint = zeros(nobs, bayes_model.nclasses);\nmap = zeros(nobs, bayes_model.nclasses);\n\nclass_est = zeros(nobs, 1);\nbest_log = zeros(nobs, 1);\n\ngam = bayes_model.params.gam; % prior weighting factor; from 0 to nfeatures.\n\nlogpriors = log(bayes_model.priors);\n%logpriors = logpriors(ones(nfeatures, bayes_model.nclasses));\n\nfor i = 1:nobs\n\n wh_active = Y(i,:)' > 0;\n\n % sum of log prob. of activation at each active voxel, plus sum of\n % log prob. of NOT activation at each inactive voxel (1 - p(activation))\n % Same as ln of product of all p(act state = observed state |\n % class) for all features\n\n % prob. that activity state is the observed one in the test vector,\n % given each class.\n % p(Fi = fi | C = c)\n % p(ACTi = acti | T = t)\n\n % % % % p_obs_act_given_class(wh_active, :) = bayes_model.pt_given_act1(wh_active, :); % p(active | t, obs active)\n % % % % p_obs_act_given_class(~wh_active, :) = bayes_model.pt_given_act0(~wh_active, :);\n\n p_obs_act_given_class = zeros(nfeatures, bayes_model.nclasses);\n p_obs_act_given_class(wh_active, :) = bayes_model.pa1_given_t(wh_active, :); % p(active | t, obs active)\n p_obs_act_given_class(~wh_active, :) = bayes_model.pa0_given_t(~wh_active, :); % p(not active | t, obs not active)\n\n loglikelihood = sum(log(p_obs_act_given_class));\n log_joint(i,:) = gam * log(bayes_model.priors) + loglikelihood; % log of joint prob. p(T, Y), p(task, act1, act2, act3, etc.)\n\n %log_joint(i,:) = sum(log(p_obs_act_given_class)); % proportional to the posterior.\n\n [best_log(i) class_est(i)] = max(log_joint(i,:));\n\n % Divide joint by evidence\n % get scaled estimate of p(task | activation)\n % These are Max. a posteriori estimates, and values may be > 1 because\n % we're assuming independence when that assumption is not likely to be true\n % * something still wrong with this\n % % % %\n % % % % % evidence\n % % % % log_evidence = sum(bayes_model.log_evidence_act(wh_active)) + sum(bayes_model.log_evidence_notact(~wh_active));\n % % % % % because something is wrong, exp() gives Inf values a lot, so isn't\n % very sensible.\n % % % % map(i,:) = log_joint(i,:) - log_evidence; %exp(log_joint(i,:) - log_evidence);\n\n\n map(i,:) = exp(log_joint(i,:) ./ (gam + nfeatures) ); %exp(log_joint(i, :)); % will be very small\n %sum(log_joint) + nfeatures * logpriors;\n\n %map = map ./ sum(map);\n\n\nend\n\n\nend\n\n\n\n\nfunction [prop_correct, m, misclass, prop_correct_by_class, chance, chance_95_ci] = classify_naive_bayes_eval(true_class, class_est, wh_obs)\n\nif nargin < 3 || isempty(wh_obs)\n % assume we have all observations.\n wh_obs = 1:length(true_class);\nend\n\n[m,dp,corr,far,misclass] = confusion_matrix(true_class(wh_obs),class_est);\n\ntotaln = sum(m(:));\nprop_correct = trace(m) ./ totaln;\n\nnclasses = length(unique(true_class(true_class ~= 0)));\n\nprop_correct_by_class = diag(m) ./ sum(m,2);\n\n\nchance = 1 ./ nclasses;\nchance_95_ci = [chance - sqrt(chance * (1 - chance) ./ totaln) chance + sqrt(chance * (1 - chance) ./ totaln)];\n\nend\n\n\n\nfunction [Y, whkeep] = eliminate_empty_Y(Y)\n\nfprintf('Eliminating any empty features. \\n');\n\n% using whkeep helps avoid out of memory errors.\nwhzero = (sum(Y) < eps);\nwhkeep = ~whzero;\nY = Y(:, whkeep);\n\nend\n\n\n\nfunction [Y, whkeep, whomsave] = select_features(Y, Xi, activation_cutoff, selectivity_cutoff, whkeep)\n\n% select features\n% -----------------------------------------------------------------\n\n[nobs, nfeatures] = size(Y);\nntasks = size(Xi,2);\n\nsumtasks = sum(Y); sumtasks(sumtasks==0) = 1; % avoid warning for empty tasks\n\n% p(task | activation) estimates\nptask = (Xi' * Y) ./ repmat(sumtasks,ntasks,1);\n\nmaxp = max(ptask); % max prob of task across vars\n\npt = (Xi' * Y) ./ repmat(sum(Xi)',1,nfeatures); % proportion of each task that activated in an area\nptmax = max(pt);\nwhomsave = maxp > (selectivity_cutoff) & ptmax > activation_cutoff;\n\nif sum(whomsave) == 0\n disp('Warning: No variables meet feature selection criteria.');\n whomsave = (maxp == max(maxp));\nend\n\nwhkeep(whkeep) = whomsave; % indices of saved voxels in whole-brain (original) index vector\n%whkeep = whkeep(whomsave); % overall indices of saved voxels\nY = Y(:,whomsave);\n\n%fprintf(1,'Selected: %3.0f ',nvars);\n% get weights on voxels based on n activations.... ******\n\nend\n\n\n\n\nfunction bayes_model = write_images(bayes_model, Y, volInfo, conditionnames)\n% bayes_model = write_images(bayes_model, MC_Setup.volInfo, MC_Setup.Xinms)\n\n% Xi = bayes_model.Xi;\n\n%[priors, pa1_given_t, pa0_given_t, varargout] = bayes_get_probabilities(Y, Xi, bayes_model.params.k);\n\nnfeatures_orig = length(bayes_model.whkeep);\n\npa1_given_t = NaN * zeros(nfeatures_orig, bayes_model.nclasses);\npa1_given_not_t = NaN * zeros(nfeatures_orig, bayes_model.nclasses);\n\npt_given_act1 = NaN * zeros(nfeatures_orig, bayes_model.nclasses);\npt_given_act0 = NaN * zeros(nfeatures_orig, bayes_model.nclasses);\n\npa1_given_t(bayes_model.whkeep,:) = bayes_model.pa1_given_t;\npa1_given_not_t(bayes_model.whkeep,:) = bayes_model.pa1_given_not_t;\n\npt_given_act1(bayes_model.whkeep,:) = bayes_model.pt_given_act1;\npt_given_act0(bayes_model.whkeep,:) = bayes_model.pt_given_act0;\n\n\n% now done in bayes_get_probabilities\n% % pa1_given_not_t = (double(~(Xi)') * Y)' ./ repmat(sum(~Xi), size(Y, 2), 1);\n% % pa1_given_not_t(pa1_given_not_t < eps) = 1 ./ bayes_model.nobs;\n% % pa1_given_not_t(pa1_given_not_t == 1) = 1 - (1 ./ bayes_model.nobs);\n\n%%%%pa1_given_not_t(~bayes_model.whkeep, :) = NaN;\n\n\ndisp('Writing images to disk in the current directory.');\n\nfor i = 1:bayes_model.nclasses\n pa1_given_tname{i} = ['pa|t_' conditionnames{i} '.img'];\n iimg_reconstruct_3dvol(pa1_given_t(:,i), volInfo, 'outname', pa1_given_tname{i});\n\n disp(pa1_given_tname{i})\n\n pa_given_nottname{i} = ['pa|nott_' conditionnames{i} '.img'];\n iimg_reconstruct_3dvol(pa1_given_not_t(:,i), volInfo, 'outname', pa_given_nottname{i});\n\n disp(pa_given_nottname{i})\n\n pt_given_aname{i} = ['pt|a_' conditionnames{i} '.img'];\n iimg_reconstruct_3dvol(pt_given_act1(:,i), volInfo, 'outname', pt_given_aname{i});\n\n disp(pt_given_aname{i})\n\n pt_given_notaname{i} = ['pt|nota_' conditionnames{i} '.img'];\n iimg_reconstruct_3dvol(pt_given_act0(:,i), volInfo, 'outname', pt_given_notaname{i});\n\n disp(pt_given_notaname{i})\nend\n\n\n% likelihood ratio at each voxel\n% should penalize this in some way for low activations...\n%pa1_given_t(pa1_given_t == 0) = 1;\n%pa1_given_not_t(pa1_given_not_t == 0) = 1;\n\n% higher numbers mean more association between activation and class.\n% lr for 2 classes can both be positive IF not all obs. fall within class 1\n% or class 2!!!\nevidence_yes = (sum(Y) ./ bayes_model.nobs)';\nevidence_yes = evidence_yes(:, ones(1, bayes_model.nclasses));\n\n% % priors = NaN * zeros(nfeatures_orig, bayes_model.nclasses);\n% % priors(bayes_model.whkeep,:) = bayes_model.priors(ones(bayes_model.nfeatures, bayes_model.nclasses));\n\n% add .1 to regularize...this could be k param\nlr = ( (pa1_given_t + .1) ./ (evidence_yes + .1) ) - 1;\n%pt_given_act1 ./ pt_given_act0;\nlr(lr < .05 & lr > -.05) = NaN;\n%lr = log(lr);\n\nfor i = 1:bayes_model.nclasses\n lrname{i} = ['likeratio_' conditionnames{i} '.img'];\n iimg_reconstruct_3dvol(lr(:,i), volInfo, 'outname', lrname{i});\n\n disp(lrname{i})\nend\n\nbayes_model.image_output.volInfo = volInfo;\nbayes_model.image_output.pa1_given_tname = pa1_given_tname;\nbayes_model.image_output.pa_given_nottname = pa_given_nottname;\n\nbayes_model.image_output.pt_given_aname = pt_given_aname;\nbayes_model.image_output.pt_given_notaname = pt_given_notaname;\n\nbayes_model.image_output.likerationame = lrname;\n\nbayes_model.image_output.pa1_given_t = pa1_given_t;\nbayes_model.image_output.pa1_given_not_t = pa1_given_not_t;\nbayes_model.image_output.likeratio = lr;\n\nend\n\n\n\n\nfunction cl = display_output(bayes_model, disptype, varargin)\n% display_output(bayes_model, disptype, varargin)\n\nswitch spm('Ver')\n case 'SPM2'\n % spm_defaults is a script\n disp('WARNING: spm defaults not set for spm2. Make sure your defaults are set correctly');\n\n case 'SPM5'\n % spm_defaults is a function\n spm_defaults()\n \n case 'SPM8'\n % spm_defaults is a function\n spm_defaults()\n \n otherwise\n % unknown SPM\n disp('Unknown version of SPM!');\n spm_defaults()\nend\n\ncl = [];\ncolors1 = [1 .7 0];\ncolors2 = [0 0 1];\n\nfor i = 1:length(varargin)\n if iscell(varargin{i})\n colors1 = varargin{i}{1};\n colors2 = varargin{i}{2};\n elseif length(varargin{i}) == 1\n thresh = varargin{i};\n end\nend\n\nswitch disptype\n\n case {'pa|t', 'lr', 'pt|a'}\n\n overlay = which('spm2_single_subj_T1_scalped.img');\n spm_check_registration(repmat(overlay, bayes_model.nclasses, 1));\n\n for i = 1:bayes_model.nclasses\n\n switch disptype\n case 'pa|t'\n cl{i} = mask2clusters(bayes_model.image_output.pa1_given_tname{i});\n fprintf('Displayed: p(a | t) for each task.\\n');\n\n spm_orthviews_name_axis(bayes_model.image_output.pa1_given_tname{i}, i);\n\n\n case 'lr'\n cl{i} = mask2clusters(bayes_model.image_output.likerationame{i});\n fprintf('Displayed: regions with positive likelihood ratio for each task.\\n');\n\n spm_orthviews_name_axis(bayes_model.image_output.likerationame{i}, i);\n\n case 'pt|a'\n cl{i} = mask2clusters(bayes_model.image_output.pt_given_aname{i});\n fprintf('Displayed: p(t | a) for each task.\\n');\n\n spm_orthviews_name_axis(bayes_model.image_output.pt_given_aname{i}, i);\n\n end\n\n % threshold\n if exist('thresh', 'var')\n for j = 1:length(cl{i})\n wh_omit = abs( cat(2, cl{i}(j).Z) ) < thresh;\n cl{i}(j).XYZ(:, wh_omit) = [];\n cl{i}(j).XYZmm(:, wh_omit) = [];\n cl{i}(j).Z(:, wh_omit) = [];\n end\n\n clu = clusters2CLU(cl{i});\n cl{i} = tor_extract_rois([], clu, clu);\n\n end\n\n\n cluster_orthviews(cl{i}, 'handle', i, 'add');\n\n end\n\n switch disptype\n case 'pa|t'\n %spm_orthviews_change_colormap([.2 .2 .4], [1 1 0], [.9 .6 .1]); %slate to orange to yellow\n spm_orthviews_change_colormap([.5 0 0], [1 1 0], [1 .5 0]); %blue to yellow\n\n case 'lr'\n spm_orthviews_change_colormap(colors2, colors1); %blue to white to yellow\n\n case 'pt|a'\n spm_orthviews_change_colormap(colors2, colors1);\n\n end\n\n case 'lr surface'\n\n poscm = colormap_tor([.2 .2 .4], [1 1 0], [.9 .6 .1]); %slate to orange to yellow\n negcm = colormap_tor([0 0 1], [0 .3 1]); % light blue to dark blue (shouldn't be needed!)\n\n\n for i = 1:bayes_model.nclasses\n\n cl{i} = mask2clusters(bayes_model.image_output.likerationame{i});\n\n fprintf('Displayed: regions with positive likelihood ratio for each task.\\n');\n\n % Left medial and lateral surface\n % ----------------------------------------------------------\n create_figure('Brain Surface'); scn_export_papersetup(800);\n\n cluster_surf(cl{i}, 4, 'heatmap', 'colormaps', poscm, negcm, 'hires left');\n sh = cluster_surf(cl{i}, 4, 'heatmap', 'colormaps', poscm, negcm, 'brainstem');\n saveas(gcf, [bayes_model.image_output.likerationame{i}(1:end-4) '_left_medial'], 'png');\n\n view(270,0); lightRestoreSingle;\n saveas(gcf, [bayes_model.image_output.likerationame{i}(1:end-4) '_left_lateral'], 'png');\n\n % Right medial and lateral surface\n % ----------------------------------------------------------\n create_figure('Brain Surface'); cluster_surf(cl{i}, 4, 'heatmap', 'colormaps', poscm, negcm, 'hires right');\n sh = cluster_surf(cl{i}, 4, 'heatmap', 'colormaps', poscm, negcm, 'brainstem');\n scn_export_papersetup(800); saveas(gcf, [bayes_model.image_output.likerationame{i}(1:end-4) '_right_lateral'], 'png');\n\n view(270,0); lightRestoreSingle;\n saveas(gcf, [bayes_model.image_output.likerationame{i}(1:end-4) '_right_medial'], 'png');\n\n % Limbic\n % ---------------------------------------------------------\n create_figure('Brain Surface'); cluster_surf(cl{i}, 4, 'heatmap', 'colormaps', poscm, negcm, 'limbic');\n saveas(gcf, [bayes_model.image_output.likerationame{i}(1:end-4) '_limbic'], 'png');\n saveas(gcf, [bayes_model.image_output.likerationame{i}(1:end-4) '_limbic'], 'fig');\n end\n\n\n case 'map plot'\n\n % MAP plot\n\n colors = {'b' 'r' 'k' 'g' 'm'};\n create_figure('MAP Plot across observations');\n for i = 1:bayes_model.nclasses\n\n trueclassi = find(bayes_model.Xi(:,i) == 1);\n myclassmap = bayes_model.apparent.map(trueclassi, i);\n\n plot(bayes_model.apparent.map(:, i), 'color', colors{i});\n plot(trueclassi, bayes_model.apparent.map(find(bayes_model.Xi(:,i) == 1), i), 'o', 'Color', colors{i},'MarkerFaceColor',colors{i});\n\n incorrect_obs = ~(myclassmap == max(bayes_model.apparent.map(trueclassi, :), [], 2));\n incorrect_obs_vec = zeros(bayes_model.nobs, 1);\n incorrect_obs_vec(trueclassi(incorrect_obs)) = 1;\n\n plot(find(incorrect_obs_vec), myclassmap(incorrect_obs), 'kx', 'MarkerSize', 12, 'LineWidth', 2);\n end\n xlabel('Observations'); ylabel('log(MAP) (up to scaling constant)');\n\n\n\n case 'class plot'\n\n pr = bayes_model.priors;\n fr = [linspace(1, 0, 10)' linspace(0, 1, 10)']; % frequencies of guesses, from always A to always B\n\n xfr = linspace(1, 0, 10);\n\n %hr_byclass = fr .* repmat(pr, size(fr, 1), 1)\n colors = {'b' 'r' 'k' 'g' 'm'};\n\n hr = fr * pr';\n\n create_figure('Summary Line Plot');\n %plot(xfr, hr_byclass);\n plot(xfr, hr, 'k', 'LineWidth', 2);\n\n phighestfreq = sum(bayes_model.xval.class_est == wh) ./ length(bayes_model.xval.class_est); % p chosen for highest-frequency class\n plot(phighestfreq, bayes_model.xval.prop_correct, 'ko', 'LineWidth', 2, 'MarkerFaceColor', [.5 .5 .5], 'MarkerSize', 12);\n\n xx = repmat(phighestfreq, 2, bayes_model.nclasses);\n yy = [bayes_model.xval.prop_correct_by_class'; bayes_model.xval.prop_correct_by_class'];\n\n for i = 1:size(yy, 2)\n plot(xx(:,i), yy(:,i), 'o', 'Color', colors{i}, 'LineWidth', 2, 'MarkerFaceColor', colors{i}, 'MarkerSize', 12);\n end\n\n % Standard error of hit rate\n % var(hits for each category) = p*(1-p)*N for that category\n % where p is the prior p(correct) for that category, and N is the number of\n % choices in that category given the frequency of sampling that category.\n\n se_hr = sqrt( hr .* (1 - hr) ./ bayes_model.nobs );\n ci95_hr = 1.96 * se_hr;\n\n plot(xfr, hr + ci95_hr, 'k--', 'LineWidth', 1);\n plot(xfr, hr - ci95_hr, 'k--', 'LineWidth', 1);\n fill_around_line(hr, ci95_hr, 'k', xfr);\n\n ylabel('Correct classification rate');\n xlabel('Prop. choices from highest class');\n\n\n % N = fr .* bayes_model.nobs; % for each of k categories, in a row\n\n % pq = repmat(pr .* (1 - pr), size(fr,1), 1);\n % varsum = sum(pq .* N, 2)\n %\n %\n % se_hr = sqrt( sum(repmat(pr .* (1 - pr), size(fr,1), 1) ./ (bayes_model.nobs .* fr), 2) )\n % se_hr(isinf(se_hr)) = 0;\n\n\n otherwise\n error('Unknown display option.')\nend\n\nend\n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/Statistics_tools/classify_naive_bayes.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3451052709578724, "lm_q1q2_score": 0.18063512134453424}} {"text": "classdef ParadigmPAL < ParadigmBaseSimplified\n % Experimental implementation of the Pattern Alignment Learning (PAL) method.\n %\n % This paradigm is not yet completed, please move on! :-)\n %\n % Name:\n % Wave Alignment, work in progress\n %\n % Christian Kothe, Swartz Center for Computational Neuroscience, UCSD\n % 2011-08-28\n \n methods\n \n function defaults = preprocessing_defaults(self)\n % define the default pre-processing parameters of this paradigm\n defaults = {'SpectralSelection',[0.1 35],'EpochExtraction',[-0.5 1.5], 'Resampling',100};\n end\n \n function model = calibrate_simple(self,varargin)\n % Override this function to implement your calibration code\n % Model = calibrate_simple(Signal,Arguments...)\n %\n % In:\n % Signal : a single continuous EEGLAB data set (annotated with target markers; see\n % set_targetmarkers for more info)\n %\n % Arguments : further optional user arguments\n %\n % Out:\n % Model : a model struct with a mandatory field .filter_graph and arbitrary other content\n % * The .filter_graph filed is a 1x1 cell array that contains the desciption of\n % filter steps that is to be applied to the data, and is usually passed as either\n % the .tracking.online_expression field of the processed Signal or the processed\n % Signal itself. If no signal processing is performed by this paradigm, the raw\n % signal may be passed.\n %\n % * May have optional fields .prediction_function, .prediction_window and\n % .prediction_channels - though these are generally auto-deduced\n %\n % Notes:\n \n args = arg_define(varargin, ...\n arg_norep('signal'), ...\n arg_sub({'flt','SignalProcessing'}, self.preprocessing_defaults(), @flt_pipeline, 'Signal processing stages. These parameters control filter stages that run on the signal level; they can be enabled, disabled and configured for the given paradigm. The prediction operates on the outputs of this stage.'), ...\n arg({'lambdas','Lambdas'},[2.^(8:-0.125:-5)],[0 Inf],'Regularization parameter. Larger means stronger regularization, 1.0 is the Bayesian ad hoc choice.'), ...\n arg({'duration','WaveDuration'},0.8,[0 Inf],'Duration of Waveform. This is the length of the waveform that will be searched in the epoch.'), ...\n arg({'stepping','Stepping'},3,uint32([1 100]),'Relative jitter stepping. This is the precision (in samples) at which relative jitters will be considered.'), ...\n arg({'admm_iters','ADMMIterations'},30,uint32([1 1000]),'Max Iterations. Number of iterations for the overall ADMM solver.'), ...\n arg({'inner_iters','InnerIterations'},10,uint32([1 1000]),'Max Inner Iterations. Number of iterations for the inner ADMM solver that solves the sparsity vs trace norm.'), ...\n arg({'cg_iters','CgIterations'},30,uint32([1 1000]),'Max CG Iterations. Number of iterations for the inner conjugate-gradient solver.'), ...\n arg({'lanczos_iters','LanczosIterations'},10,uint32([1 1000]),'Max Lanczos Iterations. Number of iterations for the inner Lanczos solver.'), ...\n arg({'abs_tol','AbsoluteTolerance'},1e-6,[],'Absolute tolerance.'), ...\n arg({'rel_tol','RelativeTolerance'},1e-3,[],'Relative tolerance.'), ...\n arg({'alpha','OverRelaxation'},1,[1 1.8],'Over-relaxation parameter. Some references suggest that values between 1.5 and 1.8 can improve convergence.'), ...\n arg({'rho','AugmentedLagrangian'},1.0,[0 Inf],'Augmented Lagrangian parameter.'), ...\n arg({'rho_update','RhoUpdate'},true,[],'Update Rho. Whether to update rho dynamically according to 3.4.1 in [1]'), ...\n arg({'rho_cutoff','RhoUpdateThreshold'},10.0,[0 Inf],'Rho update threshold.'), ...\n arg({'rho_incr','RhoUpdateIncr'},2.0,[1 Inf],'Rho update increment factor.'), ...\n arg({'rho_decr','RhoUpdateDecr'},2.0,[1 Inf],'Rho update decrement factor.'), ... \n arg({'kappa','SparsityTraceTradeoff'},0.75,[0 1],'Sparsity (=1) vs. Trace norm (=0) tradeoff. Between 0 and 1, similar to the elastic net criterion.'), ...\n arg({'patterns','NumPatterns'},20,uint32([1 1000]),'Number of weight patterns. This is the maximum number of (possibly distinct) weight patterns to recover.'), ...\n arg({'verbose','Verbose'},'really',[],'Verbose output.'), ...\n arg({'scaling','Scaling'}, 'std', {'none','center','std','minmax','whiten'}, 'Pre-scaling of the data. For the regulariation to work best, the features should either be naturally scaled well, or be artificially scaled.'), ...\n arg({'fast','Fast'},true,[],'Fast mode.'), ...\n arg({'arg_dialogsel','ConfigLayout'},self.dialog_layout_defaults(),[],'Parameters displayed in the config dialog. Cell array of parameter names to display (dot-notation allowed); blanks are translated into empty rows in the dialog. Referring to a structure argument lists all parameters of that struture, except if it is a switchable structure - in this case, a pulldown menu with switch options is displayed.','type','cellstr','shape','row'));\n \n % first pre-process the data (symbolically)\n signal = flt_pipeline('signal',args.signal, args.flt); %#ok<*NODEF>\n \n % evaluate this in an optimized fashion\n signal = exp_eval_optimized(signal);\n \n % get trial labels\n labels = set_gettarget(signal);\n \n % build meta-data\n model.args = rmfield(args,'signal');\n model.classes = unique(labels,'rows');\n model.tracking.filter_graph = signal;\n \n if length(model.classes) > 2\n error('Currently, only two classes are supported here.'); end\n \n % extract time-shifted windows from each trial...\n duration = round(args.duration * signal.srate);\n offsets = 1 : args.stepping : (signal.pnts - duration);\n trials = cell(1,length(offsets));\n\n % get the entire epoch and figure out an appropriate rescaling\n alldata = reshape(permute(signal.data,[2 1 3]),[],signal.trials);\n sc_info = hlp_findscaling(alldata,args.scaling);\n \n % for each time shift...\n for o = offsets\n % determine the window to cut out of the data\n cutwindow = o + (1:duration);\n % extract from all trials\n data = signal.data(:,cutwindow,:);\n % vectorize into #trials x #features, and rescale\n data = permute(data,[2 1 3]);\n trials{o} = hlp_applyscaling(reshape(data,[],signal.trials),sc_info)';\n end\n \n T = signal.trials;\n fprintf('#trials=%.0f; #shifts=%.0f; #features=%.0f; #channels=%.0f; #windows=%.0f\\n',T,length(offsets),signal.nbchan*length(cutwindow),signal.nbchan,length(cutwindow));\n \n % vertically concatenate all shifts (into #shifts*#trials x #features)\n A = vertcat(trials{:});\n\n % remap the labels to -1 / +1\n labels(labels == model.classes(1)) = -1;\n labels(labels == model.classes(2)) = +1;\n \n % and generate shift-replicated target matrix b\n b = repmat(labels,1,length(offsets));\n b = b(:);\n \n C0 = -[b A]; % (bias is first elem, followed by rest...)\n ccp = C0';\n \n % weight vectors\n [m,n] = size(A);\n Wz = zeros(n+1,m); % consensus variable\n Wx = zeros(n+1,m); % data weights variable, FxN; n+1 accounts for the added bias (this is actually just the initial conditions vector...)\n Wu = zeros(n+1,m); % scaled dual parameter u for Wx\n\n alpha = args.alpha; % over-relaxation parameter (if 1, OR turned off)\n rho = args.rho; % augmented Lagrangian parameter; probably determines sort of the tightness of the constraints...\n kappa = args.kappa; % blend factor between trialwise sparsity and trialwise agreement\n K = args.patterns; % the maximum number of SV's to recover\n \n rescale = 1; % scale of the left-hand side term (could be m/length(offsets)\n for mu = args.lambdas % regularization parameter (should be decreasing)\n fprintf('Now using lambda = %.3f\\n',mu);\n if args.verbose\n fprintf('%3s\\t%10s\\t%10s\\t%10s\\t%10s\\t%10s\\n', 'iter', ...\n 'r norm', 'eps pri', 's norm', 'eps dual', 'objective');\n end\n \n for k = 1:args.admm_iters\n Wzold = Wz;\n fprintf('Outer step #%.0f\\n',k);\n \n %% x-update\n Wx = ParadigmPAL.minimize_batch(Wx, @ParadigmPAL.x_objective_batch, args.cg_iters, Wz, Wu, ccp, rho);\n Wx_hat = alpha*Wx + (1-alpha)*Wzold; % (optional over-relaxation)\n \n %% z-update\n Wz = Wx_hat + Wu;\n [Wz,fuuu,U,V] = ParadigmPAL.prox_sum(Wz,rescale,mu,kappa,rho,K,T,m,args);\n\n %% dual parameter update\n fprintf(' updating u''s\\n');\n Wu = Wu + (Wx_hat - Wz);\n \n %% diagnostics, reporting, termination checks\n fprintf(' diagnostics...\\n');\n history.objval(k) = 0; %ParadigmPAL.full_objective(ccp, mu, Wx, Wz);\n history.r_norm(k) = norm(Wx(:) - Wz(:));\n history.s_norm(k) = norm(rho*(Wz(:) - Wzold(:)));\n history.eps_pri(k) = args.abs_tol + args.rel_tol*max(norm(Wx(:)), norm(Wz(:)));\n history.eps_dual(k)= args.abs_tol + args.rel_tol*norm(rho*Wu(:));\n \n if args.verbose\n fprintf('%3d\\t%10.4f\\t%10.4f\\t%10.4f\\t%10.4f\\t%10.2f\\n', k, ...\n history.r_norm(k), history.eps_pri(k), ...\n history.s_norm(k), history.eps_dual(k), history.objval(k));\n if strcmp(args.verbose,'really') && nnz(fuuu)\n f=figure; set(f,'Position',get(f,'Position')-[0 500 0 0]);\n imagesc(Wz); ylabel('features'); xlabel('shifted trials'); title(sprintf('ADMM iter #%.0f, lambda=%.3f',k,mu)); \n figure;\n % weight patterns \n N = nnz(fuuu);\n cols = ceil(sqrt(N));\n rows = ceil(N/cols);\n for p=1:N\n subplot(cols,rows,p);\n plot((0:round(args.duration * signal.srate)-1)/signal.srate,reshape(U(2:end,p),length(cutwindow),signal.nbchan)); title(sprintf('weight array #%.0f',p)); xlabel('time (s)'); ylabel('weight');\n end\n % topoplots...\n f=figure; set(f,'Position',get(f,'Position')-[550 0 0 0]);\n N = nnz(fuuu);\n cols = ceil(sqrt(N));\n rows = ceil(N/cols);\n for p=1:N\n subplot(cols,rows,p);\n mat = reshape(U(2:end,p),length(cutwindow),signal.nbchan);\n mat_inner = mat(round(end*1/4):round(end*3/4),:);\n [dummy,peakidx] = max(mean(abs(mat_inner),2)); % #ok\n topoplot(mat_inner(peakidx,:),signal.chanlocs);\n end\n drawnow; \n end\n end\n \n if history.r_norm(k) < history.eps_pri(k) && history.s_norm(k) < history.eps_dual(k)\n break; end\n \n %% update of rho\n if args.rho_update\n if history.r_norm(k) > args.rho_cutoff * history.s_norm(k)\n disp(' incrementing rho.');\n rho = rho .* args.rho_incr;\n Wu = Wu ./ args.rho_incr;\n elseif history.s_norm(k) > args.rho_cutoff * history.r_norm(k)\n disp(' decrementing rho.');\n rho = rho ./ args.rho_incr;\n Wu = Wu .* args.rho_incr;\n end\n end\n end\n end\n 1 \n %% plotting...\n \n% % full weight matrix\n% figure;imagesc(Wz); title('full weight matrix'); xlabel('features'); ylabel('shifted trials');\n% \n% % shift matrix (?)\n% figure; imagesc(reshape(V(:,1),length(offsets),[])); title('shift matrix'); xlabel('trials'); ylabel('shifts');\n end \n \n function outputs = predict_simple(self,signal,model)\n % Override this function to implement your prediction code\n % Outputs = predict_simple(Sginal,Model)\n %\n % In:\n % Signal : a signal pre-processed according to the model's filter graph\n %\n % Model : a predictive model as created by your calibrate_simple() function\n %\n % Out:\n % Outputs : a prediction/estimate for the most recent time point in the data (or one for\n % every epoch if the signal is epoched); see ml_predict for the allowed formats\n \n error('This paradigm implements no predict() function.');\n end\n \n \n function visualize(self,model)\n % Optionally override this function to implement your visualization code\n % visualize(Model)\n %\n % In:\n % Model: a model as created by your calibrate() function;\n % a plot or GUI will be produced to inspect the model\n %\n \n error('This paradigm implements no visualize() function.');\n end\n \n \n \n % --- implementation ----\n \n function model = calibrate(self,varargin)\n % Implementation of the calibrate() function (see ParadigmBase)\n % Model = calibrate(Collection,GoalIdentifier,Arguments...)\n %\n % This is essentially a wrapper around calibrate_simple() which peels off any additional\n % data structure (for multiple collections and stream bundles) before passing it on.\n %\n % In:\n % Collection : a collection (cell array) of stream bundles\n %\n % GoalIdentifier: the goal-identifier\n %\n % Arguments... : further optional user arguments\n %\n % Out:\n % Model : The returned model struct\n \n % get the collection argument and extract the signal argument\n collection = arg_extract(varargin,{'collection','Collection'},[],{});\n if ~isempty(collection)\n if length(collection) > 1\n error('This paradigm does not support collections of more than one recording.'); end\n if length(collection{1}.streams) > 1\n error('This paradigm does not support more than one stream in parallel.'); end\n signal = collection{1}.streams{1};\n else\n signal = {};\n end\n \n % call calibrate_simple with the signal passed in as additional argument\n model = self.calibrate_simple('signal',signal,varargin{:});\n end\n \n \n function outputs = predict(self,bundle,model)\n % Override this function to implement your prediction code\n % Outputs = predict(Bundle,Model)\n %\n % This is a wrapper around the predict_simple() function which peels off the stream bundle\n % representation and just passes on the contained signal.\n %\n % In:\n % Bundle : stream bundle preprocessed by the model's filter graph\n %\n % Model : a predictive model\n %\n % Out:\n % Outputs : the outputs of calibrate_simple()\n \n if length(bundle.streams) > 1\n error('This paradigm does not support more than one stream in parallel.'); end\n outputs = self.predict_simple(bundle.streams{1},model);\n end\n \n end\n \n \n methods(Static)\n function obj = full_objective(ccp, mu, Wx, Wz)\n % this is the overall objective function of alignment learning\n obj = sum(log(1 + exp(sum(ccp.*Wx)))) + mu*(norm_nuc(Wz) + sum(norms(Wz))) * size(ccp,2); \n end\n \n function [val,grad] = x_objective(x, C, z, u, rho)\n % this is the objective function for the decoupled x criterion (basically l2 logreg)\n ecx = exp(C*x);\n val = sum(log(1 + ecx)) + (rho/2)*norm(x - z + u).^2;\n grad = C'*(ecx./(1 + ecx)) + rho*(x - z + u);\n end\n \n function [vals,grads] = x_objective_batch(Wx,Wz,Wu,ccp,rho)\n % this is the batch version of the above (for all samples & variables in parallel)\n ecx = exp(sum(ccp.*Wx));\n d = Wx - Wz + Wu;\n vals = log(1 + ecx) + (rho/2)*sum(d.*d);\n grads = bsxfun(@times,ccp,(ecx./(1 + ecx))) + rho*d;\n end\n \n % l1/l2 shrinkage operator\n function Wz = shrinkage(Wa, kappa)\n Wz = pos(1 - kappa/norm(Wa))*Wa;\n end\n\n % l1 shrinkage operator\n function z = shrinkage_l1(a, kappa)\n z = max(0, a-kappa) - max(0, -a-kappa);\n end\n\n % trace norm proximal operator\n function [W,fuuu,U,V] = prox_tr(W,rescale,mu,kappa,rho,K,args)\n fprintf(' trace norming r\\n');\n [U,S,V] = pca(W,K,args.lanczos_iters);\n fuuu = ParadigmPAL.shrinkage_l1(diag(S),(rescale*mu*(1-kappa))/rho); nn = length(fuuu); % we shrink the SV spectrum using prox operator\n Ws = sparse(1:nn,1:nn,fuuu,size(S,1),size(S,2));\n % clamp minority of V's members at 0\n smv = sign(median(V));\n V(:,smv==-1) = min(0,V(:,smv==-1));\n V(:,smv==1) = max(0,V(:,smv==1));\n W = U*(Ws*V');\n \n if strcmp(args.verbose,'ultra')\n f=figure; set(f,'Position',get(f,'Position')-[0 500 0 0]);\n imagesc(W); ylabel('features'); xlabel('shifted trials'); title(sprintf('lambda=%.3f',mu));\n figure;\n % weight patterns\n N = nnz(spec);\n cols = ceil(sqrt(N));\n rows = ceil(N/cols);\n signal=args.signal;\n for p=1:N\n subplot(cols,rows,p);\n plot((0:(numel(U(2:end,p))/signal.nbchan)-1)/signal.srate,reshape(U(2:end,p),[],signal.nbchan)); title(sprintf('weight array #%.0f',p)); xlabel('time (s)'); ylabel('weight');\n end\n drawnow;\n end\n \n end\n \n % group-sparse proximal operator\n function W = prox_gl(W,rescale,mu,kappa,rho,T,m)\n fprintf(' sparsifying z\\n');\n for i = 1:m\n W(2:end,i) = ParadigmPAL.shrinkage(W(2:end,i), (rescale*mu*kappa/10)/rho); end\n end\n \n % summed proximal operator (using some splitting scheme, see Bauscke, 2008)\n function [x,fuuu,U,V] = prox_sum(r,rescale,mu,kappa,rho,K,T,m,args)\n y = r;\n p = zeros(size(y));\n q = zeros(size(y));\n for n=1:args.inner_iters\n [x,fuuu,U,V] = ParadigmPAL.prox_tr(y+q,rescale,mu,kappa,rho,K,args);\n q = y+q-x;\n y = ParadigmPAL.prox_gl(x+p,rescale,mu,kappa,rho,T,m);\n p = x+p-y;\n if norm(x(:) - y(:)) < args.rel_tol*max(norm(x(:)),norm(y(:)))\n break; end\n end \n end\n \n function X = minimize_batch(X, f, len, Wz,Wu,ccp,rho)\n % Copyright (C) 2001 - 2010 by Carl Edward Rasmussen, 2010-01-03\n \n INT = 0.1; % don't reevaluate within 0.1 of the limit of the current bracket % const\n EXT = 3.0; % extrapolate maximum 3 times the current step-size % const\n MAX = 20; % max 20 function evaluations per line search % const\n RATIO = 10; % maximum allowed slope ratio % const\n SIG = 0.1; RHO = SIG/2; % SIG and RHO are the constants controlling the Wolfe- % const\n if max(size(len)) == 2, red=len(2); len=len(1); else red=1; end % scalar\n\n \n [f0 df0] = feval(f,X,Wz,Wu,ccp,rho); % get function value and gradient\n N = length(f0);\n \n [A,B,d1,d2,d3,d4,f1,f2,f3,f4,x1,x2,x4] = deal(zeros(1,N)); % initialize a few variables...\n df3 = zeros(size(X));\n i = 0; % zero the run length counter % scalar\n ls_failed = false(1,N); % no previous line search has failed% boolean vector\n i = i + (len<0); % count epochs?! % scalar\n s = -df0; % initial search direction (steepest) % column MATRIX\n d0 = -sum(s.*s); % and slope % row vector\n x3 = red./(1-d0); % initial step is red/(|s|+1) % row vector\n \n keep_going = true(1,N); % mask for the outermost loop updates... \n while any(keep_going) && i < abs(len) % while not finished % scalar\n i = i + (len>0); % count iterations?! % scalar\n fprintf(' Cg step #%.0f\\n',i);\n \n X0 = X; % column MATRIX\n F0 = f0; % row vector\n dF0 = df0; % make a copy of current values % column MATRIX\n if len>0, M = MAX; else M = min(MAX, -len-i); end % scalar\n \n om = keep_going; % mask for outer-loop updates\n while 1 % keep extrapolating as long as necessary\n x2(om) = 0; % row vector\n f2(om) = f0(om); % row vector\n d2(om) = d0(om); % row vector\n f3(om) = f0(om); % row vector\n df3(:,om) = df0(:,om); % column matrix\n ok(om) = false; % boolean vector\n while ~all(ok(om)) && M > 0 % mask check\n M = M - 1; i = i + (len<0); % count epochs?! % scalar\n nokom = ~ok&om;\n [f3(nokom) df3(:,nokom)] = feval(f, X(:,nokom) + bsxfun(@times,x3(nokom),s(:,nokom)), Wz(:,nokom), Wu(:,nokom), ccp(:,nokom), rho); % masked array op\n ok(om) = ok(om) | ~(isnan(f3(om)) | isinf(f3(om)) | any(isnan(df3(om))+isinf(df3(om)))); % mask update\n x3(~ok&om) = (x2(~ok&om)+x3(~ok&om))/2; % bisect and try again % maked update\n end\n mask = f3 SIG*d0 | f3 > f0 + x3.*d0*RHO) = false; % update outer mask\n if ~any(om) || M == 0 % are we done extrapolating?\n break; end\n \n x1(om) = x2(om); f1(om) = f2(om); d1(om) = d2(om); % move point 2 to point 1 % row vectors\n x2(om) = x3(om); f2(om) = f3(om); d2(om) = d3(om); % move point 3 to point 2 % row vectors\n A(om) = 6*(f1(om)-f2(om))+3*(d2(om)+d1(om)).*(x2(om)-x1(om));% make cubic extrap.% row vectors\n B(om) = 3*(f2(om)-f1(om))-(2*d1(om)+d2(om)).*(x2(om)-x1(om));\n x3(om) = x1(om)-d1(om).*(x2(om)-x1(om)).^2./(B(om)+sqrt(B(om).*B(om)-A(om).*d1(om).*(x2(om)-x1(om)))); % num. error possible, ok!\n \n % implement fixups: num prob | wrong sign | new point beyond extrapolation limit?\n issue_mask = ~isreal(x3) | isnan(x3) | isinf(x3) | x3 < 0 | x3 > x2*EXT;\n x3(om & issue_mask) = x2(om & issue_mask)*EXT;\n % new point too close to previous point?\n issue_mask = ~issue_mask & (x3 < x2+INT*(x2-x1));\n x3(om & issue_mask) = x2(om & issue_mask) + INT*(x2(om & issue_mask) - x1(om & issue_mask));\n end % end extrapolation\n\n while 1 \n om = keep_going & (abs(d3) > -SIG*d0 | f3 > f0+x3.*d0*RHO); % update outer mask\n if ~(any(om) && M > 0)\n break; end\n tog = d3 > 0 | f3 > f0+x3.*d0*RHO; % subinterval toggle\n x4(om&tog) = x3(om&tog); \n f4(om&tog) = f3(om&tog); \n d4(om&tog) = d3(om&tog);\n x2(om&~tog) = x3(om&~tog); \n f2(om&~tog) = f3(om&~tog); \n d2(om&~tog) = d3(om&~tog); \n tog=f4>f0; % interpolation toggle\n x3(om&tog) = x2(om&tog) - (0.5*d2(om&tog).*(x4(om&tog)-x2(om&tog)).^2) ./ (f4(om&tog)-f2(om&tog)-d2(om&tog).*(x4(om&tog)-x2(om&tog))); % quadratic interpolation \n A(om&~tog) = 6*(f2(om&~tog)-f4(om&~tog))./(x4(om&~tog)-x2(om&~tog)) + 3*(d4(om&~tog)+d2(om&~tog)); % cubic interpolation\n B(om&~tog) = 3*(f4(om&~tog)-f2(om&~tog)) - (2*d2(om&~tog)+d4(om&~tog)).*(x4(om&~tog)-x2(om&~tog));\n x3(om&~tog) = x2(om&~tog) + (sqrt(B(om&~tog).*B(om&~tog) - A(om&~tog).*d2(om&~tog).*(x4(om&~tog)-x2(om&~tog)).^2)-B(om&~tog))./A(om&~tog); % num. error possible, ok!\n numprob = isnan(x3) | isinf(x3); % if we had a numerical problem then bisect\n x3(om&numprob) = (x2(om&numprob)+x4(om&numprob))/2;\n\n x3(om) = max(min(x3(om), x4(om)-INT*(x4(om)-x2(om))),x2(om)+INT*(x4(om)-x2(om))); % don't accept too close\n [f3(om) df3(:,om)] = feval(f, X(:,om) + bsxfun(@times,x3(om),s(:,om)), Wz(:,om), Wu(:,om), ccp(:,om), rho); % masked array op\n mask = om & f3 0; % otherwise use steepest direction\n s(:,mask) = -df0(:,mask);\n d0(mask) = -sum(s(:,mask).*s(:,mask)); \n x3(upd) = x3(upd) .* min(RATIO, d3(upd)./(d0(upd)-realmin)); % slope ratio but max RATIO \n ls_failed(upd) = false; % this line search did not fail\n \n upd = ~okay & keep_going;\n X(:,upd) = X0(:,upd);\n f0(upd) = F0(upd);\n df0(:,upd) = dF0(:,upd);\n \n keep_going(upd) = keep_going(upd) & ~ls_failed(upd); % line search failed twice in a row\n % so we give up on these guys\n upd = upd & keep_going;\n if i <= abs(len)\n s(:,upd) = -df0(:,upd);\n d0(:,upd) = -sum(s(:,upd).*s(:,upd)); % try steepest\n x3(upd) = 1./(1-d0(upd));\n ls_failed(upd) = true;\n end\n end\n end\n \n function layout = dialog_layout_defaults(self)\n layout = {'SignalProcessing.Resampling.SamplingRate','SignalProcessing.SpectralSelection.FrequencySpecification', ...\n 'SignalProcessing.EpochExtraction','','Lambdas','WaveDuration','Stepping','ADMMIterations','CgIterations',...\n 'LanczosIterations','NumPatterns','SparsityTraceTradeoff'};\n end\n \n end\nend\n\n% (turn off a few editor warnings because some actual implementations are missing in this file)\n%#ok<*INUSD,*STOUT,*MANU>\n\n\n", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/code/paradigms/in_development/ParadigmPAL.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832058771036, "lm_q2_score": 0.3345894346180164, "lm_q1q2_score": 0.18033808612302601}} {"text": "function MDP = DEM_demo_MDP_rule\n% Demo of active inference for visual salience\n%__________________________________________________________________________\n%\n% This routine simulates a crude form of consciousness using active\n% inference and structure learning to vitiate ignorance or nescience. This\n% entails learning the hyper parameters of causal structure generating\n% outcomes and then using Bayesian model reduction (during sleep) to\n% minimise complexity.\n%\n% We first set up an abstract problem in which an agent has to respond\n% according to rules (identify the correct colour depending upon one of\n% three rules that are specified by the colour of a cue in the centre of\n% vision). If the rule is centre, the colour is always green; however, if\n% the colour of the Centre cue is red, the correct colour is on the left\n% (and on the right if the queue is blue). Simulations are provided when\n% the agent knows the rules. This is then repeated in the absence\n% (nescience) of any knowledge about the rules to see if the agent can\n% learn causal structure through Bayesian belief updating of the likelihood\n% array (A).\n%\n% We then consider the improvement in performance (in terms of variational\n% free energy, its constituent parts and performance) following Bayesian\n% model reduction of the likelihood model (heuristically, like slow wave\n% sleep), followed by a restitution of posterior beliefs during fictive\n% active inference (as in REM sleep). Finally, we address the communication\n% of the implicit structure learning to a conspecific or child to\n% demonstrate the improvement under instruction.\n%\n% see also: DEM_demo_MDP_habits.m and spm_MPD_VB_X.m\n%__________________________________________________________________________\n% Copyright (C) 2005 Wellcome Trust Centre for Neuroimaging\n\n% Karl Friston\n% $Id: DEM_demo_MDP_rule.m 7679 2019-10-24 15:54:07Z spm $\n\n% set up and preliminaries\n%==========================================================================\n\n% specify the (rule-based) generative process (environment)\n%==========================================================================\nrng('default')\n\n% prior beliefs about initial states (in terms of counts_: D\n%--------------------------------------------------------------------------\nD{1} = [1 1 1]'; % rule: {'left','centre','right'}\nD{2} = [1 1 1]'; % what: {'red','green','blue'}\nD{3} = [0 0 0 1]'; % where: {'left','centre','right','null'}\nD{4} = [0 0 0 1]'; % report: {'red','green','blue','undecided'}\n\n% probabilistic mapping from hidden states to outcomes: A\n%--------------------------------------------------------------------------\nNf = numel(D);\nNs = zeros(1,Nf);\nfor f = 1:Nf\n Ns(f) = numel(D{f});\nend\nfor f1 = 1:Ns(1) % rule\n for f2 = 1:Ns(2) % correct colour\n for f3 = 1:Ns(3) % location of fixation\n for f4 = 1:Ns(3) % decision\n \n % A{1} what: {'red','green','blue','null'}\n %==========================================================\n if f3 == 4, A{1}(4,f1,f2,f3,f4) = 1; end\n if f3 == 2, A{1}(f1,f1,f2,f3,f4) = 1; end\n if f3 == 1\n if f1 == 1\n A{1}(f2,f1,f2,f3,f4) = 1;\n else\n A{1}(1:3,f1,f2,f3,f4) = 1/3;\n end\n end\n if f3 == 3\n if f1 == 3\n A{1}(f2,f1,f2,f3,f4) = 1;\n else\n A{1}(1:3,f1,f2,f3,f4) = 1/3;\n end\n end\n \n % A{2} where: {'left','centre','right','null'}\n %----------------------------------------------------------\n A{2}(f3,f1,f2,f3,f4) = 1;\n \n % A{3} feedback: {'null','right','wrong'}\n %----------------------------------------------------------\n if f4 == 4,\n A{3}(1,f1,f2,f3,f4) = 1; % undecided\n else\n if f1 == 2 && f4 == 2, A{3}(2,f1,f2,f3,f4) = 1; end % right\n if f1 == 2 && f4 ~= 2, A{3}(3,f1,f2,f3,f4) = 1; end % wrong\n if f1 == 1 && f4 == f2, A{3}(2,f1,f2,f3,f4) = 1; end % right\n if f1 == 1 && f4 ~= f2, A{3}(3,f1,f2,f3,f4) = 1; end % wrong\n if f1 == 3 && f4 == f2, A{3}(2,f1,f2,f3,f4) = 1; end % right\n if f1 == 3 && f4 ~= f2, A{3}(3,f1,f2,f3,f4) = 1; end % wrong\n end\n end\n end\n end\nend\nNg = numel(A);\nfor g = 1:Ng\n No(g) = size(A{g},1);\n A{g} = double(A{g});\nend\n\n% controlled transitions: B{f} for each factor\n%--------------------------------------------------------------------------\nfor f = 1:Nf\n B{f} = eye(Ns(f));\nend\n\n% control states B(3): where {'left','centre','right','null'}\n%--------------------------------------------------------------------------\nfor k = 1:Ns(3)\n B{3}(:,:,k) = 0;\n B{3}(k,:,k) = 1;\nend\n\n% control states B(4): report {'red','green','blue','undecided'}\n%--------------------------------------------------------------------------\nfor k = 1:Ns(4)\n B{4}(:,:,k) = 0;\n B{4}(k,:,k) = 1;\nend\n\n% allowable policies (specified as the next action) U\n%--------------------------------------------------------------------------\nU(1,1,:) = [1 1 1 4]'; % sample left\nU(1,2,:) = [1 1 2 4]'; % sample centre\nU(1,3,:) = [1 1 3 4]'; % sample right\nU(1,4,:) = [1 1 4 1]'; % return to centre and report red\nU(1,5,:) = [1 1 4 2]'; % return to centre and report green\nU(1,6,:) = [1 1 4 3]'; % return to centre and report blue\n\n\n% priors: (utility) C; the agent expects to avoid mistakes\n%--------------------------------------------------------------------------\nfor g = 1:Ng\n C{g} = zeros(No(g),1);\nend\n% and expects itself to make a decision after the fifth observation\n%--------------------------------------------------------------------------\nC{3} = [ 0 0 0 0 -8 -8;\n 0 0 0 0 0 0;\n -4 -4 -4 -4 -4 -4];\n\n% MDP Structure\n%--------------------------------------------------------------------------\nmdp.T = size(C{3},2); % number of moves\nmdp.U = U; % allowable policies\nmdp.A = A; % observation model\nmdp.B = B; % transition probabilities\nmdp.C = C; % preferred outcomes\nmdp.D = D; % prior over initial states\n\nmdp.Aname = {'what','where','feedback'};\nmdp.Bname = {'rule','colour','where','decision'};\n\n% illustrate a single trial\n%==========================================================================\nmdp = spm_MDP_check(mdp);\nMDP = spm_MDP_VB_X(mdp);\n\n% show belief updates (and behaviour)\n%--------------------------------------------------------------------------\nspm_figure('GetWin','Figure 1'); clf\nspm_MDP_VB_trial(MDP);\n\n% illustrate phase-precession and responses\n%--------------------------------------------------------------------------\nspm_figure('GetWin','Figure 2'); clf\nspm_MDP_VB_LFP(MDP,[],1);\n\n% illustrate behaviour\n%--------------------------------------------------------------------------\nsubplot(3,2,3)\nspm_MDP_rule_plot(MDP)\n\n% illustrate a sequence of trials\n%==========================================================================\nclear MDP\n\n% create structure array\n%--------------------------------------------------------------------------\nN = 8;\nfor i = 1:N\n MDP(i) = mdp;\nend\n\n\n% Solve an example sequence under different initial states\n%==========================================================================\nMDP = spm_MDP_VB_X(MDP);\n\n% illustrate behavioural responses and neuronal correlates\n%--------------------------------------------------------------------------\nspm_figure('GetWin','Figure 3'); clf\nspm_MDP_VB_game(MDP);\n\n[F,Fu] = spm_MDP_F(MDP);\n\nsubplot(6,1,4), plot(1:N,F), xlabel('trial'), spm_axis tight, title('Free energy','Fontsize',16)\nsubplot(6,1,5), plot(1:N,Fu), xlabel('trial'), spm_axis tight, title('Confidence','Fontsize',16)\nsubplot(6,1,6), spm_MDP_plot_moves(MDP), spm_axis tight\ntitle('Action ','Fontsize',16), legend({'saccades','hits'})\n\n\n% illustrate phase-amplitude (theta-gamma) coupling\n%--------------------------------------------------------------------------\nspm_figure('GetWin','Figure 4'); clf\nspm_MDP_VB_LFP(MDP);\n\n% illustrate behaviour in more detail\n%--------------------------------------------------------------------------\nspm_figure('GetWin','Figure 5'); clf;\nfor i = 1:min(N,15)\n subplot(5,3,i), spm_MDP_rule_plot(MDP(i));\n axis square\nend\n\n\n% repeat with rule learning\n%==========================================================================\n\n% retain knowledge about the cue but remove knowledge about the rules\n%--------------------------------------------------------------------------\nfor f1 = 1:Ns(1) % rule\n for f2 = 1:Ns(2) % correct colour\n for f3 = 1:Ns(3) % location of fixation\n for f4 = 1:Ns(3) % decision\n \n % A{1} what: {'red','green','blue','null'}\n %==========================================================\n if f3 == 4, a{1}(4,f1,f2,f3,f4) = 128; end\n if f3 == 2, a{1}(f1,f1,f2,f3,f4) = 128; end\n if f3 == 1\n a{1}(1:3,f1,f2,f3,f4) = 1;\n end\n if f3 == 3\n a{1}(1:3,f1,f2,f3,f4) = 1;\n end\n end\n end\n end\nend\n\na{2} = A{2}*128;\na{3} = A{3}*128;\nmda = mdp;\nmda.a = a;\nmda.a0 = a;\n\n% create structure array\n%--------------------------------------------------------------------------\nclear MDP\nN = 32;\nfor i = 1:N\n MDP(i) = mda;\nend\n\n\n% Solve - an example sequence\n%==========================================================================\nrng('default')\nMDP = spm_MDP_VB_X(MDP);\n\n% show responses to a difficult (right) trial before and after learning\n%--------------------------------------------------------------------------\nfor i = 1:N\n s(:,i) = MDP(i).s(:,1);\nend\ni = find(ismember(s(1:2,:)',s(1:2,1)','rows'));\n\nspm_figure('GetWin','Figure 6 - before');\nspm_MDP_VB_LFP(MDP(i(1)),[],2);\nsubplot(3,2,2), set(gca,'YLim',[-.1 1])\nsubplot(3,2,4), set(gca,'YLim',[-.1 .2])\nsubplot(3,2,3), spm_MDP_rule_plot(MDP(i(1)))\ntitle(['trial ' num2str(i(1))],'FontSize',16)\n\nspm_figure('GetWin','Figure 6 - after' );\nspm_MDP_VB_LFP(MDP(i(end)),[],2);\nsubplot(3,2,2), set(gca,'YLim',[-.1 1]);\nsubplot(3,2,4), set(gca,'YLim',[-.1 .2])\nsubplot(3,2,3), spm_MDP_rule_plot(MDP(i(end)))\ntitle(['trial ' num2str(i(end))],'FontSize',16)\n\n% show learning effects in terms of underlying uncertainty\n%--------------------------------------------------------------------------\nspm_figure('GetWin','Figure 7 - before'); clf; spm_MDP_VB_trial(MDP(i(1)));\nspm_figure('GetWin','Figure 7 - after' ); clf; spm_MDP_VB_trial(MDP(i(end)));\n\n\n% illustrate phase-amplitude (theta-gamma) coupling\n%--------------------------------------------------------------------------\nn = min(N,4);\nspm_figure('GetWin','Figure 4a'); clf\nspm_MDP_VB_LFP(MDP(1:n),[],2);\nfor i = 1:n\n subplot(4,n,i + 3*n), spm_MDP_rule_plot(MDP(i));\n axis square\nend\n\n\n% show trial-by-trial measures in terms of free energy terms\n%--------------------------------------------------------------------------\nspm_figure('GetWin','Figure 8'); clf;\nspm_MDP_VB_game(MDP);\n\n\n[F,Fu] = spm_MDP_F(MDP);\n\nsubplot(6,1,4), plot(1:N,F), xlabel('trial'), spm_axis tight, title('Free energy','Fontsize',16)\nsubplot(6,1,5), plot(1:N,Fu), xlabel('trial'), spm_axis tight, title('Confidence','Fontsize',16)\nsubplot(6,1,6), spm_MDP_plot_moves(MDP), spm_axis tight\ntitle('Action ','Fontsize',16), legend({'saccades','hits'})\n\n\n% illustrate Bayesian model reduction\n%--------------------------------------------------------------------------\nOPTIONS.g = 1;\nOPTIONS.f = 2;\nOPTIONS.T = 3;\nOPTIONS.m = @(i,i1,i2,i3,i4) i == i2;\n\nfor n = 1:N\n sdp{n} = spm_MDP_VB_sleep(MDP(n),OPTIONS);\n cor(n) = corr(spm_vec(MDP(n).A{1} > 0),spm_vec(sdp{n}.a{1}) > 0);\nend\n[m,n] = max(cor);\n\nspm_figure('GetWin','Figure 9'); clf; str = sprintf('Sleep (trial %d)',n);\nfor n = n\n subplot(3,2,1), spm_MDP_A_plot(MDP(n).A);\n subplot(3,2,2), spm_MDP_A_plot(MDP(n).a0), title('Before','Fontsize',16)\n subplot(3,2,3), spm_MDP_A_plot(MDP(n).a), title('After', 'Fontsize',16)\n subplot(3,2,4), spm_MDP_A_plot(sdp{n}.a), title(str, 'Fontsize',16)\nend\n\n% return % here for short demo\n\n% Bayesian model reduction with dreaming\n%--------------------------------------------------------------------------\nOPTIONS.o = {MDP.o};\nrdp = spm_MDP_VB_sleep(MDP(n),OPTIONS);\nsdp = sdp{n};\n\n\n% illustrate benefits of sleep (with and without dreaming)\n%==========================================================================\nRDP = MDP(n:end);\nRDP = rmfield(RDP,{'o','u'});\nfor i = 1:length(RDP)\n RDP(i).s = RDP(i).s(:,1);\nend\nSDP = RDP;\nSDP(1).a = sdp.a;\nRDP(1).a = rdp.a;\nSDP = spm_MDP_VB_X(SDP);\nRDP = spm_MDP_VB_X(RDP);\n\n% plot performance and without sleep\n%--------------------------------------------------------------------------\nspm_figure('GetWin','Figure 10'); clf;\n\n[F,Fu] = spm_MDP_F(MDP);\n\nsubplot(4,1,1),plot(1:N,F, ':'), xlabel('trial'), spm_axis tight, hold on\nsubplot(4,1,2),plot(1:N,Fu,':'), xlabel('trial'), spm_axis tight, hold on\n\n% and after SWS sleep\n%--------------------------------------------------------------------------\n[F,Fu] = spm_MDP_F(SDP);\n\nsubplot(4,1,1),plot(n:N,F ,'-.'), xlabel('trial'), spm_axis tight, hold on\nsubplot(4,1,2),plot(n:N,Fu,'-.'), xlabel('trial'), spm_axis tight, hold on\n\n% and after REM sleep\n%--------------------------------------------------------------------------\n[F,Fu] = spm_MDP_F(RDP);\n\nsubplot(4,1,1),plot(n:N,F ,'-'), xlabel('trial'), spm_axis tight, hold on\ntitle('Free energy (with sleep)','Fontsize',16)\nsubplot(4,1,2),plot(n:N,Fu,'-'), xlabel('trial'), spm_axis tight, hold on\ntitle('Confidence (with sleep)','Fontsize',16)\n\n% and correct responses\n%--------------------------------------------------------------------------\nhit = @(MDP) any(MDP.o(3,:) == 2) & ~any(MDP.o(3,:) == 3);\nk = min(Fu);\nhold on\nfor i = 1:numel(RDP)\n j = i + n - 1;\n if hit(SDP(i)), plot(j,k,'hr','MarkerSize',8); end\nend\nfor i = 1:(n - 1)\n if hit(MDP(i)), plot(i,k,'hb','MarkerSize',8); end\nend\nhold off\n\n\n% illustrate the benefits of instruction (communication of model)\n%==========================================================================\n\n% create instructed agent\n%--------------------------------------------------------------------------\nn = 1:16;\nNDP = MDP(n);\nNDP = rmfield(NDP,{'o','u'});\nfor i = 1:length(NDP)\n NDP(i).s = NDP(i).s(:,1);\n NDP(i).a = sdp.a0;\nend\nNDP = spm_MDP_VB_X(NDP);\n\n% plot performance and without received wisdom\n%--------------------------------------------------------------------------\n[F,Fu] = spm_MDP_F(MDP(n));\n\nsubplot(4,2,5),plot(n,F ,':'), xlabel('trial'), spm_axis tight, hold on\nsubplot(4,2,6),plot(n,Fu,':'), xlabel('trial'), spm_axis tight, hold on\n\n% and after instruction\n%--------------------------------------------------------------------------\n[F,Fu] = spm_MDP_F(NDP(n));\nk = min(Fu);\n\nsubplot(4,2,5),plot(n,F), xlabel('trial'), spm_axis tight\ntitle('Free energy (instruction)','Fontsize',16)\nsubplot(4,2,6),plot(n,Fu), xlabel('trial'), spm_axis tight\ntitle('Confidence (instruction)','Fontsize',16)\n\n% and correct responses\n%--------------------------------------------------------------------------\nfor i = n\n hold on\n if hit(NDP(i)); plot(i,k,'hr','MarkerSize',8), end\n if hit(MDP(i)); plot(i,k,'hb','MarkerSize',8), end\n hold off\nend\n\n\n% run multiple subjects\n%==========================================================================\nBMR.g = 1;\nBMR.f = 2;\nBMR.T = 3;\nBMR.m = @(i,i1,i2,i3,i4) i == i2;\nOPT.BMR = BMR;\n\nN = 32;\nNs = 64;\nfor m = 1:Ns\n \n % create structure array and solve\n %----------------------------------------------------------------------\n clear MDP OPTIONS\n for i = 1:N\n MDP(i) = mda;\n end\n rng(m)\n MDP = spm_MDP_VB_X(MDP);\n \n % free energy and confidence\n %----------------------------------------------------------------------\n [F,Fu] = spm_MDP_F(MDP);\n Fm(:,m) = F(:);\n Fum(:,m) = Fu(:);\n \n % find run of correct responses\n %----------------------------------------------------------------------\n for i = 1:N\n if hit(MDP(i)); h(i,m) = 1; else, h(i,m) = 0; end\n end\n\n % repeat with BMR\n %----------------------------------------------------------------------\n RDP = MDP;\n RDP = rmfield(RDP,{'u','o'});\n for i = 1:N\n RDP(i).a = mda.a;\n RDP(i).a0 = mda.a0;\n RDP(i).s = RDP(i).s(:,1);\n end\n rng(m)\n RDP = spm_MDP_VB_X(RDP,OPT);\n [F,Fu] = spm_MDP_F(RDP);\n Rm(:,m) = F(:);\n Rum(:,m) = Fu(:);\n \n % look for instances of BMR\n %----------------------------------------------------------------------\n vA = spm_vec(A{1});\n for i = 1:N\n c(i,1) = corr(vA,(spm_vec(RDP(i).a{1}) > 0));\n end\n bmr(:,m) = diff(c);\n \n % preferred locations\n %----------------------------------------------------------------------\n for i = 1:N\n if hit(RDP(i)); r(i,m) = 1; else, r(i,m) = 0; end\n end\n \n % find run of correct responses\n %----------------------------------------------------------------------\n for i = 1:N\n if hit(RDP(i)); r(i,m) = 1; else, r(i,m) = 0; end\n end\n \n % find non-learners\n %----------------------------------------------------------------------\n R = spm_conv(r,2,0);\n H = spm_conv(h,2,0);\n \n % show results\n %----------------------------------------------------------------------\n spm_figure('GetWin','Figure 11');clf\n subplot(4,1,1)\n b = bar(mean(R(:,:),2)); set(b,'EdgeColor','w','FaceColor',[1 1 1]*.0),hold on\n b = bar(mean(H(:,:),2)); set(b,'EdgeColor','w','FaceColor',[1 1 1]*.8),hold off\n xlabel('trial'), ylabel('probability of correct'), axis([1/2 (N + 1/2) 1/3 1]);\n title('Average performance','Fontsize',16)\n \n subplot(4,1,2)\n spm_plot_ci(mean(Rm'),var(Rm')), hold on\n plot(mean(Fm'),'r'), hold off\n xlabel('trial'), ylabel('free energy'); set(gca,'XLim',[1 N])\n title('Average free energy','Fontsize',16)\n \n subplot(4,1,3)\n spm_plot_ci(mean(Rum'),var(Rum')), hold on\n plot(mean(Fum'),'r'), hold off\n xlabel('trial'), ylabel('confidence'); set(gca,'XLim',[1 N])\n title('Average confidence','Fontsize',16)\n \n % show individual performance\n %----------------------------------------------------------------------\n subplot(4,1,4), image(32*(r'))\n xlabel('trial'), ylabel('subject')\n title('Aha moments','Fontsize',16)\n \n % plot model updates\n %----------------------------------------------------------------------\n hold on\n for i = 1:m\n j = find(bmr(:,i) > 0) + 1;\n try, plot(j(1),i,'.m','MarkerSize',32), end\n try, plot(j(2),i,'.r','MarkerSize',32), end\n j = find(bmr(:,i) < 0);\n plot(j, (j - j + i),'.b','MarkerSize',32)\n end\n hold off, drawnow\n \n save paper\n \nend\n\n\nreturn\n\n\n% confidence - negatively over policies\n%--------------------------------------------------------------------------\nfor i = 1:numel(MDP)\n p = MDP(i).R;\n Fu(i) = sum(sum(p.*log(p)));\nend\n\nreturn\n\nfunction spm_MDP_plot_moves(MDP)\nfor i = 1:numel(MDP)\n m(i) = sum(~~diff(MDP(i).u(3,:)));\nend\nh = bar(m); set(h,'EdgeColor','w','FaceColor',[1 1 1]*.9), hold on\n\n% and correct responses\n%--------------------------------------------------------------------------\nhit = @(MDP) any(MDP.o(3,:) == 2) & ~any(MDP.o(3,:) == 3);\nfor i = 1:numel(MDP)\n if hit(MDP(i))\n h = plot(i,0,'hr','MarkerSize',8);\n set(h,'MarkerFaceColor',[1 1/2 0])\n end\nend\nreturn\n\n\nfunction spm_MDP_A_plot(A)\n% assemble key parts of the likelihood array\n%==========================================================================\nfor i = 1:3\n for j = 1:3;\n a{i,j} = squeeze(A{1}(:,i,:,j,4));\n a{i,j} = a{i,j}*diag(1./sum(a{i,j}));\n end\nend\na = spm_cat(a);\nimagesc(a);\ntitle( 'Sample: left - center - right', 'FontSize',16)\nylabel('Rule: left - center - right','FontSize',14)\nxlabel('Correct color', 'FontSize',14)\nset(gca,'XTick',1:9)\nset(gca,'YTick',1:12)\nset(gca,'XTicklabel',repmat(['r','g','b'],[1 3])')\nset(gca,'YTicklabel',repmat(['r','g','b',' '],[1 3])')\naxis image\n\nreturn\n\n\n\n\nfunction spm_MDP_rule_plot(MDP)\n% illustrates visual search graphically\n%==========================================================================\n\n% locations\n%--------------------------------------------------------------------------\nx{1} = [-1 0; 0 1; 1 0; 0 0];\nx{2} = [-1 -1; 0 -1; 1 -1; 0 -2]/2;\ncol = {'r','g','b','c'};\n\n% plot cues\n%--------------------------------------------------------------------------\nif strcmp('replace',get(gca,'Nextplot'))\n \n % plot cues\n %----------------------------------------------------------------------\n s = MDP.s;hold off\n for i = 1:length(MDP.D{3})\n a = MDP.A{1}(:,s(1),s(2),i,1);\n j = find(rand < cumsum(a),1);\n plot(x{1}(i,1),x{1}(i,2),['.',col{j}],'MarkerSize',32), hold on\n end\n \n % plot choices\n %----------------------------------------------------------------------\n for i = 1:length(MDP.D{4})\n a = find(MDP.A{3}(:,s(1),s(2),4,i));\n if a == 2\n plot(x{2}(i,1),x{2}(i,2),['.m'],'MarkerSize',32), hold on\n end\n plot(x{2}(i,1),x{2}(i,2),['.',col{i}],'MarkerSize',16), hold on\n \n end\n axis([-2 2 -2 2]);\n \nend\n\n% Extract and plot eye movements and choice\n%--------------------------------------------------------------------------\nfor i = 1:numel(MDP.o(2,:))\n X(i,:) = x{1}(MDP.o(2,i),:);\nend\nplot(X(:,1),X(:,2),'k')\nfor i = 1:numel(MDP.s(4,:))\n X(i,:) = x{2}(MDP.s(4,i),:);\nend\nplot(X(:,1),X(:,2),'k')\naxis([-2 2 -2 2]);\n\nreturn\n\n\n\n\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/toolbox/DEM/DEM_demo_MDP_rule.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.35220178204788966, "lm_q1q2_score": 0.17885224354419688}} {"text": "function [At,b,c,K,prep,origcoeff] = pretransfo(At,b,c,K,pars)\n\n% [At,b,c,K,prep] = pretransfo(At,b,c,K)\n%\n% PRETRANSFO Checks data and then transforms into internal SeDuMi format.\n%\n% ********** INTERNAL FUNCTION OF SEDUMI **********\n%\n% See also sedumi\n\n% Nearly complete rewrite for SeDumI 1.4\n% Copyright (c) 2013 Michael C. Grant\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% Make sure that all fields exist in K, and verify that they are valid\n% -------------------------------------------------------------------------\n\nif ~isfield(K,'f') || isempty(K.f)\n K.f = 0;\nelseif numel(K.f) ~= 1 || K.f ~= floor(K.f) || K.f < 0 || ~isreal(K.f)\n error('K.f should be nonnegative integer')\nend\nif ~isfield(K,'l') || isempty(K.l)\n K.l = 0;\nelseif K.l ~= floor(K.l) || K.l < 0 || ~isreal(K.l)\n error('K.l should be nonnegative integer')\nend\nif ~isfield(K,'q') || ~nnz(K.q)\n K.q = zeros(1,0);\nelse\n K.q = K.q(:)';\n if any(K.q ~= floor(K.q)) || any(K.q<2) || ~isreal(K.q)\n error('K.q should contain only integers bigger than 1')\n end\nend\nif ~isfield(K,'r') || ~nnz(K.r)\n K.r = zeros(1,0);\nelse\n K.r = K.r(:)';\n if any(K.r ~= floor(K.r)) || any(K.r<3) || ~isreal(K.r)\n error('K.r should contain only integers bigger than 2')\n end\nend\nif ~isfield(K,'s') || ~nnz(K.s)\n K.s = zeros(1,0);\nelse\n K.s = K.s(:)';\n if any(K.s ~= floor(K.s)) || any(K.s<1) || ~isreal(K.s)\n error('K.s should contain only positive integers')\n end\nend\n% As an alternative to the 'scomplex' flag, I've added a 'z' parameter\n% containing a list of Hermitian semidefinite cone sizes. For now, this\n% is just translated to 'scomplex' for you. In the future, we may use\n% this internally *instead* of scomplex or rsdpN.\nif ~isfield(K,'z') || ~nnz(K.z)\n K.z = zeros(1,0);\nelse\n K.z = K.z(:)';\n if any(K.z ~= floor(K.z)) || any(K.z<1) || ~isreal(K.z)\n error('K.z should contain only positive integers')\n end\nend\n\nN_f = K.f;\nN_l = K.l;\nN_fl = N_f + N_l;\nL_q = length(K.q);\nN_q = sum(K.q);\nL_r = length(K.r);\nN_r = sum(K.r);\nN_qr = N_q + N_r;\nL_qr = L_q + L_r;\nL_s = length(K.s);\nL_z = length(K.z);\nL_sz = L_s + L_z;\nN_s = sum((K.s).^2);\nN_z = sum((K.z).^2);\nN_sz = N_s + N_z;\nL_qrsz = L_qr + L_sz;\nN_flqr = N_fl + N_qr;\nN = N_flqr + N_sz;\n\nif ~isfield(K,'ycomplex') || isempty(K.ycomplex)\n K.ycomplex = zeros(1,0);\nelse\n K.ycomplex = sort(K.ycomplex(:))';\n K.ycomplex(find(~diff(K.ycomplex))+1) = [];\n if any(K.ycomplex ~= floor(K.ycomplex)) || any(K.ycomplex<1)\n error('K.ycomplex should contain only positive integers');\n elseif any(K.ycomplex > numel(b))\n error('Elements of K.ycomplex are out of range');\n end\nend\nif ~isfield(K,'xcomplex') || isempty(K.xcomplex)\n K.xcomplex = zeros(1,0);\nelse\n K.xcomplex = sort(K.xcomplex(:))';\n K.xcomplex(find(~diff(K.xcomplex))+1) = [];\n if any(K.xcomplex ~= floor(K.xcomplex)) || any(K.xcomplex<1)\n error('K.xcomplex should contain only positive integers');\n elseif any(K.xcomplex>N_flqr)\n error('Elements of K.xcomplex are out of range');\n end\nend\nif ~isfield(K,'scomplex') || isempty(K.scomplex)\n K.scomplex = zeros(1,0);\nelse\n K.scomplex = sort(K.scomplex(:))';\n K.scomplex(find(~diff(K.scomplex))+1) = [];\n if any(K.scomplex~=floor(K.scomplex)) || any(K.scomplex<1)\n error('K.scomplex should contain only positive integers');\n elseif any(K.scomplex>L_s)\n error('Elements of K.xcomplex are out of range');\n end\nend\nif L_z,\n K.s = [ K.s, K.z ];\n K.scomplex = [ K.scomplex, L_s + 1 : L_sz ];\n K.z = zeros(1,0);\n L_s = L_s + L_z;\n N_s = N_s + N_z;\n L_z = 0; %#ok\n N_z = 0; %#ok\nend\n\n% -------------------------------------------------------------------------\n% Verify the size and validity of At, b, and c\n% N = # variables\n% -------------------------------------------------------------------------\n\n% SeDuMi assumes that if At is not consistent with K but At' is, that the\n% user supplied the transpose of the coefficient matrix. This introduces a\n% rare ambiguity in the case where At happens to be square. Past versions \n% of SeDuMi would not have allowed this, instead rejecting the case where\n% m >= N; however, with complex variables, the situation is not quite as\n% clear, and there may technically be cases where m >= N is acceptable.\n\nif ndims(At) > 2 %#ok\n error('A must be a matrix');\nelseif nnz(isnan(At)) || nnz(isinf(At)),\n error('A contains NaN or Inf');\nelseif size(At,1) == N,\n % nothing\nelseif size(At,2) == N,\n At = At';\nelse\n error('(At,K) size mismatch');\nend\nif all(size(b)>1)\n error('Parameter b must be a vector');\nelseif any(isnan(b)) || any(isinf(b)),\n error('b contains NaN or Inf');\nelseif length(b) ~= size(At,2),\n error('(At,b) size mismatch');\nelse\n b = b(:);\nend\nif all(size(c)>1)\n error('Parameter c must be a vector');\nelseif any(isnan(c)) || any(isinf(c))\n error('c contains NaN or Inf');\nelseif length(c) ~= N\n error('(c,K) size mismatch');\nelse\n c = c(:);\nend\n\n% -------------------------------------------------------------------------\n% Save the standardized data for further use if needed\n% -------------------------------------------------------------------------\n\nif isfield(pars,'errors') && pars.errors==1\n origcoeff.At=At;\n origcoeff.c=c;\n origcoeff.b=b;\n origcoeff.K=K;\nelse\n origcoeff=[];\nend\n\n% -------------------------------------------------------------------------\n% Flag diagonal SDP blocks for removal\n% -------------------------------------------------------------------------\n\n% There is some serious MATLAB trickery here (if I do say so myself) that\n% merits explanation. \"spattern\" contains the indices of symbolically \n% nonzero elements of the dual variable z = c - At * y. This is a single\n% vector across all LMI constraints, so \"sblk\" tells us which indices \n% belong to which constraints. The \"rem\" statement is what determines if\n% a particular element is off-diagonal. If there is even one off-diagonal\n% element in an SDP, then its corresponding element of \"sdiag\" is false.\n%\n% This new version of the analysis replaces the old preprocessSDP(), and\n% seems inexpensive enough to apply to all LMIs regardless of size/count.\n% The previous version was applied more sparingly.\n%\n% In theory one could do a more complex analysis of the block structure of\n% an LMI, potentially breaking a larger into smaller ones. But this would\n% likely be significantly more expensive.\n\nif L_s && ( ~isfield(pars,'sdp') || pars.sdp ),\n ssiz = (K.s).^2;\n strt = cumsum([1,ssiz(1:end-1)]);\n sblk = zeros(1,N_s);\n sblk(strt) = 1;\n sblk = cumsum(sblk);\n spattern = find(c(N_flqr+1:N)~=0|any(At(N_flqr+1:N,:),2))';\n sblk = sblk(spattern);\n sblk = sblk(rem(spattern-strt(sblk),K.s(sblk)+1)~=0);\n sdiag = true(1,L_s);\n sdiag(sblk) = false;\nelse\n % Even if we disable SDP processing, we're going to move 1x1 SDPs into\n % the nonnegative variable block. It just doesn't make sense to deploy\n % all of that SDP machinery for nonnegative variables.\n sdiag = K.s == 1;\nend\n\n% -------------------------------------------------------------------------\n% Handle K.ycomplex by splitting apart the complex constraints into pairs\n% of real constraints\n% -------------------------------------------------------------------------\n\nif ~isempty(K.ycomplex)\n b = [ real(b) ; imag(b(K.ycomplex)) ];\n At = [ At, 1j * At(:,K.ycomplex) ];\nelse\n b = real(b);\nend\n\n% -------------------------------------------------------------------------\n% Find the locations of the the complex data, so we can convert into\n% SeDuMi's internal format, which uses only MATLAB's real representation.\n% -------------------------------------------------------------------------\n% Strictly speaking, nonnegative variables, the first variable in a Lorentz \n% cone, and the first two variables in a rotated Lorentz cone are real. But\n% But SeDuMi has allowed them all to be specified as complex; the imaginary\n% portions are interpreted as free variables. We have kept that behavior.\n\n% This code replaces whichcpx.c in its entirety. It actually fixes a bug in\n% rotated Lorentz cone handling that was probably never exercised.\nif isempty(K.xcomplex) && isempty(K.scomplex),\n K.fcplx = zeros(1,0);\n K.qcplx = zeros(1,0);\n K.rcplx = zeros(1,0);\n scplx = false(1,L_s);\n sreal = ~sdiag;\n K.rsdpN = L_s;\n N_fc = 0;\n K.cdim = 0;\nelse\n xc = K.xcomplex;\n tt = xc <= N_fl;\n K.fcplx = xc(tt);\n xc = xc(~tt) - N_fl;\n tt = xc <= N_q;\n K.qcplx = xc(tt);\n xc = xc(~tt) - N_q;\n tt = xc <= N_r;\n K.rcplx = xc(tt);\n if ~isempty(K.qcplx),\n ndxs = cumsum([1,K.q(1:end-1)]);\n t2 = any(bsxfun(@eq,K.qcplx,ndxs'),1);\n K.fcplx = [ K.fcplx, K.qcplx(t2) + N_fl ];\n K.qcplx(t2) = [];\n t2 = sum(bsxfun(@gt,K.qcplx,ndxs'),1);\n K.q = K.q + full(sparse(1,t2,1,1,L_q));\n K.qcplx = K.qcplx + (1:length(K.qcplx));\n N_q = N_q + length(K.qcplx);\n end\n if ~isempty(K.rcplx),\n ndxs = cumsum([1,K.r(1:end-1)]);\n t2 = any(bsxfun(@eq,K.rcplx,[ndxs,ndxs+1]'),1);\n K.fcplx = [ K.fcplx, K.rcplx(t2) + N_fl + N_q ];\n K.rcplx(t2) = [];\n t2 = sum(bsxfun(@gt,K.rcplx,ndxs'),1);\n K.r = K.r + full(sparse(1,t2,1,1,L_r));\n % This 2*t2 offset is required because QR makes two accesses\n % each of the first two elements of a rotated Lorentz cone.\n K.rcplx = K.rcplx + (1:length(K.rcplx)) + 2 * t2;\n N_r = N_r + length(K.rcplx);\n end\n N_fc = length(K.fcplx);\n N_f = N_f + N_fc;\n N_fl = N_f + N_l; %#ok\n N_qr = N_q + N_r;\n scplx = false(1,L_s);\n scplx(K.scomplex&~sdiag) = true;\n sreal = ~scplx & ~sdiag;\n K.rsdpN = nnz(sreal);\n K.cdim = length(K.xcomplex) + sum(K.s(scplx).^2);\nend\n\n% -------------------------------------------------------------------------\n% We have significantly rewritten this section of the code. This section\n% constructs a sparse matrix that represents the following transformations:\n% --- Free variables split into differences of nonnegative variables; OR\n% --- Free variables placed in a Lorentz-cone\n% --- Rotated lorentz cones translated to standard Lorentz cones\n% --- Lorentz cones rearranged to trace block + norm-bound blocks\n% --- Conversion of diagonal SDPs to nonnegative variables\n% --- SDP coefficients moved to the lower triangle for increased sparsity\n% This code replaces the rotlorenz, qreshape, and vectril MEX files.\n% -------------------------------------------------------------------------\n\nnewL = 0;\nnewQ = zeros(1,0);\nii = {}; jj = {}; vv = {};\n\n% Split free variables into the difference of nonnegatives\nif ~isfield( pars, 'free' ) || pars.free == 2 && L_qrsz,\n pars.free = 1;\nend\nif N_f && ~pars.free,\n jt = [ 1 : K.f, K.fcplx ; 1 : K.f, K.fcplx ];\n vt = [ ones(1,K.f), -1j*ones(1,N_fc) ; -ones(1,K.f), 1j*ones(1,N_fc) ];\n ii{end+1} = 1 : 2 * N_f;\n jj{end+1} = jt(:)';\n vv{end+1} = vt(:)';\n newL = 2 * N_f;\n prep.freeL = N_f;\nend\n\n% Copy nonnegative variables without change\nif K.l,\n ii{end+1} = newL + 1 : newL + K.l;\n jj{end+1} = K.f + 1 : K.f + K.l;\n vv{end+1} = ones(1,K.l);\n newL = newL + K.l;\nend\n\n% Convert diagonal SDPs to nonnegative variables\nif any(sdiag),\n dsize = K.s(sdiag);\n sdpL = sum(dsize);\n prep.sdiag = dsize;\n jstrt = cumsum([N_flqr+1,K.s(1:end-1).^2]);\n jstrt = jstrt(sdiag);\n istrt = cumsum([1,dsize(1:end-1)]);\n dsize = dsize + 1;\n dblks = cumsum(full(sparse(1,istrt,1,1,sdpL)));\n ii{end+1} = newL + 1 : newL + sdpL;\n jj{end+1} = jstrt(dblks) + dsize(dblks) .* ( ( 1 : sdpL ) - istrt(dblks) );\n vv{end+1} = ones(1,sdpL);\n newL = newL + sdpL;\nend\n\n% Stuff free variables into a Lorentz cone\ntr_off = newL;\nnb_off = newL + L_qr;\nif N_f && pars.free,\n tr_off = tr_off + 1;\n nb_off = nb_off + 1;\n ii{end+1} = nb_off + 1 : nb_off + N_f;\n jj{end+1} = [ 1 : K.f, K.fcplx ];\n vv{end+1} = [ ones(1,K.f), -1j*ones(1,N_fc) ];\n nb_off = nb_off + K.f;\n newQ = N_f + 1;\nend\n\n% Rearrange Lorentz cones to trace block + norm-bound blocks\nif N_q,\n ndxs = cumsum([1,K.q(1:end-1)]);\n it = zeros(1,N_q);\n it(ndxs) = tr_off + 1 : tr_off + L_q;\n it(it==0) = nb_off + 1 : nb_off + ( N_q - L_q );\n jt = K.f + K.l + 1 : K.f + K.l + N_q;\n vt = ones(1,N_q);\n if ~isempty(K.qcplx),\n jt = jt - cumsum(full(sparse(1,K.qcplx,1,1,N_q)));\n vt(K.qcplx) = -1j;\n end\n ii{end+1} = it(:)';\n jj{end+1} = jt;\n vv{end+1} = vt;\n tr_off = tr_off + L_q;\n nb_off = nb_off + N_q - L_q;\nend\n\n% Transform rotated Lorentz cones to standard Lorentz cones, and rearrange\n% to trace block + norm-bound blocks.\nif N_r,\n ndxr = cumsum([1,K.r(1:end-1)]);\n ndxp = ndxr + 2*(0:L_r-1); \n it = zeros(1,N_r+2*L_r);\n it(ndxp) = tr_off + 1 : tr_off + L_r;\n it(ndxp+1) = -1;\n it(ndxp+2) = it(ndxp);\n it(it==0) = nb_off + 1 : nb_off + ( N_r - L_r );\n it(ndxp+1) = it(ndxp+3);\n jt = [ K.f + K.l + N_q + 1, ones(1,N_r+2*L_r-1) ];\n jt([ndxp+1,ndxp+3]) = 0;\n vt = ones(1,N_r+2*L_r);\n vt([ndxp,ndxp+1,ndxp+2]) = sqrt(0.5);\n vt(ndxp+3) = -sqrt(0.5);\n if ~isempty(K.rcplx),\n jt(K.rcplx) = 0;\n vt(K.rcplx) = -1j;\n end\n ii{end+1} = it;\n jj{end+1} = cumsum(jt);\n vv{end+1} = vt;\n nb_off = nb_off + N_r - L_r;\nend\n\n% Replace non-diagonal real SDP coefficients with tril(X) + tril(X',-1).\n% This cuts the number of nonzeros approximately in half.\nif K.rsdpN,\n dsize = K.s(sreal);\n sdpL = sum(dsize.^2);\n jstrt = cumsum([N_flqr+1,K.s(1:end-1).^2]);\n jstrt = jstrt(sreal);\n istrt = cumsum([1,dsize(1:end-1).^2]);\n dblks = cumsum(full(sparse(1,istrt,1,1,sdpL)));\n istrt = istrt + nb_off;\n dsize = dsize(dblks);\n istrt = istrt(dblks);\n jndxs = ( nb_off + 1 : nb_off + sdpL ) - istrt;\n cols = floor(jndxs ./ dsize);\n rows = jndxs - dsize .* cols;\n ii{end+1} = max(rows,cols) + min(rows,cols) .* dsize + istrt;\n jj{end+1} = jndxs + jstrt(dblks);\n vv{end+1} = ones(1,sdpL);\n nb_off = nb_off + sdpL;\n clear dsize jstrt istrt dblks jndxs rows cols\nend\n\n% Replace Hermitian SDP coefficients with tril(X) + tril(X',-1). This one's\n% a bit trickier because we have the real and complex values interleaved, \n% and the imaginary values along the diagonal are zero.\nif K.rsdpN < length(K.s),\n dsize = K.s(scplx);\n jsize = dsize .^ 2;\n sdpL = 2 * sum(jsize);\n jstrt = cumsum([N_flqr+1,K.s(1:end-1).^2]);\n jstrt = jstrt(scplx);\n bstrt = cumsum([1,2*jsize(1:end-1)]);\n dblks = cumsum(full(sparse(1,bstrt,1,1,sdpL)));\n istrt = bstrt + nb_off;\n dsize = dsize(dblks);\n istrt = istrt(dblks);\n bndxs = ( nb_off + 1 : nb_off + sdpL ) - istrt;\n cols = floor( bndxs ./ dsize );\n rows = bndxs - dsize .* cols;\n imgv = cols >= dsize;\n cols = cols - imgv .* dsize;\n indxs = max(rows,cols) + min(rows,cols) .* dsize + imgv .* jsize(dblks) + istrt;\n vals = ( 1 - 2 * ( cols > rows ) ) .* ( 1 - ( 1 + 1j ) .* imgv );\n keep = ~imgv | ( rows ~= cols );\n jndxs = rows + cols .* dsize + jstrt(dblks);\n ii{end+1} = indxs(keep);\n jj{end+1} = jndxs(keep);\n vv{end+1} = vals(keep);\n clear dsize jsize jstrt bstrt istrt bndxs rows cols vals imgv keep\nend\n\n% Update free, nonnegative, and Lorentz variable counts\nK.f = 0;\nK.l = newL;\nK.q = [ newQ, K.q, K.r ];\nK.r = zeros(0,1);\nK.s = [ K.s(:,~scplx&~sdiag), K.s(scplx&~sdiag) ];\nK.rsdpN = nnz(~scplx&~sdiag);\nK.N = K.l + sum(K.q) + sum(K.s(1:K.rsdpN).^2)+2*sum(K.s(K.rsdpN+1:end).^2);\n\n% Create the artificial (x0,z0) variable for the self-dual model by\n% appending a zero row to At and c. This is accomplished in QR by adding\n% 1 to all of the row indices created above.\nK.N = K.N + 1;\nK.l = K.l + 1;\nK.m = length(b);\n\n% Transform At, c\n% The transformation matrix QR does not satisfy QR'*QR=I. But it does, in \n% fact, serve as a reverse transformation:\n% --- For Lorentz cones, QR applies a permutation; QR' reverses it.\n% --- For rotated Lorentz cones, QR applies a unitary, self-adjoint\n% rotation on the first two variables, so QR' reverses it.\n% --- For split free variables, QR creates the positive and negative\n% parts; QR' combines them back together.\n% --- For free variables placed in a Lorentz cone, QR moves them to the\n% Lorentz cone block, adding an extra epigraph variable. QR' moves\n% them back and drops the extra variable.\n% --- For semidefinte cones, QR adds the strict upper triangle to the\n% strict lower triangle; QR' copies the strict lower triangle to the\n% strict upper triangle, ensuring symmetry.\n% --- QR adds a row for the self-dual variable; QR' removes it.\n[dummy,ndxs] = sort(cellfun(@(x) x(1),jj)); %#ok\nQR = sparse( horzcat(ii{ndxs})+1, horzcat(jj{ndxs}), horzcat(vv{ndxs}), K.N, length(c) );\nAt = real( sparse( QR * At ) );\nc = real( sparse( QR * c ) );\nb = sparse( b );\nprep.QR = QR;\nclear ii jj vv\n\n% -------------------------------------------------------------------------\n% Now K has field K.{l,q,s}\n% Generate a more detailed description of cone K:\n% Let K.blkstart(i):K.blkstart(i+1)-1 give the index range of block i.\n% Compute maxN=max(order), len=sum(order) for LORENTZ, real PSD, herm PSD\n% yields: K.{l,q,s,rsdpN,blkstart,rLen,hLen,qMaxn,rMaxn,hMaxn}\n% -------------------------------------------------------------------------\nKsr = K.s(1:K.rsdpN);\nKsc = K.s(K.rsdpN+1:end);\nK.blkstart = cumsum([K.l+1,length(K.q)+length(K.r),K.q-1,Ksr.^2,2*Ksc.^2]);\nK.rLen = sum(Ksr);\nK.hLen = sum(Ksc);\nK.qMaxn = max([0,K.q]);\nK.rMaxn = max([0,Ksr]);\nK.hMaxn = max([0,Ksc]);\nK.mainblks = K.blkstart(cumsum([1 1 length(K.q)]));\nK.qblkstart = K.blkstart(2:2+length(K.q)); % Also include blkend\nK.sblkstart = K.blkstart(2+length(K.q):end);\nK.lq = K.mainblks(end)-1;\n", "meta": {"author": "yu-jiang", "repo": "radpbook", "sha": "88b9fa7d0a541099cdd1ac29383c89e087d1d895", "save_path": "github-repos/MATLAB/yu-jiang-radpbook", "path": "github-repos/MATLAB/yu-jiang-radpbook/radpbook-88b9fa7d0a541099cdd1ac29383c89e087d1d895/tools/cvx-w64/cvx/sedumi/pretransfo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.33458945452352534, "lm_q1q2_score": 0.17643454791881116}} {"text": "%% AI Clinician Identifiying MIMIC-III sepsis cohort\n\n% (c) Matthieu Komorowski, Imperial College London 2015-2019\n% as seen in publication: https://www.nature.com/articles/s41591-018-0213-5\n\n% version 16 Feb 19\n% IDENTIFIES THE COHORT OF PATIENTS WITH SEPSIS in MIMIC-III\n\n% PURPOSE:\n% ------------------------------\n% This creates a list of icustayIDs of patients who develop sepsis at some point \n% in the ICU. records charttime for onset of sepsis. Uses sepsis3 criteria\n\n% STEPS:\n% -------------------------------\n% IMPORT DATA FROM CSV FILES\n% FLAG PRESUMED INFECTION\n% PREPROCESSING\n% REFORMAT in 4h time slots\n% COMPUTE SOFA at each time step\n% FLAG SEPSIS\n\n% note: the process generates the same features as the final MDP dataset, most of which are not used to compute SOFA\n% External files required: Reflabs, Refvitals, sample_and_hold (all saved in reference_matrices.mat file)\n\n% This code 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\n\n%% ########################################################################\n% IMPORT ALL DATA\n\ntic\nabx=table2array(readtable('D:/exportdir/abx.csv'));\nculture=table2array(readtable('D:/exportdir/culture.csv'));\nmicrobio=table2array(readtable('D:/exportdir/microbio.csv'));\ndemog=(readtable('D:/exportdir/demog.csv'));\nce010=table2array(readtable('D:/exportdir/ce010000.csv'));\nce1020=table2array(readtable('D:/exportdir/ce1000020000.csv'));\nce2030=table2array(readtable('D:/exportdir/ce2000030000.csv'));\nce3040=table2array(readtable('D:/exportdir/ce3000040000.csv'));\nce4050=table2array(readtable('D:/exportdir/ce4000050000.csv'));\nce5060=table2array(readtable('D:/exportdir/ce5000060000.csv'));\nce6070=table2array(readtable('D:/exportdir/ce6000070000.csv'));\nce7080=table2array(readtable('D:/exportdir/ce7000080000.csv'));\nce8090=table2array(readtable('D:/exportdir/ce8000090000.csv'));\nce90100=table2array(readtable('D:/exportdir/ce90000100000.csv'));\nlabU=[ table2array(readtable('D:/exportdir/labs_ce.csv')) ; table2array(readtable('D:/exportdir/labs_le.csv')) ];\nMV=table2array(readtable('D:/exportdir/mechvent.csv'));\ninputpreadm=table2array(readtable('D:/exportdir/preadm_fluid.csv'));\ninputMV=table2array(readtable('D:/exportdir/fluid_mv.csv'));\ninputCV=table2array(readtable('D:/exportdir/fluid_cv.csv'));\nvasoMV=table2array(readtable('D:/exportdir/vaso_mv.csv'));\nvasoCV=table2array(readtable('D:/exportdir/vaso_cv.csv'));\nUOpreadm=table2array(readtable('D:/exportdir/preadm_uo.csv'));\nUO=table2array(readtable('D:/exportdir/uo.csv'));\ntoc\n\n%% ########################################################################\n% INITIAL DATA MANIPULATIONS\n% #########################################################################\n\nii=isnan(microbio(:,3)); %if charttime is empty but chartdate isn't\nmicrobio(ii,3)=microbio(ii,4); %copy time\nmicrobio( :,4)=[]; %delete chardate\n% Add empty col in microbio (# 3 and #5)\nmicrobio(:,4)=microbio(:,3);\nmicrobio(:,[3 5])=0;\n% Combine both tables for micro events\nbacterio = [microbio ; culture];\n% correct NaNs in DEMOG\ndemog.morta_90(isnan(demog.morta_90))=0;\ndemog.morta_hosp(isnan(demog.morta_hosp))=0;\ndemog.elixhauser(isnan(demog.elixhauser))=0;\n\n% compute normalized rate of infusion\n% if we give 100 ml of hypertonic fluid (600 mosm/l) at 100 ml/h (given in 1h) it is 200 ml of NS equivalent\n% so the normalized rate of infusion is 200 ml/h (different volume in same duration)\ninputMV(:,8)=inputMV(:,7).*inputMV(:,6)./inputMV(:,5);\n\n% fill-in missing ICUSTAY IDs in bacterio\nfor i=1:size(bacterio,1)\nif bacterio(i,3)==0 %if missing icustayid\n o=bacterio(i,4); %charttime\n subjectid=bacterio(i,1);\n hadmid=bacterio(i,2);\n ii=find(demog.subject_id==subjectid);\n jj=find(demog.subject_id==subjectid & demog.hadm_id==hadmid);\n for j=1:numel(ii)\n if o>=demog.intime(ii(j))-48*3600 & o<=demog.outtime(ii(j))+48*3600\n bacterio(i,3)=demog.icustay_id(ii(j));\n elseif numel(ii)==1 %if we cant confirm from admission and discharge time but there is only 1 admission: it's the one!!\n bacterio(i,3)=demog.icustay_id(ii(j));\n end\n end\nend \nend\ntoc\n\n\nfor i=1:size(bacterio,1)\nif bacterio(i,3)==0 %if missing icustayid\n subjectid=bacterio(i,1);\n hadmid=bacterio(i,2);\n jj=find(demog.subject_id==subjectid & demog.hadm_id==hadmid);\n if numel(jj)==1\n bacterio(i,3)=demog.icustay_id(jj);\n end\nend\nend\n\n% fill-in missing ICUSTAY IDs in ABx\n\nfor i=1:size(abx,1)\nif isnan(abx(i,2))\n o=abx(i,3); %time of event\n hadmid=abx(i,1);\n ii=find(demog.hadm_id==hadmid); %row in table demographics\n for j=1:numel(ii)\n if o>=demog.intime(ii(j))-48*3600 & o<=demog.outtime(ii(j))+48*3600\n abx(i,2)=demog.icustay_id(ii(j));\n elseif numel(ii)==1 %if we cant confirm from admission and discharge time but there is only 1 admission: it's the one!!\n abx(i,2)=demog.icustay_id(ii(j));\n end\n end\nend \nend\n\n%% ########################################################################\n% find presumed onset of infection according to sepsis3 guidelines\n% ########################################################################\n\n% METHOD:\n% I loop through all the ABx given, and as soon as there is a sample present\n% within the required time criteria I pick this flag and break the loop.\n\nonset=zeros(100000,3);\n\nfor icustayid=1:100000\n\n ab=abx(abx(:,2)==icustayid+200000,3); %start time of abx for this icustayid\n bact=bacterio(bacterio(:,3)==icustayid+200000,4); %time of sample\n subj_bact=bacterio(bacterio(:,3)==icustayid+200000,1); %subjectid\n \n if ~isempty(ab) & ~isempty(bact) %if we have data for both: proceed\n \n D = pdist2(ab, bact)/3600; %pairwise distances btw antibio and cultures, in hours\n \n for i=1:size(D,1) % looping through all rows of AB given, from early to late\n [M,I] = min(D(i,:)); %minimum distance in this row\n ab1=ab(i); %timestamp of this value in list of antibio\n bact1=bact(I); %timestamp in list of cultures\n \n if M<=24 & ab1<=bact1 %if ab was first and delay < 24h\n onset(icustayid,1)=subj_bact(1); %subject_id\n onset(icustayid,2)=icustayid; % icustay_id\n onset(icustayid,3)=ab1; %onset of infection = abx time\n icustayid\n break\n elseif M<=72 & ab1>=bact1 %elseif sample was first and delay < 72h\n onset(icustayid,1)=subj_bact(1);\n onset(icustayid,2)=icustayid;\n onset(icustayid,3)=bact1; %onset of infection = sample time\n break\n end\n end\n end \nend\ntoc\n\n%sum of records found\nsum(onset(:,3)>0)\n\n\n%% Replacing item_ids with column numbers from reference tables\n\n% replace itemid in labs with column number\n% this will accelerate process later\n\ntic\nfor i=1:size(labU,1)\n[~,locb]=ismember(Reflabs,labU(i,3));\nlabU(i,3)=find(max(locb')');\nend\ntoc\n\n% replace itemid in vitals with col number\n\nfor i=1:size(ce010,1)\n[~,locb]=ismember(Refvitals,ce010(i,3));ce010(i,3)=find(max(locb')');\nend\nfor i=1:size(ce1020,1)\n[~,locb]=ismember(Refvitals,ce1020(i,3));ce1020(i,3)=find(max(locb')');\nend\nfor i=1:size(ce2030,1)\n[~,locb]=ismember(Refvitals,ce2030(i,3));ce2030(i,3)=find(max(locb')');\nend\nfor i=1:size(ce3040,1)\n[~,locb]=ismember(Refvitals,ce3040(i,3));ce3040(i,3)=find(max(locb')');\nend\nfor i=1:size(ce4050,1)\n[~,locb]=ismember(Refvitals,ce4050(i,3));ce4050(i,3)=find(max(locb')');\nend\nfor i=1:size(ce5060,1)\n[~,locb]=ismember(Refvitals,ce5060(i,3));ce5060(i,3)=find(max(locb')');\nend\nfor i=1:size(ce6070,1)\n[~,locb]=ismember(Refvitals,ce6070(i,3));ce6070(i,3)=find(max(locb')');\nend\nfor i=1:size(ce7080,1)\n[~,locb]=ismember(Refvitals,ce7080(i,3));ce7080(i,3)=find(max(locb')');\nend\nfor i=1:size(ce8090,1)\n[~,locb]=ismember(Refvitals,ce8090(i,3));ce8090(i,3)=find(max(locb')');\nend\nfor i=1:size(ce90100,1)\n[~,locb]=ismember(Refvitals,ce90100(i,3));ce90100(i,3)=find(max(locb')');\nend\n\n\n\n%% ########################################################################\n% INITIAL REFORMAT WITH CHARTEVENTS, LABS AND MECHVENT\n% ########################################################################\n\n% gives an array with all unique charttime (1 per row) and all items in columns.\n% ################## IMPORTANT !!!!!!!!!!!!!!!!!!\n% Here i use -48 -> +24 because that's for sepsis3 cohort defintion!!\n% I need different time period for the MDP (-24 -> +48)\n\n\nreformat=NaN(2000000,68); %final table \nqstime=zeros(100000,4);\nwinb4=49; %lower limit for inclusion of data (48h before time flag)\nwinaft=25; % upper limit (24h after)\nirow=1; %recording row for summary table\nh = waitbar(0,'Initializing waitbar...');\n\ntic\nfor icustayid=1:100000\nqst=onset(icustayid,3); %flag for presumed infection\nif qst>0 % if we have a flag\nd1=table2array(demog(demog.icustay_id==icustayid+200000,[11 5])); %age of patient + discharge time\n\nif d1(1)>6574 % if older than 18 years old\n\n waitbar(icustayid/100000,h,icustayid/1000) %moved here to save some time\n% CHARTEVENTS\n if icustayid<10000\n temp=ce010(ce010(:,1)==icustayid+200000,:);\n elseif icustayid>=10000 & icustayid<20000\n temp=ce1020(ce1020(:,1)==icustayid+200000,:);\n elseif icustayid>=20000 & icustayid<30000\n temp=ce2030(ce2030(:,1)==icustayid+200000,:);\n elseif icustayid>=30000 && icustayid<40000\n temp=ce3040(ce3040(:,1)==icustayid+200000,:);\n elseif icustayid>=40000 & icustayid<50000\n temp=ce4050(ce4050(:,1)==icustayid+200000,:);\n elseif icustayid>=50000 & icustayid<60000\n temp=ce5060(ce5060(:,1)==icustayid+200000,:);\n elseif icustayid>=60000 & icustayid<70000\n temp=ce6070(ce6070(:,1)==icustayid+200000,:);\n elseif icustayid>=70000 & icustayid<80000\n temp=ce7080(ce7080(:,1)==icustayid+200000,:);\n elseif icustayid>=80000 & icustayid<90000\n temp=ce8090(ce8090(:,1)==icustayid+200000,:);\n elseif icustayid>=90000\n temp=ce90100(ce90100(:,1)==icustayid+200000,:);\n end\n\nii=temp(:,2)>= qst-(winb4+4)*3600 & temp(:,2)<=qst+(winaft+4)*3600; %time period of interest -4h and +4h\ntemp=temp(ii,:); %only time period of interest\n\n%LABEVENTS\nii=labU(:,1)==icustayid+200000;\ntemp2=labU(ii,:);\nii=temp2(:,2)>= qst-(winb4+4)*3600 & temp2(:,2)<=qst+(winaft+4)*3600; %time period of interest -4h and +4h\ntemp2=temp2(ii,:); %only time period of interest\n\n%Mech Vent + ?extubated\nii=MV(:,1)==icustayid+200000;\ntemp3=MV(ii,:);\nii=temp3(:,2)>= qst-(winb4+4)*3600 & temp3(:,2)<=qst+(winaft+4)*3600; %time period of interest -4h and +4h\ntemp3=temp3(ii,:); %only time period of interest\n\nt=unique([temp(:,2);temp2(:,2); temp3(:,2)]); %list of unique timestamps from all 3 sources / sorted in ascending order\n\nif t\nfor i=1:numel(t)\n \n %CHARTEVENTS\n ii=temp(:,2)==t(i);\n col=temp(ii,3);\n value=temp(ii,4); \n reformat(irow,1)=i; %timestep \n reformat(irow,2)=icustayid;\n reformat(irow,3)=t(i); %charttime\n reformat(irow,3+col)=value;%(locb(:,1)); %store available values\n\n \n %LAB VALUES\n ii=temp2(:,2)==t(i);\n col=temp2(ii,3);\n value=temp2(ii,4);\n reformat(irow,31+col)=value; %store available values\n \n %MV \n ii=temp3(:,2)==t(i);\n if nansum(ii)>0\n value=temp3(ii,3:4);\n reformat(irow,67:68)=value; %store available values\n else\n reformat(irow,67:68)=NaN;\n end\n \n irow=irow+1;\n \nend\n\nqstime(icustayid,1)=qst; %flag for presumed infection / this is time of sepsis if SOFA >=2 for this patient\n%HERE I SAVE FIRST and LAST TIMESTAMPS, in QSTIME, for each ICUSTAYID\nqstime(icustayid,2)=t(1); %first timestamp\nqstime(icustayid,3)=t(end); %last timestamp\nqstime(icustayid,4)=d1(2); %dischargetime\n\nend\nend\nend\nend\ntoc\n\nclose(h);\nreformat(irow:end,:)=[]; %delete extra unused rows\n\n\n%% ########################################################################\n% OUTLIERS \n% ########################################################################\n\n%weight\nreformat=deloutabove(reformat,5,300); %delete outlier above a threshold (300 kg), for variable # 5\n\n%HR\nreformat=deloutabove(reformat,8,250);\n\n%BP\nreformat=deloutabove(reformat,9,300);\nreformat=deloutbelow(reformat,10,0);\nreformat=deloutabove(reformat,10,200);\nreformat=deloutbelow(reformat,11,0);\nreformat=deloutabove(reformat,11,200);\n\n%RR\nreformat=deloutabove(reformat,12,80);\n\n%SpO2\nreformat=deloutabove(reformat,13,150);\nii=reformat(:,13)>100;reformat(ii,13)=100;\n\n%temp\nii=reformat(:,14)>90 & isnan(reformat(:,15));reformat(ii,15)=reformat(ii,14);\nreformat=deloutabove(reformat,14,90);\n\n%interface / is in col 22\n\n% FiO2\nreformat=deloutabove(reformat,23,100);\nii=reformat(:,23)<1;reformat(ii,23)=reformat(ii,23)*100;\nreformat=deloutbelow(reformat,23,20);\nreformat=deloutabove(reformat,24,1.5);\n\n% O2 FLOW\nreformat=deloutabove(reformat,25,70);\n\n%PEEP\nreformat=deloutbelow(reformat,26,0);\nreformat=deloutabove(reformat,26,40);\n\n%TV\nreformat=deloutabove(reformat,27,1800);\n\n%MV\nreformat=deloutabove(reformat,28,50);\n\n%K+\nreformat=deloutbelow(reformat,32,1);\nreformat=deloutabove(reformat,32,15);\n\n%Na\nreformat=deloutbelow(reformat,33,95);\nreformat=deloutabove(reformat,33,178);\n\n%Cl\nreformat=deloutbelow(reformat,34,70);\nreformat=deloutabove(reformat,34,150);\n\n%Glc\nreformat=deloutbelow(reformat,35,1);\nreformat=deloutabove(reformat,35,1000);\n\n%Creat\nreformat=deloutabove(reformat,37,150);\n\n%Mg\nreformat=deloutabove(reformat,38,10);\n\n%Ca\nreformat=deloutabove(reformat,39,20);\n\n%ionized Ca\nreformat=deloutabove(reformat,40,5);\n\n%CO2\nreformat=deloutabove(reformat,41,120);\n\n%SGPT/SGOT\nreformat=deloutabove(reformat,42,10000);\nreformat=deloutabove(reformat,43,10000);\n\n%Hb/Ht\nreformat=deloutabove(reformat,50,20);\nreformat=deloutabove(reformat,51,65);\n\n%WBC\nreformat=deloutabove(reformat,53,500);\n\n%plt\nreformat=deloutabove(reformat,54,2000);\n\n%INR\nreformat=deloutabove(reformat,58,20);\n\n%pH\nreformat=deloutbelow(reformat,59,6.7);\nreformat=deloutabove(reformat,59,8);\n\n%po2\nreformat=deloutabove(reformat,60,700);\n\n%pco2\nreformat=deloutabove(reformat,61,200);\n\n%BE\nreformat=deloutbelow(reformat,62,-50);\n\n%lactate\nreformat=deloutabove(reformat,63,30);\n\n% ####################################################################\n% some more data manip / imputation from existing values\n\n% estimate GCS from RASS - data from Wesley JAMA 2003\nii=isnan(reformat(:,6))&reformat(:,7)>=0;\nreformat(ii,6)=15;\nii=isnan(reformat(:,6))&reformat(:,7)==-1;\nreformat(ii,6)=14;\nii=isnan(reformat(:,6))&reformat(:,7)==-2;\nreformat(ii,6)=12;\nii=isnan(reformat(:,6))&reformat(:,7)==-3;\nreformat(ii,6)=11;\nii=isnan(reformat(:,6))&reformat(:,7)==-4;\nreformat(ii,6)=6;\nii=isnan(reformat(:,6))&reformat(:,7)==-5;\nreformat(ii,6)=3;\n\n\n% FiO2\nii=~isnan(reformat(:,23)) & isnan(reformat(:,24));\nreformat(ii,24)=reformat(ii,23)./100;\nii=~isnan(reformat(:,24)) & isnan(reformat(:,23));\nreformat(ii,23)=reformat(ii,24).*100;\n\n\n%ESTIMATE FiO2 /// with use of interface / device (cannula, mask, ventilator....)\n\nreformatsah=SAH(reformat,sample_and_hold); % do SAH first to handle this task\n\n%NO FiO2, YES O2 flow, no interface OR cannula\nii=find(isnan(reformatsah(:,23))&~isnan(reformatsah(:,25))&(reformatsah(:,22)==0|reformatsah(:,22)==2)); \nreformat(ii(reformatsah(ii,25)<=15),23)=70;\nreformat(ii(reformatsah(ii,25)<=12),23)=62;\nreformat(ii(reformatsah(ii,25)<=10),23)=55;\nreformat(ii(reformatsah(ii,25)<=8),23)=50;\nreformat(ii(reformatsah(ii,25)<=6),23)=44;\nreformat(ii(reformatsah(ii,25)<=5),23)=40;\nreformat(ii(reformatsah(ii,25)<=4),23)=36;\nreformat(ii(reformatsah(ii,25)<=3),23)=32;\nreformat(ii(reformatsah(ii,25)<=2),23)=28;\nreformat(ii(reformatsah(ii,25)<=1),23)=24;\n\n%NO FiO2, NO O2 flow, no interface OR cannula\nii=find(isnan(reformatsah(:,23))&isnan(reformatsah(:,25))&(reformatsah(:,22)==0|reformatsah(:,22)==2)); %no fio2 given and o2flow given, no interface OR cannula\nreformat(ii,23)=21;\n\n%NO FiO2, YES O2 flow, face mask OR.... OR ventilator (assume it's face mask)\nii=find(isnan(reformatsah(:,23))&~isnan(reformatsah(:,25))&(reformatsah(:,22)==NaN|reformatsah(:,22)==1|reformatsah(:,22)==3|reformatsah(:,22)==4|reformatsah(:,22)==5|reformatsah(:,22)==6|reformatsah(:,22)==9|reformatsah(:,22)==10)); \nreformat(ii(reformatsah(ii,25)<=15),23)=75;\nreformat(ii(reformatsah(ii,25)<=12),23)=69;\nreformat(ii(reformatsah(ii,25)<=10),23)=66;\nreformat(ii(reformatsah(ii,25)<=8),23)=58;\nreformat(ii(reformatsah(ii,25)<=6),23)=40;\nreformat(ii(reformatsah(ii,25)<=4),23)=36;\n\n%NO FiO2, NO O2 flow, face mask OR ....OR ventilator\nii=find(isnan(reformatsah(:,23))&isnan(reformatsah(:,25))&(reformatsah(:,22)==NaN|reformatsah(:,22)==1|reformatsah(:,22)==3|reformatsah(:,22)==4|reformatsah(:,22)==5|reformatsah(:,22)==6|reformatsah(:,22)==9|reformatsah(:,22)==10)); %no fio2 given and o2flow given, no interface OR cannula\nreformat(ii,23)=NaN;\n\n%NO FiO2, YES O2 flow, Non rebreather mask\nii=find(isnan(reformatsah(:,23))&~isnan(reformatsah(:,25))&reformatsah(:,22)==7); \nreformat(ii(reformatsah(ii,25)>=10),23)=90;\nreformat(ii(reformatsah(ii,25)>=15),23)=100;\nreformat(ii(reformatsah(ii,25)<10),23)=80;\nreformat(ii(reformatsah(ii,25)<=8),23)=70;\nreformat(ii(reformatsah(ii,25)<=6),23)=60;\n\n%NO FiO2, NO O2 flow, NRM\nii=find(isnan(reformatsah(:,23))&isnan(reformatsah(:,25))&reformatsah(:,22)==7); %no fio2 given and o2flow given, no interface OR cannula\nreformat(ii,23)=NaN;\n\n% update again FiO2 columns\nii=~isnan(reformat(:,23)) & isnan(reformat(:,24));\nreformat(ii,24)=reformat(ii,23)./100;\nii=~isnan(reformat(:,24)) & isnan(reformat(:,23));\nreformat(ii,23)=reformat(ii,24).*100;\n\n%BP\nii=~isnan(reformat(:,9))&~isnan(reformat(:,10)) & isnan(reformat(:,11));\nreformat(ii,11)=(3*reformat(ii,10)-reformat(ii,9))./2;\nii=~isnan(reformat(:,09))&~isnan(reformat(:,11)) & isnan(reformat(:,10));\nreformat(ii,10)=(reformat(ii,9)+2*reformat(ii,11))./3;\nii=~isnan(reformat(:,10))&~isnan(reformat(:,11)) & isnan(reformat(:,9));\nreformat(ii,9)=3*reformat(ii,10)-2*reformat(ii,11);\n\n%TEMP\n%some values recorded in the wrong column\nii=reformat(:,15)>25&reformat(:,15)<45; %tempF close to 37deg??!\nreformat(ii,14)=reformat(ii,15);\nreformat(ii,15)=NaN;\nii=reformat(:,14)>70; %tempC > 70?!!! probably degF\nreformat(ii,15)=reformat(ii,14);\nreformat(ii,14)=NaN;\nii=~isnan(reformat(:,14)) & isnan(reformat(:,15));\nreformat(ii,15)=reformat(ii,14)*1.8+32;\nii=~isnan(reformat(:,15)) & isnan(reformat(:,14));\nreformat(ii,14)=(reformat(ii,15)-32)./1.8;\n\n% Hb/Ht\nii=~isnan(reformat(:,50)) & isnan(reformat(:,51));\nreformat(ii,51)=(reformat(ii,50)*2.862)+1.216;\nii=~isnan(reformat(:,51)) & isnan(reformat(:,50));\nreformat(ii,50)=(reformat(ii,51)-1.216)./2.862;\n\n%BILI\nii=~isnan(reformat(:,44)) & isnan(reformat(:,45));\nreformat(ii,45)=(reformat(ii,44)*0.6934)-0.1752;\nii=~isnan(reformat(:,45)) & isnan(reformat(:,44));\nreformat(ii,44)=(reformat(ii,45)+0.1752)./0.6934;\n\n\n%% ########################################################################\n% SAMPLE AND HOLD on RAW DATA\n% ########################################################################\n\nreformat=SAH(reformat(:,1:68),sample_and_hold);\n\n\n%% ########################################################################\n% DATA COMBINATION\n% ########################################################################\n\n% WARNING: the time window of interest has been defined above (here -48 -> +24)! \n\ntimestep=4; %resolution of timesteps, in hours\nirow=1;\nicustayidlist=unique(reformat(:,2));\nreformat2=nan(size(reformat,1),84); %output array\nh = waitbar(0,'Initializing waitbar...');\nnpt=numel(icustayidlist); %number of patients\n% Adding 2 empty cols for future shock index=HR/SBP and P/F\nreformat(:,69:70)=NaN(size(reformat,1),2);\n\ntic\nfor i=1:npt\n \n icustayid=icustayidlist(i); %1 to 100000, NOT 200 to 300K!\n \n %CHARTEVENTS AND LAB VALUES\n temp=reformat(reformat(:,2)==icustayid,:); %subtable of interest\n beg=temp(1,3); %timestamp of first record\n \n % IV FLUID STUFF\n iv=find(inputMV(:,1)==icustayid+200000); %rows of interest in inputMV\n input=inputMV(iv,:); %subset of interest\n iv=find(inputCV(:,1)==icustayid+200000); %rows of interest in inputCV\n input2=inputCV(iv,:); %subset of interest\n startt=input(:,2); %start of all infusions and boluses\n endt=input(:,3); %end of all infusions and boluses\n rate=input(:,8); %rate of infusion (is NaN for boluses) || corrected for tonicity\n \n pread=inputpreadm(inputpreadm(:,1)==icustayid+200000,2) ;%preadmission volume\n if ~isempty(pread) %store the value, if available\n totvol=nansum(pread);\n waitbar(i/npt,h,i/npt*100) %moved here to save some time\n else\n totvol=0; %if not documented: it's zero\n end\n \n % compute volume of fluid given before start of record!!!\n t0=0;\n t1=beg;\n %input from MV (4 ways to compute)\n infu= nansum(rate.*(endt-startt).*(endt<=t1&startt>=t0)/3600 + rate.*(endt-t0).*(startt<=t0&endt<=t1&endt>=t0)/3600 + rate.*(t1-startt).*(startt>=t0&endt>=t1&startt<=t1)/3600 + rate.*(t1-t0).*(endt>=t1&startt<=t0) /3600);\n %all boluses received during this timestep, from inputMV (need to check rate is NaN) and inputCV (simpler):\n bolus=nansum(input(isnan(input(:,6))& input(:,2)>=t0&input(:,2)<=t1,7)) + nansum(input2(input2(:,2)>=t0&input2(:,2)<=t1,5)); \n totvol=nansum([totvol,infu,bolus]); \n \n %VASOPRESSORS \n iv=find(vasoMV(:,1)==icustayid+200000); %rows of interest in vasoMV\n vaso1=vasoMV(iv,:); %subset of interest\n iv=find(vasoCV(:,1)==icustayid+200000); %rows of interest in vasoCV\n vaso2=vasoCV(iv,:); %subset of interest\n startv=vaso1(:,3); %start of VP infusion\n endv=vaso1(:,4); %end of VP infusions\n ratev=vaso1(:,5); %rate of VP infusion\n \n\n %DEMOGRAPHICS / gender, age, elixhauser, re-admit, died in hosp?, died within\n %48h of out_time (likely in ICU or soon after), died within 90d after admission? \n demogi=find(demog.icustay_id==icustayid+200000); \n dem=[ demog.gender(demogi) ; demog.age(demogi) ;demog.elixhauser(demogi) ; demog.adm_order(demogi)>1 ; demog.morta_hosp(demogi); abs(demog.dod(demogi)-demog.outtime(demogi))<(24*3600*2); demog.morta_90(demogi) ; (qstime(icustayid,4)-qstime(icustayid,3))/3600]; \n \n \n % URINE OUTPUT\n iu=find(UO(:,1)==icustayid+200000); %rows of interest in inputMV\n output=UO(iu,:); %subset of interest\n pread=UOpreadm(UOpreadm(:,1)==icustayid,4) ;%preadmission UO\n if ~isempty(pread) %store the value, if available\n UOtot=nansum(pread);\n else\n UOtot=0;\n end\n % adding the volume of urine produced before start of recording! \n UOnow=nansum(output(output(:,2)>=t0&output(:,2)<=t1,4)); %t0 and t1 defined above\n UOtot=nansum([UOtot UOnow]);\n \n \n for j=0:timestep:79 % -52 until +28 = 80 hours in total\n t0=3600*j+ beg; %left limit of time window\n t1=3600*(j+timestep)+beg; %right limit of time window\n ii=temp(:,3)>=t0 & temp(:,3)<=t1; %index of items in this time period\n if sum(ii)>0\n \n \n %ICUSTAY_ID, OUTCOMES, DEMOGRAPHICS\n reformat2(irow,1)=(j/timestep)+1; %'bloc' = timestep (1,2,3...)\n reformat2(irow,2)=icustayid; %icustay_ID\n reformat2(irow,3)=3600*j+ beg; %t0 = lower limit of time window\n reformat2(irow,4:11)=dem; %demographics and outcomes\n \n \n %CHARTEVENTS and LAB VALUES (+ includes empty cols for shock index and P/F)\n value=temp(ii,:);%records all values in this timestep\n \n % ##################### DISCUSS ADDING STUFF HERE / RANGE, MIN, MAX ETC ################\n \n if sum(ii)==1 %if only 1 row of values at this timestep\n reformat2(irow,12:78)=value(:,4:end);\n else\n reformat2(irow,12:78)=nanmean(value(:,4:end)); %mean of all available values\n end\n \n \n %VASOPRESSORS\n % for CV: dose at timestamps.\n % for MV: 4 possibles cases, each one needing a different way to compute the dose of VP actually administered:\n %----t0---start----end-----t1----\n %----start---t0----end----t1----\n %-----t0---start---t1---end\n %----start---t0----t1---end----\n\n \n %MV\n v=(endv>=t0&endv<=t1)|(startv>=t0&endv<=t1)|(startv>=t0&startv<=t1)|(startv<=t0&endv>=t1);\n %CV\n v2=vaso2(vaso2(:,3)>=t0&vaso2(:,3)<=t1,4);\n v1=nanmedian([ratev(v); v2]);\n v2=nanmax([ratev(v); v2]);\n if ~isempty(v1)&~isnan(v1)&~isempty(v2)&~isnan(v2)\n reformat2(irow,79)=v1; %median of dose of VP\n reformat2(irow,80)=v2; %max dose of VP\n end\n \n %INPUT FLUID\n %input from MV (4 ways to compute)\n infu= nansum(rate.*(endt-startt).*(endt<=t1&startt>=t0)/3600 + rate.*(endt-t0).*(startt<=t0&endt<=t1&endt>=t0)/3600 + rate.*(t1-startt).*(startt>=t0&endt>=t1&startt<=t1)/3600 + rate.*(t1-t0).*(endt>=t1&startt<=t0) /3600);\n %all boluses received during this timestep, from inputMV (need to check rate is NaN) and inputCV (simpler):\n bolus=nansum(input(isnan(input(:,6))& input(:,2)>=t0&input(:,2)<=t1,7)) + nansum(input2(input2(:,2)>=t0&input2(:,2)<=t1,5)); \n %sum fluid given\n totvol=nansum([totvol,infu,bolus]);\n reformat2(irow,81)=totvol; %total fluid given\n reformat2(irow,82)=nansum([infu,bolus]); %fluid given at this step\n \n %UO\n UOnow=nansum(output(output(:,2)>=t0&output(:,2)<=t1,4)); \n UOtot=nansum([UOtot UOnow]);\n reformat2(irow,83)=UOtot; %total UO\n reformat2(irow,84)=nansum(UOnow); %UO at this step\n\n %CUMULATED BALANCE\n reformat2(irow,85)=totvol-UOtot; %cumulated balance\n\n irow=irow+1;\n end\n end\nend\ntoc\n\nreformat2(irow:end,:)=[];\nclose(h);\n\n\n%% ########################################################################\n% CONVERT TO TABLE AND DELETE VARIABLES WITH EXCESSIVE MISSINGNESS\n% ########################################################################\n\ndataheaders=[sample_and_hold(1,:) {'Shock_Index' 'PaO2_FiO2'}]; \ndataheaders=regexprep(dataheaders,'['']','');\ndataheaders = ['bloc','icustayid','charttime','gender','age','elixhauser','re_admission', 'died_in_hosp', 'died_within_48h_of_out_time','mortality_90d','delay_end_of_record_and_discharge_or_death',...\n dataheaders, 'median_dose_vaso','max_dose_vaso','input_total','input_4hourly','output_total','output_4hourly','cumulated_balance'];\n\nreformat2t=array2table(reformat2);\nreformat2t.Properties.VariableNames=dataheaders;\nmiss=sum(isnan(reformat2))./size(reformat2,1);\n\n% if values have less than 70% missing values (over 30% of values present): I keep them\nreformat3t=reformat2t(:,[true(1,11) miss(12:74)<0.70 true(1,11)]) ; \n\n%% ########################################################################\n% HANDLING OF MISSING VALUES & CREATE REFORMAT4T\n% ########################################################################\n\n% Do linear interpol where missingness is low (kNN imputation doesnt work if all rows have missing values)\nreformat3=table2array(reformat3t);\nmiss=sum(isnan((reformat3)))./size(reformat3,1);\nii=miss>0&miss<0.05; %less than 5% missingness\nmechventcol=find(ismember(reformat3t.Properties.VariableNames,{'mechvent'}));\n\nfor i=11:mechventcol-1 % correct col by col, otherwise it does it wrongly\n if ii(i)==1\n reformat3(:,i)=fixgaps(reformat3(:,i));\n end\nend\n\nreformat3t(:,11:mechventcol-1)=array2table(reformat3(:,11:mechventcol-1));\n\n% KNN IMPUTATION - Done on chunks of 10K records.\n\nmechventcol=find(ismember(reformat3t.Properties.VariableNames,{'mechvent'}));\nref=reformat3(:,11:mechventcol-1); %columns of interest\n\ntic\nfor i=1:10000:size(reformat3,1)-9999 %dataset divided in 5K rows chunks (otherwise too large)\n i\n ref(i:i+9999,:)=knnimpute(ref(i:i+9999,:)',1, 'distance','seuclidean')';\nend\n\nref(end-9999:end,:)=knnimpute(ref(end-9999:end,:)',1, 'distance','seuclidean')'; %the last bit is imputed from the last 10K rows\n\ntoc\n\n% I paste the data interpolated, but not the demographics and the treatments\nreformat3t(:,11:mechventcol-1)=array2table(ref); \n\nreformat4t=reformat3t;\nreformat4=table2array(reformat4t);\n\n\n%% ########################################################################\n% COMPUTE SOME DERIVED VARIABLES: P/F, Shock Index, SOFA, SIRS...\n% ########################################################################\n\n% CORRECT GENDER\nreformat4t.gender=reformat4t.gender-1; \n\n%CORRECT AGE > 200 yo\nii=reformat4t.age>150*365.25;\nreformat4t.age(ii)=91.4*365.25;\n\n% FIX MECHVENT\nreformat4t.mechvent(isnan(reformat4t.mechvent))=0;\nreformat4t.mechvent(reformat4t.mechvent>0)=1;\n\n% FIX Elixhauser missing values\nreformat4t.elixhauser(isnan(reformat4t.elixhauser))=nanmedian(reformat4t.elixhauser); %use the median value / only a few missing data points \n\n%vasopressors / no NAN\na=find(ismember(reformat4t.Properties.VariableNames,{'median_dose_vaso'}));\nii=isnan(reformat4(:,a));\nreformat4t(ii,a)=array2table(zeros(sum(ii),1));\na=find(ismember(reformat4t.Properties.VariableNames,{'max_dose_vaso'}));\nii=isnan(reformat4(:,a));\nreformat4t(ii,a)=array2table(zeros(sum(ii),1));\n\n% re-compute P/F with no missing values...\np=find(ismember(reformat4t.Properties.VariableNames,{'paO2'}));\nf=find(ismember(reformat4t.Properties.VariableNames,{'FiO2_1'}));\na=find(ismember(reformat4t.Properties.VariableNames,{'PaO2_FiO2'}));\nreformat4t(:,a)=array2table(reformat4(:,p)./reformat4(:,f)); \n\n%recompute SHOCK INDEX without NAN and INF\np=find(ismember(reformat4t.Properties.VariableNames,{'HR'}));\nf=find(ismember(reformat4t.Properties.VariableNames,{'SysBP'}));\na=find(ismember(reformat4t.Properties.VariableNames,{'Shock_Index'}));\nreformat4(:,a)=reformat4(:,p)./reformat4(:,f); \nreformat4(isinf(reformat4(:,a)),a)=NaN;\nd=nanmean(reformat4(:,a));\nreformat4(isnan(reformat4(:,a)),a)=d; %replace NaN with average value ~ 0.8\nreformat4t(:,a)=array2table(reformat4(:,a));\n\n% SOFA - at each timepoint\n% need (in this order): P/F MV PLT TOT_BILI MAP NORAD(max) GCS CR UO\na=zeros(8,1); % indices of vars used in SOFA\na(1)=find(ismember(reformat4t.Properties.VariableNames,{'PaO2_FiO2'}));\na(2)=find(ismember(reformat4t.Properties.VariableNames,{'Platelets_count'}));\na(3)=find(ismember(reformat4t.Properties.VariableNames,{'Total_bili'}));\na(4)=find(ismember(reformat4t.Properties.VariableNames,{'MeanBP'}));\na(5)=find(ismember(reformat4t.Properties.VariableNames,{'max_dose_vaso'}));\na(6)=find(ismember(reformat4t.Properties.VariableNames,{'GCS'}));\na(7)=find(ismember(reformat4t.Properties.VariableNames,{'Creatinine'}));\na(8)=find(ismember(reformat4t.Properties.VariableNames,{'output_4hourly'}));\ns=table2array(reformat4t(:,a)); \n\np=[0 1 2 3 4];\n\ns1=[s(:,1)>400 s(:,1)>=300 &s(:,1)<400 s(:,1)>=200 &s(:,1)<300 s(:,1)>=100 &s(:,1)<200 s(:,1)<100 ]; %count of points for all 6 criteria of sofa\ns2=[s(:,2)>150 s(:,2)>=100 &s(:,2)<150 s(:,2)>=50 &s(:,2)<100 s(:,2)>=20 &s(:,2)<50 s(:,2)<20 ];\ns3=[s(:,3)<1.2 s(:,3)>=1.2 &s(:,3)<2 s(:,3)>=2 &s(:,3)<6 s(:,3)>=6 &s(:,3)<12 s(:,3)>12 ];\ns4=[s(:,4)>=70 s(:,4)<70&s(:,4)>=65 s(:,4)<65 s(:,5)>0 &s(:,5)<=0.1 s(:,5)>0.1 ];\ns5=[s(:,6)>14 s(:,6)>12 &s(:,6)<=14 s(:,6)>9 &s(:,6)<=12 s(:,6)>5 &s(:,6)<=9 s(:,6)<=5 ];\ns6=[s(:,7)<1.2 s(:,7)>=1.2 &s(:,7)<2 s(:,7)>=2 &s(:,7)<3.5 (s(:,7)>=3.5 &s(:,7)<5)|(s(:,8)<84) (s(:,7)>5)|(s(:,8)<34) ];\n\nnrcol=size(reformat4,2); %nr of variables in data\nreformat4(1,nrcol+1:nrcol+7)=0; \nfor i=1:size(reformat4,1) \n t=max(p(s1(i,:)))+max(p(s2(i,:)))+max(p(s3(i,:)))+max(p(s4(i,:)))+max(p(s5(i,:)))+max(p(s6(i,:))); %SUM OF ALL 6 CRITERIA\n \n if t\n reformat4(i,nrcol+1:nrcol+7)= [max(p(s1(i,:))) max(p(s2(i,:))) max(p(s3(i,:))) max(p(s4(i,:))) max(p(s5(i,:))) max(p(s6(i,:))) t];\n end\nend\n\n% SIRS - at each timepoint | need: temp HR RR PaCO2 WBC \na=zeros(5,1); % indices of vars used in SOFA\na(1)=find(ismember(reformat4t.Properties.VariableNames,{'Temp_C'}));\na(2)=find(ismember(reformat4t.Properties.VariableNames,{'HR'}));\na(3)=find(ismember(reformat4t.Properties.VariableNames,{'RR'}));\na(4)=find(ismember(reformat4t.Properties.VariableNames,{'paCO2'}));\na(5)=find(ismember(reformat4t.Properties.VariableNames,{'WBC_count'}));\ns=table2array(reformat4t(:,a)); \n\ns1=[s(:,1)>=38| s(:,1)<=36]; %count of points for all criteria of SIRS\ns2=[s(:,2)>90 ];\ns3=[s(:,3)>=20|s(:,4)<=32];\ns4=[s(:,5)>=12| s(:,5)<4];\nreformat4(:,nrcol+8)=s1+s2+s3+s4;\n\n% adds 2 cols for SOFA and SIRS, if necessary\nif sum(ismember(reformat4t.Properties.VariableNames,{'SIRS'}))== 0\nreformat4t(:,end+1:end+2)=array2table(0);\nreformat4t.Properties.VariableNames(end-1:end)= {'SOFA','SIRS'}; \nend\n\n% records values\nreformat4t(:,end-1)=array2table(reformat4(:,end-1));\nreformat4t(:,end)=array2table(reformat4(:,end));\n\n\n%% ########################################################################\n% EXCLUSION OF SOME PATIENTS \n% ########################################################################\n\nnumel(unique(reformat4t.icustayid)) %count before\n\n% check for patients with extreme UO = outliers = to be deleted (>40 litres of UO per 4h!!)\na=find(reformat4t.output_4hourly>12000);\ni=unique(reformat4t.icustayid(a));\ni=find(ismember(reformat4t.icustayid,i));\nreformat4t(i,:)=[];\n\n% some have bili = 999999\na=find(reformat4t.Total_bili>10000); \ni=unique(reformat4t.icustayid(a));\ni=find(ismember(reformat4t.icustayid,i));\nreformat4t(i,:)=[];\n\n% check for patients with extreme INTAKE = outliers = to be deleted (>10 litres of intake per 4h!!)\na=find(reformat4t.input_4hourly>10000);\ni=unique(reformat4t.icustayid(a)); % 28 ids\ni=find(ismember(reformat4t.icustayid,i));\nreformat4t(i,:)=[];\n\n\n% #### exclude early deaths from possible withdrawals ####\n% stats per patient\nq=reformat4t.bloc==1;\n% fence_posts=find(q(:,1)==1);\nnum_of_trials=numel(unique(reformat4t.icustayid));%size(fence_posts,1);\na=array2table([reformat4t.icustayid reformat4t.mortality_90d reformat4t.max_dose_vaso reformat4t.SOFA]);\na.Properties.VariableNames={'id','mortality_90d','vaso','sofa'};\nd=grpstats(a,'id','max');\n\n%finds patients who match our criteria\ne=zeros(num_of_trials,1);\nfor i=1:num_of_trials\n if d.max_mortality_90d(i) ==1\n ii=reformat4t.icustayid==d.id(i) & reformat4t.bloc==d.GroupCount(i); %last row for this patient\n e(i)=sum((reformat4t.max_dose_vaso(ii)==0 & d.max_vaso(i)>0.3 & reformat4t.SOFA(ii)>=d.max_sofa(i)/2))>0;\n end\nend\nr=d.id(e==1 & d.GroupCount<20); % ids to be removed\nii=ismember(reformat4t.icustayid,r);\nreformat4t(ii,:)=[];\n\n% exclude patients who died in ICU during data collection period\nii=reformat4t.bloc==1&reformat4t.died_within_48h_of_out_time==1& reformat4t.delay_end_of_record_and_discharge_or_death<24;\nii=ismember(icustayidlist,reformat4t.icustayid(ii));\nreformat4t(ii,:)=[];\n\nnumel(unique(reformat4t.icustayid)) %count after\n\n%% #######################################################################\n% CREATE SEPSIS COHORT\n% ########################################################################\n\n% create array with 1 row per icu admission\n% keep only patients with flagged sepsis (max sofa during time period of interest >= 2)\n% we assume baseline SOFA of zero (like other publications)\n\nsepsis=zeros(30000,5);\nirow=1;\n\ntic\nfor icustayid=1:100000\n ii=find(ismember(reformat4t.icustayid,icustayid));\n if mod(icustayid,10000)==0;disp([num2str(icustayid/1000), ' %']);end\n if ii\n \n sofa=reformat4t.SOFA(ii);\n sirs=reformat4t.SIRS(ii);\n sepsis(irow,1)=icustayid+200000; \n sepsis(irow,2)=reformat4t.mortality_90d(ii(1)); % 90-day mortality\n sepsis(irow,3)=max(sofa);\n sepsis(irow,4)=max(sirs);\n sepsis(irow,5)=qstime(icustayid); %time of onset of sepsis\n irow=irow+1;\n end\nend\ntoc\nsepsis(irow:end,:)=[];\n\nsepsis=array2table(sepsis);\nsepsis.Properties.VariableNames={'icustayid','morta_90d','max_sofa','max_sirs','sepsis_time'};\n\n% delete all non-sepsis\nsepsis(sepsis.max_sofa<2,:)=[];\n\n% final count\nsize(sepsis,1) \n\n%save cohort\nwritetable(sepsis,'sepsis_mimiciii.csv','Delimiter',',');\n", "meta": {"author": "matthieukomorowski", "repo": "AI_Clinician", "sha": "0669f8907e65503641857ca76aa46938641e513f", "save_path": "github-repos/MATLAB/matthieukomorowski-AI_Clinician", "path": "github-repos/MATLAB/matthieukomorowski-AI_Clinician/AI_Clinician-0669f8907e65503641857ca76aa46938641e513f/AIClinician_sepsis3_def_160219.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.33111974622959367, "lm_q1q2_score": 0.17460491340411385}} {"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: battistn@tcnj.edu\n% Date Created: October 8th, 2018\n% Institution: TCNJ\n%\n% This code is capable of creating Lagrangian Structures using:\n% \t1. Springs\n% \t2. Beams (*torsional springs / non-invariant beams *)\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 (battistn@tcnj.edu) know.\n%\n%--------------------------------------------------------------------------------------------------------------------%\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: provides data from previous .vtk information for restarting a\n% simulation that has ended because of power failure, etc.\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [current_time,cter,ctsave,U,V,xLag,yLag,xLag_P,yLag_P] = pass_Back_Data_For_Restart(dt,ctsave,print_dump,path_to_data);\n\n\n% \n% Automated\n%\ncter = ctsave * print_dump; % Total # of time-steps thus far up to and included last data point saved\ncurrent_time = cter * dt; % Current time in simulation when last time-step was saved\n\n\n%\n% Read in LAGRANGIAN data for last and second to last timepoint for U,V,mVelocity,F_Poro, xLag,yLag,xLag_P,yLag_P\n%\n[xLag,yLag,xLag_P,yLag_P] = please_Give_Saved_Lag_Point_Info(ctsave,path_to_data);\n\n%\n% Read in EULERIAN data for last timepoint for U,V\n%\n[U,V] = please_Give_Saved_Eulerian_Info(ctsave,path_to_data);\n\n\n%\n% Update for next iteration (*pretends data from last timepoint was just saved*)\n%\nctsave = ctsave + 1; % Update for next ctsave number (always increases by 1 after data is saved)\ncurrent_time = current_time + dt; % Update for next time-step\ncter = cter + 1; % Update for next time-step\n\ncd ../ % Go back into Example Directory\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: passes back EULERIAN data from last saved timepoint\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [U,V] = please_Give_Saved_Eulerian_Info(ctsave,path_to_data)\n\n % Points to desired data viz_IB2d data file for CURRENT time-step\n if ctsave<10\n numSim = ['000', num2str(ctsave) ];\n elseif ctsave<100\n numSim = ['00', num2str(ctsave) ];\n elseif ctsave<1000\n numSim = ['0', num2str(ctsave)];\n else\n numSim = num2str(ctsave);\n end\n \n % Imports (x,y) grid values and ALL EULERIAN DATA %\n % DEFINITIONS \n % x: x-grid y: y-grid\n % Omega: vorticity P: pressure\n % uMag: mag. of velocity \n % uX: mag. of x-Velocity uY: mag. of y-Velocity \n % U: x-directed velocity V: y-directed velocity\n % Fx: x-directed Force Fy: y-directed Force\n %\n % Note: U(j,i): j-corresponds to y-index, i to the x-index\n %\n % \n Eulerian_Flags(1) = 0; % OMEGA\n Eulerian_Flags(2) = 0; % PRESSURE\n Eulerian_Flags(3) = 0; % uMAG\n Eulerian_Flags(4) = 0; % uX (mag. x-component of velocity)\n Eulerian_Flags(5) = 0; % uY (mag. x-component of velocity)\n Eulerian_Flags(6) = 1; % uVEC (vector components of velocity: U,V)\n Eulerian_Flags(7) = 0; % Fx (x-component of force )\n Eulerian_Flags(8) = 0; % Fy (y-component of force)\n %\n [~,~,~,~,~,~,~,U,V,~,~] = import_Eulerian_Data(path_to_data,numSim,Eulerian_Flags);\n\n % TURNS OUT UNNECESSARY\n %U = U'; % For IB2d convention from .vtk\n %V = V'; % For IB2d convention from .vtk \n \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: passes back LAGRANGIAN data from last two saved timepoints\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [xLag,yLag,xLag_P,yLag_P] = please_Give_Saved_Lag_Point_Info(ctsave,path_to_data)\n\n iP = ctsave - 1; % Previous time-point\n\n % Points to desired data viz_IB2d data file for CURRENT time-step\n if ctsave<10\n numSim = ['000', num2str(ctsave) ];\n elseif ctsave<100\n numSim = ['00', num2str(ctsave) ];\n elseif ctsave<1000\n numSim = ['0', num2str(ctsave)];\n else\n numSim = num2str(ctsave);\n end\n\n % Points to desired data viz_IB2d data file for PREVIOUS time-step data\n if iP<10\n numSim_Prev = ['000', num2str(iP) ];\n elseif iP<100\n numSim_Prev = ['00', num2str(iP) ];\n elseif iP<1000\n numSim_Prev = ['0', num2str(iP)];\n else\n numSim_Prev = num2str(iP);\n end\n \n % Imports immersed boundary positions %\n [xLag,yLag] = give_Lag_Positions(path_to_data,numSim);\n [xLag_P,yLag_P] = give_Lag_Positions(path_to_data,numSim_Prev);\n \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: gives (x,y) positions of the immersed boundary at a single step\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [xLag,yLag] = give_Lag_Positions(path,numSim)\n\n[xLag,yLag] = read_Lagrangian_Data_From_vtk(path,numSim);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: Reads in (x,y) positions of the immersed boundary from .vtk\n% format\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [xLag,yLag] = read_Lagrangian_Data_From_vtk(path,simNums)\n\n\ncd(path);\n\nfilename = ['lagsPts.' num2str(simNums) '.vtk']; % desired lagsPts.xxxx.vtk file\n\nfileID = fopen(filename);\nif ( fileID== -1 )\n error('\\nCANNOT OPEN THE FILE!');\nend\n\nstr = fgets(fileID); %-1 if eof\nif ~strcmp( str(3:5),'vtk');\n error('\\nNot in proper VTK format');\nend\n\n% read in the header info %\nstr = fgets(fileID);\nstr = fgets(fileID);\nstr = fgets(fileID);\nstr = fgets(fileID);\nstr = fgets(fileID); % Up to white space in previous lagsPts.X files (pre June 2021)\n\n% Check whether VTK file has time info. This is a VTK file with time, \n% need to read the next 3 lines to have read in appropriate\n% number of header lines.\nif ~strcmp( str(1), 'P')\n\tstr = fgets(fileID);\n str = fgets(fileID);\n str = fgets(fileID);\nend\n\n \n% stores # of Lagrangian Pts. as stated in .vtk file\nnumLagPts = sscanf(str,'%*s %f %*s',1); \n\n% read in the vertices %\n[mat,count] = fscanf(fileID,'%f %f %f',3*numLagPts);\nif count ~= 3*numLagPts\n error('\\nProblem reading in Lagrangian Pts.'); \nend\n\nmat = reshape(mat, 3, count/3); % Reshape vector -> matrix (every 3 entries in vector make into matrix row)\nvertices = mat'; % Store vertices in new matrix\n\nfclose(fileID); % Closes the data file.\n\nxLag = vertices(:,1); % x-Lagrangian Pts.\nyLag = vertices(:,2); % y-Lagrangian Pts.\n\n%---------------------------------------------------------------\n% NEEDS TO BE COMMENTED OUT!\n% (when compared to other file in data analysis toolbox)\n%---------------------------------------------------------------\n%cd ..; % Change directory back to ../viz_IB2d/ directory\n\nclear mat str filename fileID count;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: imports all Eulerian Data at a single step\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [x,y,Omega,P,uMag,uX,uY,U,V,Fx,Fy] = import_Eulerian_Data(path,numSim,Eulerian_Flags)\n\n %\n % EULERIAN FLAGS FOR WHAT GETS SPIT OUT %\n % \n %Eulerian_Flags(1): OMEGA\n %Eulerian_Flags(2): PRESSURE\n %Eulerian_Flags(3): uMAG\n %Eulerian_Flags(4): uX (mag. x-component of velocity)\n %Eulerian_Flags(5): uY (mag. x-component of velocity)\n %Eulerian_Flags(6): uVEC (x,y-components of velocity: U,V)\n %Eulerian_Flags(7): Fx (x-component of force )\n %Eulerian_Flags(8): Fy (y-component of force)\n %\n \n%analysis_path = pwd\n \n% read in Vorticity %\nif Eulerian_Flags(1)\n strChoice = 'Omega'; first = 1;\n [Omega,x,y] = read_Eulerian_Data_From_vtk(path,numSim,strChoice,first);\nelse\n Omega=[];\nend\n\n\n% read in Pressure %\nif Eulerian_Flags(2)\n strChoice = 'P'; first = 1;\n [P,x,y] = read_Eulerian_Data_From_vtk(path,numSim,strChoice,first);\nelse\n P=[];\nend\n\n\n% read in Velocity Magnitude %\nif Eulerian_Flags(3)\n strChoice = 'uMag'; first = 1;\n [uMag,x,y] = read_Eulerian_Data_From_vtk(path,numSim,strChoice,first);\nelse\n uMag=[];\nend\n\n% read in x-directed Velocity Magnitude %\nif Eulerian_Flags(4)\n strChoice = 'uX'; first = 1;\n [uX,x,y] = read_Eulerian_Data_From_vtk(path,numSim,strChoice,first);\nelse\n uX=[];\nend\n\n% read in y-directed Velocity Magnitude %\nif Eulerian_Flags(5)\n strChoice = 'uY'; first = 1;\n [uY,x,y] = read_Eulerian_Data_From_vtk(path,numSim,strChoice,first);\nelse\n uY=[];\nend\n\n% read in x-directed Forces %\nif Eulerian_Flags(7)\n strChoice = 'Fx'; first = 1;\n [Fx,x,y] = read_Eulerian_Data_From_vtk(path,numSim,strChoice,first);\nelse\n Fx=[];\nend\n\n% read in y-directed Forces %\nif Eulerian_Flags(8)\n strChoice = 'Fy'; first = 1;\n [Fy,x,y] = read_Eulerian_Data_From_vtk(path,numSim,strChoice,first);\nelse\n Fy=[];\nend\n\n% read in Velocity Field %\nif Eulerian_Flags(6)\n [U,V] = read_Eulerian_Velocity_Field_vtk(path,numSim);\nelse\n U=[];\n V=[];\nend\n\n% Default for x,y values\nif max(Eulerian_Flags([1:5,7,8]))==0\n x=[];\n y=[];\nend\n\n%cd(analysis_path);\n\nclear analysis_path;\n\nclear strChoice first;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: Reads in the velocity data field from .vtk format\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%s\n\nfunction [U,V] = read_Eulerian_Velocity_Field_vtk(path,simNums)\n\nanalysis_path = pwd; % Store path to analysis folder!\n\ncd(path);\n\nfilename = ['u.' num2str(simNums) '.vtk']; % desired EULERIAN-DATA.xxxx.vtk file\n\nfileID = fopen(filename);\nif ( fileID== -1 )\n error('\\nCANNOT OPEN THE FILE!');\nend\n\nstr = fgets(fileID); %-1 if eof\nif ~strcmp( str(3:5),'vtk')\n error('\\nNot in proper VTK format');\nend\n\n% read in the header info %\nstr = fgets(fileID);\nstr = fgets(fileID);\nstr = fgets(fileID);\nstr = fgets(fileID);\nstr = fgets(fileID);\n\n% Check whether VTK file has time info. This is a VTK file with time, \n% need to read the next 3 lines to have read in appropriate\n% number of header lines.\nif ~strcmp( str(1:3), 'DIM')\n\tstr = fgets(fileID);\n str = fgets(fileID);\n str = fgets(fileID);\nend\n\n% Store grid info\nNx = sscanf(str,'%*s %f %*f %*s',1);\nNy = sscanf(str,'%*s %*f %f %*s',1);\n\n\n% bypass lines in header %\nstr = fgets(fileID);\nstr = fgets(fileID);\nstr = fgets(fileID);\nstr = fgets(fileID);\nstr = fgets(fileID);\nstr = fgets(fileID);\nstr = fgets(fileID);\n\n\n% get formatting for reading in data from .vtk in fscanf %\nstrVec = '%f';\nfor i=2:3*Nx\n strVec = [strVec ' %f'];\nend\n\n% read in the vertices %\n[e_Data,count] = fscanf(fileID,strVec,3*Nx*Ny);\nif count ~= 3*Nx*Ny\n error('Problem reading in Eulerian Data.'); \nend\n\n% reshape the matrix into desired data type %\ne_Data = reshape(e_Data, 3, count/3); % Reshape (3*Nx*Nx,1) vector to (Nx*Nx,3) matrix\ne_Data = e_Data'; % Store vertices in new matrix\n\nU = e_Data(:,1); % Store U data\nV = e_Data(:,2); % Store V data\n\nU = reshape(U,Nx,Ny)'; % Reshape (Nx*Nx,1) matrix to (Nx,Nx)\nV = reshape(V,Nx,Ny)'; % Reshape (Nx*Nx,1) matrix to (Nx,Nx)\n \nfclose(fileID); % Closes the data file.\n\ncd ..; % Change directory back to ../viz_IB2d/ directory\n\ncd(analysis_path); % Change directory back to Data Analysis Folder\n\nclear filename fileID str strVec count analysis_path e_Data Nx;\n\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/IBM_Blackbox/pass_Back_Data_For_Restart.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.34158248603300034, "lm_q1q2_score": 0.17345963903754322}} {"text": "function [data] = ft_megrealign(cfg, data)\n\n% FT_MEGREALIGN interpolates MEG data towards standard gradiometer locations by\n% projecting the individual timelocked data towards a coarse source reconstructed\n% representation and computing the magnetic field on the standard gradiometer\n% locations.\n%\n% Use as\n% [interp] = ft_megrealign(cfg, data)\n%\n% Required configuration options:\n% cfg.template\n% cfg.inwardshift\n%\n% The new gradiometer definition is obtained from a template dataset,\n% or can be constructed by averaging the gradiometer positions over\n% multiple datasets.\n% cfg.template = single dataset that serves as template\n% cfg.template(1..N) = datasets that are averaged into the standard\n%\n% The realignment is done by computing a minumum norm estimate using a\n% large number of dipoles that are placed in the upper layer of the brain\n% surface, followed by a forward computation towards the template\n% gradiometer array. This requires the specification of a volume conduction\n% model of the head and of a source model.\n%\n% A volume conduction model of the head should be specified with\n% cfg.headmodel = structure, see FT_PREPARE_HEADMODEL\n%\n% A source model (i.e. a superficial layer with distributed sources) can be\n% constructed from a headshape file, or from inner surface of the volume conduction\n% model using FT_PREPARE_SOIURCEMODEL using the following options\n% cfg.spheremesh = number of dipoles in the source layer (default = 642)\n% cfg.inwardshift = depth of the source layer relative to the headshape\n% surface or volume conduction model (no default\n% supplied, see below)\n% cfg.headshape = a filename containing headshape, a structure containing a\n% single triangulated boundary, or a Nx3 matrix with surface\n% points\n%\n% If you specify a headshape and it describes the skin surface, you should specify an\n% inward shift of 2.5 cm.\n%\n% For a single-sphere or a local-spheres volume conduction model based on the skin\n% surface, an inward shift of 2.5 cm is reasonable.\n%\n% For a single-sphere or a local-spheres volume conduction model based on the brain\n% surface, you should probably use an inward shift of about 1 cm.\n%\n% For a realistic single-shell volume conduction model based on the brain surface, you\n% should probably use an inward shift of about 1 cm.\n%\n% Other options are\n% cfg.pruneratio = for singular values, default is 1e-3\n% cfg.verify = 'yes' or 'no', show the percentage difference (default = 'yes')\n% cfg.feedback = 'yes' or 'no' (default = 'no')\n% cfg.channel = Nx1 cell-array with selection of channels (default = 'MEG'),\n% see FT_CHANNELSELECTION for details\n% cfg.trials = 'all' or a selection given as a 1xN vector (default = 'all')\n%\n% This implements the method described by T.R. Knosche, Transformation\n% of whole-head MEG recordings between different sensor positions.\n% Biomed Tech (Berl). 2002 Mar;47(3):59-62. For more information and\n% related methods, see Stolk et al., Online and offline tools for head\n% movement compensation in MEG. NeuroImage, 2012.\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_PREPARE_LOCALSPHERES, FT_PREPARE_SINGLESHELL\n\n% Copyright (C) 2004-2014, 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% these are used by the ft_preamble/ft_postamble function and scripts\nft_revision = '$Id$';\nft_nargin = nargin;\nft_nargout = nargout;\n\n% do the general setup of the function\nft_defaults\nft_preamble init\nft_preamble debug\nft_preamble 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 return\nend\n\n% check if the input cfg is valid for this function\ncfg = ft_checkconfig(cfg, 'renamed', {'plot3d', 'feedback'});\ncfg = ft_checkconfig(cfg, 'renamedval', {'headshape', 'headmodel', []});\ncfg = ft_checkconfig(cfg, 'required', {'inwardshift', 'template'});\ncfg = ft_checkconfig(cfg, 'renamed', {'hdmfile', 'headmodel'});\ncfg = ft_checkconfig(cfg, 'renamed', {'vol', 'headmodel'});\ncfg = ft_checkconfig(cfg, 'renamed', {'grid', 'sourcemodel'});\n\n% set the default configuration\ncfg.headshape = ft_getopt(cfg, 'headshape', []);\ncfg.pruneratio = ft_getopt(cfg, 'pruneratio', 1e-3);\ncfg.spheremesh = ft_getopt(cfg, 'spheremesh', 642);\ncfg.verify = ft_getopt(cfg, 'verify', 'yes');\ncfg.feedback = ft_getopt(cfg, 'feedback', 'yes');\ncfg.trials = ft_getopt(cfg, 'trials', 'all', 1);\ncfg.channel = ft_getopt(cfg, 'channel', 'MEG');\ncfg.topoparam = ft_getopt(cfg, 'topoparam', 'rms');\n\n% store original datatype\ndtype = ft_datatype(data);\n\n% check if the input data is valid for this function\ndata = ft_checkdata(data, 'datatype', 'raw', 'feedback', 'yes', 'hassampleinfo', 'yes', 'ismeg', 'yes');\n\n% do realignment per trial\npertrial = all(ismember({'nasX';'nasY';'nasZ';'lpaX';'lpaY';'lpaZ';'rpaX';'rpaY';'rpaZ'}, data.label));\n\n% put the low-level options pertaining to the dipole grid in their own field\ncfg = ft_checkconfig(cfg, 'renamed', {'tightgrid', 'tight'}); % this is moved to cfg.sourcemodel.tight by the subsequent createsubcfg\ncfg = ft_checkconfig(cfg, 'renamed', {'sourceunits', 'unit'}); % this is moved to cfg.sourcemodel.unit by the subsequent createsubcfg\n\n% put the low-level options pertaining to the sourcemodel in their own field\ncfg = ft_checkconfig(cfg, 'createsubcfg', {'sourcemodel'});\n% move some fields from cfg.sourcemodel back to the top-level configuration\ncfg = ft_checkconfig(cfg, 'createtopcfg', {'sourcemodel'});\n\nif isstruct(cfg.template)\n % this should be a cell-array\n cfg.template = {cfg.template};\nend\n\n% retain only the MEG channels in the data and temporarily store\n% the rest, these will be added back to the transformed data later.\n\n% select trials and channels of interest\ntmpcfg = [];\ntmpcfg.trials = cfg.trials;\ntmpcfg.channel = setdiff(data.label, ft_channelselection(cfg.channel, data.label));\nrest = ft_selectdata(tmpcfg, data);\n\ntmpcfg.channel = ft_channelselection(cfg.channel, data.label);\ndata = ft_selectdata(tmpcfg, data);\n\n% restore the provenance information\n[cfg, data] = rollback_provenance(cfg, data);\n\nNtrials = length(data.trial);\n\n% cfg.channel = ft_channelselection(cfg.channel, data.label);\n% dataindx = match_str(data.label, cfg.channel);\n% restindx = setdiff(1:length(data.label),dataindx);\n% if ~isempty(restindx)\n% fprintf('removing %d non-MEG channels from the data\\n', length(restindx));\n% rest.label = data.label(restindx); % first remember the rest\n% data.label = data.label(dataindx); % then reduce the data\n% for i=1:Ntrials\n% rest.trial{i} = data.trial{i}(restindx,:); % first remember the rest\n% data.trial{i} = data.trial{i}(dataindx,:); % then reduce the data\n% end\n% else\n% rest.label = {};\n% rest.trial = {};\n% end\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% construct the average template gradiometer array\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\ntemplate = struct([]); % initialize as 0x0 empty struct array with no fields\nfor i=1:length(cfg.template)\n if ischar(cfg.template{i})\n fprintf('reading template sensor position from %s\\n', cfg.template{i});\n tmp = ft_read_sens(cfg.template{i}, 'senstype', 'meg');\n elseif isstruct(cfg.template{i}) && isfield(cfg.template{i}, 'coilpos') && isfield(cfg.template{i}, 'coilori') && isfield(cfg.template{i}, 'tra')\n tmp = cfg.template{i};\n elseif isstruct(cfg.template{i}) && isfield(cfg.template{i}, 'pnt') && isfield(cfg.template{i}, 'ori') && isfield(cfg.template{i}, 'tra')\n % it seems to be a pre-2011v1 type gradiometer structure, update it\n tmp = ft_datatype_sens(cfg.template{i});\n else\n ft_error('unrecognized template input');\n end\n % prevent \"Subscripted assignment between dissimilar structures\" error\n template = appendstruct(template, tmp); clear tmp\nend\n\ngrad = ft_average_sens(template);\n\n% construct the final template gradiometer definition\ntemplate = [];\ntemplate.grad = grad;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% FT_PREPARE_VOL_SENS will match the data labels, the gradiometer labels and the\n% volume model labels (in case of a localspheres model) and result in a gradiometer\n% definition that only contains the gradiometers that are present in the data.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nvolcfg = [];\nvolcfg.headmodel = cfg.headmodel;\nvolcfg.grad = data.grad;\nvolcfg.channel = data.label; % this might be a subset of the MEG channels\ngradorig = data.grad; % this is needed later on for plotting. As of\n% yet the next step is not entirely correct, because it does not keep track\n% of the balancing of the gradiometer array. FIXME this may require some\n% thought because the leadfields are computed with low level functions and\n% do not easily accommodate for matching the correct channels with each\n% other (in order to compute the projection matrix).\n[volold, data.grad] = prepare_headmodel(volcfg);\n\n% note that it is necessary to keep the two volume conduction models\n% separate, since the single-shell Nolte model contains gradiometer specific\n% precomputed parameters. Note that this is not guaranteed to result in a\n% good projection for local sphere models.\nvolcfg.grad = template.grad;\nvolcfg.channel = 'MEG'; % include all MEG channels\n[volnew, template.grad] = prepare_headmodel(volcfg);\n\nif strcmp(ft_senstype(data.grad), ft_senstype(template.grad))\n [id, it] = match_str(data.grad.label, template.grad.label);\n fprintf('mean distance towards template gradiometers is %.2f %s\\n', mean(sum((data.grad.chanpos(id,:)-template.grad.chanpos(it,:)).^2, 2).^0.5), template.grad.unit);\nelse\n % the projection is from one MEG system to another MEG system, which makes a comparison of the data difficult\n cfg.feedback = 'no';\n cfg.verify = 'no';\nend\n\n% copy all options that are potentially used in ft_prepare_sourcemodel\ntmpcfg = keepfields(cfg, {'sourcemodel', 'mri', 'headshape', 'symmetry', 'smooth', 'threshold', 'spheremesh', 'inwardshift', 'xgrid' 'ygrid', 'zgrid', 'resolution', 'tight', 'warpmni', 'template', 'showcallinfo'});\ntmpcfg.headmodel = volold;\ntmpcfg.grad = data.grad;\n% create the source positions on which the data will be projected\nsourcemodel = ft_prepare_sourcemodel(tmpcfg);\npos = sourcemodel.pos;\n\n% sometimes some of the dipole positions are nan, due to problems with the headsurface triangulation\n% remove them to prevent problems with the forward computation\nsel = find(any(isnan(pos(:,1)),2));\npos(sel,:) = [];\n\n% compute the forward model for the new gradiometer positions\nfprintf('computing forward model for %d dipoles\\n', size(pos,1));\nlfnew = ft_compute_leadfield(pos, template.grad, volnew);\nif ~pertrial\n %this needs to be done only once\n lfold = ft_compute_leadfield(pos, data.grad, volold);\n [realign, noalign, bkalign] = computeprojection(lfold, lfnew, cfg.pruneratio, cfg.verify);\nelse\n %the forward model and realignment matrices have to be computed for each trial\n %this also goes for the singleshell volume conductor model\n %x = which('rigidbodyJM'); %this function is needed\n %if isempty(x)\n % ft_error('you are trying out experimental code for which you need some extra functionality which is currently not in the release version of FieldTrip. if you are interested in trying it out, contact Jan-Mathijs');\n %end\nend\n\n% interpolate the data towards the template gradiometers\nfor i=1:Ntrials\n fprintf('realigning trial %d\\n', i);\n if pertrial\n %warp the gradiometer array according to the motiontracking data\n sel = match_str(rest.label, {'nasX';'nasY';'nasZ';'lpaX';'lpaY';'lpaZ';'rpaX';'rpaY';'rpaZ'});\n hmdat = rest.trial{i}(sel,:);\n if ~all(hmdat==repmat(hmdat(:,1),[1 size(hmdat,2)]))\n ft_error('only one position per trial is at present allowed');\n else\n %M = rigidbodyJM(hmdat(:,1))\n M = ft_headcoordinates(hmdat(1:3,1),hmdat(4:6,1),hmdat(7:9,1));\n grad = ft_transform_geometry(M, data.grad);\n end\n\n volcfg.grad = grad;\n %compute volume conductor\n [volold, grad] = prepare_headmodel(volcfg);\n %compute forward model\n lfold = ft_compute_leadfield(pos, grad, volold);\n %compute projection matrix\n [realign, noalign, bkalign] = computeprojection(lfold, lfnew, cfg.pruneratio, cfg.verify);\n end\n data.realign{i} = realign * data.trial{i};\n if strcmp(cfg.verify, 'yes')\n % also compute the residual variance when interpolating\n [id,it] = match_str(data.grad.label, template.grad.label);\n rvrealign = rv(data.trial{i}(id,:), data.realign{i}(it,:));\n fprintf('original -> template RV %.2f %%\\n', 100 * mean(rvrealign));\n datnoalign = noalign * data.trial{i};\n datbkalign = bkalign * data.trial{i};\n rvnoalign = rv(data.trial{i}, datnoalign);\n rvbkalign = rv(data.trial{i}, datbkalign);\n fprintf('original -> original RV %.2f %%\\n', 100 * mean(rvnoalign));\n fprintf('original -> template -> original RV %.2f %%\\n', 100 * mean(rvbkalign));\n end\nend\n\n% plot the topography before and after the realignment\nif strcmp(cfg.feedback, 'yes')\n\n ft_warning('showing MEG topography (RMS value over time) in the first trial only');\n Nchan = length(data.grad.label);\n [id,it] = match_str(data.grad.label, template.grad.label);\n pos1 = data.grad.chanpos(id,:);\n pos2 = template.grad.chanpos(it,:);\n prj1 = elproj(pos1); tri1 = delaunay(prj1(:,1), prj1(:,2));\n prj2 = elproj(pos2); tri2 = delaunay(prj2(:,1), prj2(:,2));\n\n switch cfg.topoparam\n case 'rms'\n p1 = sqrt(mean(data.trial{1}(id,:).^2, 2));\n p2 = sqrt(mean(data.realign{1}(it,:).^2, 2));\n case 'svd'\n [u, s, v] = svd(data.trial{1}(id,:)); p1 = u(:,1);\n [u, s, v] = svd(data.realign{1}(it,:)); p2 = u(:,1);\n otherwise\n ft_error('unsupported cfg.topoparam');\n end\n\n X = [pos1(:,1) pos2(:,1)]';\n Y = [pos1(:,2) pos2(:,2)]';\n Z = [pos1(:,3) pos2(:,3)]';\n\n % show figure with old an new helmets, volume model and source positions\n figure\n hold on\n ft_plot_headmodel(volold);\n plot3(sourcemodel.pos(:,1),sourcemodel.pos(:,2),sourcemodel.pos(:,3),'b.');\n plot3(pos1(:,1), pos1(:,2), pos1(:,3), 'r.') % original positions\n plot3(pos2(:,1), pos2(:,2), pos2(:,3), 'g.') % template positions\n line(X,Y,Z, 'color', 'black');\n view(-90, 90);\n\n % show figure with data on old helmet location\n figure\n hold on\n plot3(pos1(:,1), pos1(:,2), pos1(:,3), 'r.') % original positions\n plot3(pos2(:,1), pos2(:,2), pos2(:,3), 'g.') % template positions\n line(X,Y,Z, 'color', 'black');\n axis equal; axis vis3d\n bnd1 = [];\n bnd1.pos = pos1;\n bnd1.tri = tri1;\n ft_plot_mesh(bnd1,'vertexcolor',p1,'edgecolor','none')\n title('RMS, before realignment')\n view(-90, 90)\n\n % show figure with data on new helmet location\n figure\n hold on\n plot3(pos1(:,1), pos1(:,2), pos1(:,3), 'r.') % original positions\n plot3(pos2(:,1), pos2(:,2), pos2(:,3), 'g.') % template positions\n line(X,Y,Z, 'color', 'black');\n axis equal; axis vis3d\n bnd2 = [];\n bnd2.pos = pos2;\n bnd2.tri = tri2;\n ft_plot_mesh(bnd2,'vertexcolor',p2,'edgecolor','none')\n title('RMS, after realignment')\n view(-90, 90)\nend\n\n% store the realigned data in a new structure\ninterp.label = template.grad.label;\ninterp.grad = template.grad; % replace with the template gradiometer array\ninterp.trial = data.realign; % remember the processed data\ninterp.fsample = data.fsample;\ninterp.time = data.time;\n\n% add the rest channels back to the data, these were not interpolated\nif ~isempty(rest.label)\n fprintf('adding %d non-MEG channels back to the data (', length(rest.label));\n fprintf('%s, ', rest.label{1:end-1});\n fprintf('%s)\\n', rest.label{end});\n for trial=1:length(rest.trial)\n interp.trial{trial} = [interp.trial{trial}; rest.trial{trial}];\n end\n interp.label = [interp.label; rest.label];\nend\n\n% copy the trial specific information into the output\nif isfield(data, 'trialinfo')\n interp.trialinfo = data.trialinfo;\nend\n\n% copy the sampleinfo field as well\nif isfield(data, 'sampleinfo')\n interp.sampleinfo = data.sampleinfo;\nend\n\n% convert back to input type if necessary\nswitch dtype\n case 'timelock'\n interp = ft_checkdata(interp, 'datatype', 'timelock');\n otherwise\n % keep the output as it is\nend\n\n% do the general cleanup and bookkeeping at the end of the function\nft_postamble debug\nft_postamble trackconfig\nft_postamble previous data\n\n% rename the output variable to accomodate the savevar postamble\ndata = interp;\n\nft_postamble provenance data\nft_postamble history data\nft_postamble savevar data\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% subfunction that computes the projection matrix(ces)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [realign, noalign, bkalign] = computeprojection(lfold, lfnew, pruneratio, verify)\n\n% compute this inverse only once, although it is used twice\ntmp = prunedinv(lfold, pruneratio);\n% compute the three interpolation matrices\nfprintf('computing interpolation matrix #1\\n');\nrealign = lfnew * tmp;\nif strcmp(verify, 'yes')\n fprintf('computing interpolation matrix #2\\n');\n noalign = lfold * tmp;\n fprintf('computing interpolation matrix #3\\n');\n bkalign = lfold * prunedinv(lfnew, pruneratio) * realign;\nelse\n noalign = [];\n bkalign = [];\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% subfunction that computes the inverse using a pruned SVD\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [lfi] = prunedinv(lf, r)\n[u, s, v] = svd(lf);\nif r<1\n % treat r as a ratio\n p = find(s<(s(1,1)*r) & s~=0);\nelse\n % treat r as the number of spatial components to keep\n diagels = 1:(min(size(s))+1):(min(size(s)).^2);\n p = diagels((r+1):end);\nend\nfprintf('pruning %d from %d, i.e. removing the %d smallest spatial components\\n', length(p), min(size(s)), length(p));\ns(p) = 0;\ns(find(s~=0)) = 1./s(find(s~=0));\nlfi = v * s' * u';\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_megrealign.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030761371502, "lm_q2_score": 0.29746993014852224, "lm_q1q2_score": 0.17292018545363916}} {"text": "function [isrc, idet, measure, channel_type] = nst_unformat_channel(channel_label, warn_bad_channel)\n% NST_UNFORMAT_CHANNEL extract source, dectector and measure information from channel label.\n%\n% [ISRC, IDET, MEAS, CHAN_TYPE] = NST_UNFORMAT_CHANNEL(CHANNEL_LABEL)\n% CHANNEL_LABEL (str): \n% formatted as 'SxDyWLz' or 'SxDyHbt', where:\n% x: source index\n% y: detector index\n% z: wavelength\n% t: Hb type (O, R, T).\n% Examples: S1D2WL685, S01D7WL830, S3D01HbR\n%\n% ISRC (int): extracted source index\n% IDET (int): extracted detector index\n% MEAS (int | str): extracted measure value\n% CHAN_TYPE (int): extracted channel type.\n%\n% If channel cannot be unformatted then all returned values are nan\n%\n% See also NST_UNFORMAT_CHANNELS, NST_CHANNEL_TYPES, NST_FORMAT_CHANNEL\nassert(ischar(channel_label));\n\nif nargin < 2\n warn_bad_channel = 0;\nend\n\nCHAN_RE = '^S([0-9]+)D([0-9]+)(WL\\d+|HbO|HbR|HbT)$';\ntoks = regexp(channel_label, CHAN_RE, 'tokens');\nif isempty(toks)\n if warn_bad_channel\n warning('NIRSTORM:MalformedChannelLabel', ...\n ['Malformed channel label:', channel_label, ...\n '. Should be SxDyWLz or SxDyHb(O|R|T)']);\n end\n isrc = nan;\n idet = nan;\n measure = nan;\n channel_type = nan;\nelse\n isrc = str2double(toks{1}{1});\n idet = str2double(toks{1}{2});\n measure = toks{1}{3};\n \n measure_types = nst_measure_types();\n if ~isempty(strfind(measure, 'WL'))\n channel_type = measure_types.WAVELENGTH;\n measure = str2double(measure(3:end));\n else\n channel_type = measure_types.HB;\n end\nend\n\nend", "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/io/private/nst_unformat_channel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.3415825061409754, "lm_q1q2_score": 0.17212553258922508}} {"text": "%% maxwell_run\n% Run MaxwellFDFD.\n\n%%% Syntax\n% [E_cell, H_cell] = maxwell_run(OSC, DOM, OBJ, SRC, [inspect_only])\n% [E_cell, H_cell, obj_array, src_array] = maxwell_run(...)\n% [E_cell, H_cell, obj_array, src_array, extra] = maxwell_run(...)\n\n\n%%% Description\n% |maxwell_run(OSC, DOM, OBJ, SRC)| constructs a simulation domain from given\n% objects and sources, and launches a finite-difference frequency-domain (FDFD)\n% solver to solve Maxwell's equations in the simulation domain.\n%\n% Each of |OSC|, |DOM|, |OBJ|, and |SRC| represents a group of parameters.\n% Each group supports several flexible expressions. See the following sections\n% about the input parameter groups for more details.\n%\n% |maxwell_run| can take an optional argument |inspect_only|, which is a logical\n% argument (i.e., |true| or |false|). If |inspect_only = true|, |maxwell_run|\n% runs without launching the solver. This is useful to inspect input arguments\n% before starting expensive computation.\n% \n% |[E_cell, H_cell] = maxwell_run(...)| returns the E- and H-field solutions of\n% Maxwell's equations. |E_cell| and |H_cell| are length-3 row cell arrays whose\n% elements are the x-, y-, and z-components of the respective field solutions.\n% Each x-, y-, z-component of the fields are provided as instances of\n% .\n%\n% |[E_cell, H_cell, obj_array, src_array] = maxwell_run(...)| returns arrays of\n% instances of and . The |EMObject|\n% and |Source| elements represent the objects and sources placed in the\n% simulation domain, so they can be used to visualize the simulation domain.\n%\n% |[E_cell, H_cell, obj_array, src_array, extra] = maxwell_run(...)| returns\n% |extra|, which is a structure containing the fields |grid3d|, |J|, |M|, |eps|,\n% and |mu|: |grid3d| is an instance of that contains the\n% grid information; |J| and |M| are the electric and magnetic current source\n% distributions that have the same structure as |E_cell| and |H_cell|; |eps| and\n% |mu| are instances of that contain the electric\n% permittivity and magnetic permeability defined at the centers of the grid\n% cells.\n\n\n%%% Input Parameter Group - OSC\n% OSC group specifies oscillation parameters. The group begins with |'OSC'| and\n% ends with one of the followings:\n%\n% * |L0, wvlen| \n% * |osc|\n%\n% |L0|: unit of length in meters. For example, |L0 = 1e-9| means 1 nm.\n% All lengths in other parameters are described in this unit. \n%\n% |wvlen|: vacuum wavelength in the unit of |L0|. In other words, the actual\n% wavelength is |wvlen * L0|.\n%\n% |osc|: instance of , which contains the information\n% about the length unit and vacuum wavelength.\n\n\n%%% Input Parameter Group - DOM\n% DOM group specifies domain parameters. The group begins with |'DOM'| and ends\n% with one of the followings:\n%\n% * |material, box, dl, bc, Lpml, [deg_pml, [R_pml]], [withuniformgrid]|\n% * |domain, dl, bc, Lpml, [deg_pml, [R_pml]], [withuniformgrid]|\n%\n% |material|: background material filling the simulation domain. See\n% for various ways to describe a\n% material.\n%\n% |box|: range of the simulation doamin in the form of |[xmin xmax; ymin ymax;\n% zmin zmax]|.\n%\n% |dl|: default grid cell size in the form of |[dx dy dz]|. Can be abbreviated\n% to a scalar |dl| if |dx == dy == dz|.\n%\n% |bc|: boundary conditions in the form of |[bc_xn bc_yn bc_zn]|, whose each\n% element specifies the boundary condition at the negative end in one of the x-,\n% y-, z-axes (e.g., |bc_xn| for the negative end in the x-axis.). Each element\n% of |bc| is an instance of . The boundary conditions at the\n% positive ends are automatically determined by those at the negative ends:\n% |bc_wp == BC.p| if |bc_wn == BC.p|, and |bc_wp == BC.m| otherwise. Can be\n% further abbreviated to a single BC instance if |bc_xn == bc_yn == bc_zn|.\n%\n% |Lpml|: thicknesses of PML in the form of |[Lpml_xn Lpml_xp; Lpml_yn Lpml_yp;\n% Lpml_zn Lpml_zp]|, whose each element specifies the thickness at either\n% negative or positive end in one of the x-, y-, z-axes (e.g., |Lpml_xn| for the\n% negative end in the x-axis). Can be abbreviated to |[Lpml_x Lpml_y Lpml_z]|\n% if |Lpml_wn == Lpml_wp| for |w = x, y, z|. Can be further abbreviated to a\n% single scalar thickness if |Lpml_x == Lpml_y == Lpml_z|. All thicknesses are\n% in the unit of |L0|.\n%\n% |domain|: instance of , which contains the information\n% about |material| and |box|.\n%\n% |deg_pml|: optional argument to specify the degrees of the polynomial gradings\n% of PML loss parameters in the form of |[deg_xn deg_xp; deg_yn deg_yp; deg_zn\n% deg_zp]|. Can be abbreviated to |[deg_x deg_y deg_z]| if |deg_wn == deg_wp|\n% for |w = x, y, z|. Can be further abbreviated to a single scalar if |deg_x ==\n% deg_y == deg_z|. The default value is |deg_pml = 4|, meaning that the\n% polynomials of degree 4 are used to smoothly increase the PML loss parameters\n% for all boundaries with PML.\n%\n% |R_pml|: optional argument to specify the target reflectances in the form of\n% |[R_xn R_xp; R_yn R_yp; R_zn R_zp]|. To specify |R_pml|, |deg_pml| should be\n% specified. Can be abbreviated to |[R_x R_y R_z]| if |R_wn == R_wp| for |w =\n% x, y, z|. Can be further abbreviated to a single scalar if |R_x == R_y ==\n% R_z|. The default value is |R_pml = exp(-16)|, meaning that the reflectance\n% from PML is aimed to be as small as |exp(-16) ~= 1e-7|.\n%\n% |withuniformgrid|: optional argument to select a grid generation algorithm.\n% If |withuniformgrid = true|, a grid is generated uniformly; otherwise a grid\n% is generated dynamically to best fit the objects in the simulation domain.\n% The default value is |withuniformgrid = false|, i.e., dynamic grid generation\n% is preferred to uniform grid generation.\n\n\n%%% Input Parameter Group - OBJ and SOBJ\n% OBJ group specifies obect parameters. The group begins with |'OBJ'| and ends\n% with one of the followings:\n%\n% * |material_1, shapes_1, ..., material_N, shapes_N|\n% * |obj_1, ..., obj_N|\n% * |eps_node_array|\n%\n% |material_i|: material filling |shapes_i|. See for various ways to describe a material.\n%\n% |shapes_i|: shapes made of |material_i|. It can be a single shape, an array\n% of shapes (i.e., |[shape_a, shape_b, ...]|), or can be spanned into several\n% shape arguments (i.e., |shape_1, shape_2, ...|). Each shape is an instance of\n% .\n%\n% |obj_i|: instance or array of instances of . Each\n% |EMObject| is composed of a material and shape.\n%\n% |eps_node_array| is a 3D array of permittivities defined at the centers of\n% grid cells. The size of the array should be the same as the number of grid\n% cells in a generated grid. Because the number of grid cells generated by\n% dynamic grid generation is hard to predict, uniform grid generation is\n% recommended (see DOM group) when |eps_node_array| is used.\n%\n% There is a similar, optional parameter group SOBJ that begins with |'SOBJ'|.\n% SOBJ stands for _scattering objects_, and it is used to define scatterers for\n% total-field/scattered-field (TF/SF) simulation. When a TF/SF source is used\n% as a source, the objects defined in SOBJ group are treated as scatterers\n% whereas the objects defined in OBJ group are treated as background objects.\n% If a TF/SF source is not used, SOBJ group works the same as OBJ group.\n\n\n%%% Input Parameter Group - SRC\n% SRC group specifies current source parameters. Depending on whether the\n% sources are electric or magnetic, the group begins with |'SRCJ'| or |'SRCM'|\n% and ends with\n%\n% * |src_1, ..., src_M|\n%\n% |src_i|: instance or array of instances of . \n\n\n%%% Material Description\n% Each material is described by one of the followings:\n%\n% * |{name, color, permittivity}|\n% * |{material_datapath, color}|\n% * |material|\n%\n% |name|: string describing the name of the material (e.g., 'vacuum', 'silver',\n% 'Ag'). \n%\n% |color|: color to be used in visualizing objects made of the material. It can\n% be either a standard color specifier character used in MATLAB (e.g., |'w'| for\n% white, |'k'| for black, etc.) or |[r, g, b]| where |r|, |g|, |b| are RGB color\n% scales ranging from |0.0| to |1.0| (e.g., |[0.5, 0.5, 0.5]| for gray). Use\n% |color = 'none'| to not draw the material.\n%\n% |permittivity|: electric permittivity value in the unit of the vacuum\n% permittivity. It is a complex number.\n%\n% |material_datapath|: path to the file of the permittivity data of the\n% material. It is a path relative to |material| directory. For example,\n% |'Palik/Si'| refers to silicon's permittivity data stored in |Si.m| file in\n% |material/Palik| directory. The permittivity for the frequency of interest is\n% automatically retrieved from the data file.\n\n%%% Example\n% gray = [0.5 0.5 0.5]; % [r g b]\n% inspect_only = true;\n% [E, H, obj_array, extra] = maxwell_run(...\n% 'OSC', 1e-9, 1550, ...\n% 'DOM', {['Palik/SiO2'], 'none'}, [-700, 700; -600, 600; -200, 1700], 20, BC.p, 200, ...\n% 'OBJ', ...\n% {['Palik/SiO2'], 'none'}, Box([-50, 50; -50, 50; -200, 1700], [2, 2, 20]), ... % OBJ1\n% {['CRC/Ag'], gray}, [Box([-700, -25; -25, 25; -200, 1700], 20), Box([25, 700; -25, 25; -200, 1700], 20)], ... % OBJ2\n% 'SRCJ', PointSrc(Axis.x, [0, 0, 200]), ...\n% inspect_only);\n\nfunction [E_cell, H_cell, obj_array, src_array, extra] = maxwell_run(varargin)\n\tDEFAULT_METHOD = 'direct'; % 'direct', 'gpu', 'aws', 'inputfile'\n\t\t\n\t% Set solver options.\n\tiarg = nargin; arg = varargin{iarg};\n\tinspect_only = false;\n\tif istypesizeof(arg, 'logical')\n\t\tinspect_only = arg;\n\t\tiarg = iarg - 1; arg = varargin{iarg};\n\tend\n\n\tis_solveropts = false;\n\tif istypesizeof(arg, 'struct')\n\t\tsolveropts = arg;\n\t\tis_solveropts = true;\n\t\tiarg = iarg - 1; % arg = varargin{iarg};\n\tend\n\t\t\n\tif ~is_solveropts || ~isfield(solveropts, 'showstruct')\n\t\tsolveropts.showstruct = true;\n\tend\n\t\n\tif ~is_solveropts || ~isfield(solveropts, 'method')\n\t\tsolveropts.method = DEFAULT_METHOD;\n\tend\n\t\n\tif is_solveropts && isequal(solveropts.method, 'inputfile')\n\t\tchkarg(isfield(solveropts, 'filenamebase'), '\"solveropts\" should have \"filenamebase\" field.');\n\tend\n\t\n\tif ~is_solveropts || ~isfield(solveropts, 'maxit')\n% \t\tsolveropts.maxit = intmax;\n\t\tsolveropts.maxit = 1e6;\n\telse\n\t\tchkarg(istypesizeof(solveropts.maxit, 'real') && solveropts.maxit > 0, ...\n\t\t\t'solveropts.maxit should be positive.');\t\n\tend\n\n\tif ~is_solveropts || ~isfield(solveropts, 'tol')\n\t\tsolveropts.tol = 1e-6;\n\telse\n\t\tchkarg(istypesizeof(solveropts.tol, 'real') && solveropts.tol > 0, ...\n\t\t\t'solveropts.tol should be positive.');\n\tend\n\n\tif ~is_solveropts || ~isfield(solveropts, 'eqtype')\n\t\tsolveropts.eqtype = EquationType(FT.e, GT.prim);\n\telse\n\t\tchkarg(istypesizeof(solveropts.eqtype, 'EquationType'), ...\n\t\t\t'solveropts.eqtype should be instance of EquationType.');\n\tend\n\n\tif ~is_solveropts || ~isfield(solveropts, 'pml')\n\t\tsolveropts.pml = PML.sc;\n\telse\n\t\tchkarg(istypesizeof(solveropts.pml, 'PML'), ...\n\t\t\t'solveropts.pml should be instance of PML.');\n\tend\n\t\n\tif ~is_solveropts || ~isfield(solveropts, 'returnAandb')\n\t\tsolveropts.returnAandb = false;\n\telse\n\t\tchkarg(istypesizeof(solveropts.returnAandb, 'logical'), ...\n\t\t\t'solveropts.returnAandb should be logical.');\n\tend\n\t\n\tif ~is_solveropts || ~isfield(solveropts, 'returnDiv')\n\t\tsolveropts.returnDiv = false;\n\telse\n\t\tchkarg(istypesizeof(solveropts.returnDiv, 'logical'), ...\n\t\t\t'solveropts.returnDiv should be logical.');\n\tend\n\t\n\tchkarg(iarg > 0, 'first argument is not correct.');\n\n\tif inspect_only\n\t\tfprintf('%s begins (inspection only).\\n', mfilename);\n\telse\n\t\tfprintf('%s begins.\\n', mfilename);\n\tend\n\tge = solveropts.eqtype.ge;\n\tfprintf('E-field grid type: %s\\n', char(ge));\n\tpm = ProgMark();\n\t\n\t% Build the system.\n\t% Make sure to pass the first consecutive elements of varargin to\n\t% build_system() for correct error reports.\n\t[osc, grid3d, s_factor, eps, mu, J, M, obj_array, src_array, mat_array, eps_node, mu_node, isiso] = ...\n\t\tbuild_system(ge, solveropts.pml, varargin{1:iarg}, pm);\n\t\n\tif ~is_solveropts || ~isfield(solveropts, 'F0')\n\t\tsolveropts.F0 = 'zero'; % 'rand' is the other choice\n\telse\n\t\tchkarg(isequal(solveropts.F0, 'zero') || isequal(solveropts.F0, 'rand') ...\n\t\t\t|| istypesizeof(solveropts.F0, 'complexcell', [1 Axis.count], grid3d.N), ...\n\t\t\t'solveropts.F0 should be length-%d cell array whose each element is %d-by-%d-by-%d array with complex numbers.', ...\n\t\t\tAxis.count, grid3d.Ncell{:});\n\tend\n\t\t\n\tif inspect_only % inspect objects and sources\n\t\tif solveropts.showstruct\n\t\t\tfigure;\n\t\t\tset(gcf, 'units','normalized','position',[0.5 0 0.5 0.5]);\t\t\t\n\t\t\twithpml = true;\n\t\t\tvisobjsrc(grid3d, obj_array, src_array, withpml);\n\t\t\tdrawnow\n\t\t\tpm.mark('domain visualization');\n\t\tend\n\t\t\n\t\t% Visualize modes.\n\t\tis_modalsrc = false;\n\t\tfor src = src_array\n\t\t\tif istypesizeof(src, 'ModalSrc')\n\t\t\t\tis_modalsrc = true;\n\t\t\t\tmodalsrc = src;\n\t\t\t\topts.withabs = true;\n\t\t\t\t\n\t\t\t\tE2d = modalsrc.E2d;\n\t\t\t\tcmax = max(abs([E2d{Axis.x}.array(:); E2d{Axis.y}.array(:); E2d{Axis.z}.array(:)]));\n\t\t\t\topts.cmax = cmax;\n\t\t\t\tfor w = Axis.elems\n\t\t\t\t\tfigure;\n\t\t\t\t\tset(gcf, 'units','normalized','position',[(int(w)-1)/3 1/2 1/3 1/3]);\t\t\t\n\t\t\t\t\tvis2d(E2d{w}, obj_array, opts);\n\t\t\t\t\tdrawnow;\n\t\t\t\tend\n\t\t\t\t\n\t\t\t\tH2d = modalsrc.H2d;\n\t\t\t\tcmax = max(abs([H2d{Axis.x}.array(:); H2d{Axis.y}.array(:); H2d{Axis.z}.array(:)]));\n\t\t\t\topts.cmax = cmax;\n\t\t\t\tfor w = Axis.elems\n\t\t\t\t\tfigure;\n\t\t\t\t\tset(gcf, 'units','normalized','position',[(int(w)-1)/3 0 1/3 1/3]);\t\t\t\n\t\t\t\t\tvis2d(H2d{w}, obj_array, opts);\n\t\t\t\t\tdrawnow;\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\t\t\n\t\tif is_modalsrc\n\t\t\tpm.mark('distributed source visualization');\n\t\tend\n\t\tfprintf('%s finishes (inspection only).\\n\\n', mfilename);\n\t\tE = {};\n\t\tH = {};\n\telse % inspect_only == false\n\t\tif isequal(solveropts.method, 'inputfile')\n\t\t\t% Define eps_node_array at vertices of the E-field edges.\n\t\t\tchkarg(isiso, 'anisotropic materials are not supported for solveropts.method == ''inputfile''.');\n\t\t\t\n\t\t\tif ge == GT.prim\n\t\t\t\teps_node = eps_node{Axis.x}; % ad hoc solution\n\t\t\t\t\n\t\t\t\t% Old implementation (without anisotropy support) starts\n\t\t\t\t% here.\n\t\t\t\teps_node_array = eps_node.data_expanded(); % (Nx+2) x (Ny+2) x (Nz+2)\n\t\t\t\teps_node_array = eps_node_array(1:end-1, 1:end-1, 1:end-1); % (Nx+1) x (Ny+1) x (Nz+1)\n\t\t\t\t\n\t\t\t\t% The below line is an ad hoc solution for the error. It\n\t\t\t\t% is just to pass an array with correct size to\n\t\t\t\t% write_input(), but eps_node_array is not used in\n\t\t\t\t% write_input() currently.\n\t\t\t\teps_node_array = eps_node_array(1:end-1, 1:end-1, 1:end-1); % Nx x Ny x Nz\n% \n% \t\t\t\t% (Anisotropy support? begins)\n% % \t\t\t\teps_node_cell = eps_cell;\n% % \t\t\t\tfor w = Axis.elems\n% % \t\t\t\t\tind_g = {':',':',':'};\n% % \t\t\t\t\tif grid3d.bc(w) == BC.p\n% % \t\t\t\t\t\tind_g{w} = grid3d.N(w);\n% % \t\t\t\t\telse\n% % \t\t\t\t\t\tind_g{w} = 1;\n% % \t\t\t\t\tend\n% % \t\t\t\t\teps_node_cell{w} = cat(int(w), eps_node_cell{w}(ind_g{:}), eps_node_cell{w});\n% % \t\t\t\tend\n% % \t\t\t\teps_node_cell{Axis.x} = 2./(1./eps_node_cell{Axis.x}(1:end-1, :, :) + 1./eps_node_cell{Axis.x}(2:end, :, :));\n% % \t\t\t\teps_node_cell{Axis.y} = 2./(1./eps_node_cell{Axis.y}(:, 1:end-1, :) + 1./eps_node_cell{Axis.y}(:, 2:end, :));\n% % \t\t\t\teps_node_cell{Axis.z} = 2./(1./eps_node_cell{Axis.z}(:, :, 1:end-1) + 1./eps_node_cell{Axis.z}(:, :, 2:end));\n% % \t\t\t\t\n% % \t\t\t\teps_node_array = (eps_node_cell{Axis.x} + eps_node_cell{Axis.y} + eps_node_cell{Axis.z})./3;\n% % \t\n% % \t\t\t\teps_node_array = (eps_node_array(1:end-1,1:end-1,1:end-1) + eps_node_array(2:end,1:end-1,1:end-1) ...\n% % \t\t\t\t\t\t\t+ eps_node_array(1:end-1,2:end,1:end-1) + eps_node_array(1:end-1,1:end-1,2:end) ...\n% % \t\t\t\t\t\t\t+ eps_node_array(1:end-1,2:end,2:end) + eps_node_array(2:end,1:end-1,2:end) ...\n% % \t\t\t\t\t\t\t+ eps_node_array(2:end,2:end,1:end-1) + eps_node_array(2:end,2:end,2:end))./8;\n% \t\t\t\t% (Anisotropy support? ends)\n% \n% \t\t\t\teps_node_array = 8./(1./eps_node_array(1:end-1,1:end-1,1:end-1) + 1./eps_node_array(2:end,1:end-1,1:end-1) ...\n% \t\t\t\t\t\t\t+ 1./eps_node_array(1:end-1,2:end,1:end-1) + 1./eps_node_array(1:end-1,1:end-1,2:end) ...\n% \t\t\t\t\t\t\t+ 1./eps_node_array(1:end-1,2:end,2:end) + 1./eps_node_array(2:end,1:end-1,2:end) ...\n% \t\t\t\t\t\t\t+ 1./eps_node_array(2:end,2:end,1:end-1) + 1./eps_node_array(2:end,2:end,2:end));\n\t\t\telse\n\t\t\t\teps_node_array = eps_node.data_original(); % Nx x Ny x Nz\n\t\t\tend\n\n\t\t\twrite_input(solveropts.filenamebase, solveropts.eqtype, osc, grid3d, s_factor, ...\n\t\t\t\teps_node_array, eps, mu, J, M, solveropts.F0, solveropts.tol, solveropts.maxit);\n\n\t\t\tpm.mark('input file creation');\t\t\n\t\t\tfprintf('%s finishes. (input file created)\\n\\n', mfilename);\n\t\t\tE = {};\n\t\t\tH = {};\n\t\telse % solveropts.method ~= 'inputfile'\n\t\t\tif isequal(solveropts.method, 'direct')\n\t\t\t\t[E, H] = solve_eq_direct(solveropts.eqtype, solveropts.pml, osc.in_omega0(), eps, mu, s_factor, J, M, grid3d);\n\t\t\telseif isequal(solveropts.method, 'iterative')\n\t\t\t\t[E, H, relres, iter, resvec] = solve_eq_iterative(solveropts.maxit, solveropts.tol, solveropts.F0, solveropts.eqtype, solveropts.pml, osc.in_omega0(), eps, mu, s_factor, J, M, grid3d);\n\t\t\telse % for solvers using E-field based equation\n\t\t\t\t%% Apply spatial inversion.\n% \t\t\t\td_prim = grid3d.dl(:, GT.prim);\n% \t\t\t\td_dual = grid3d.dl(:, GT.dual);\n% \t\t\t\ts_prim = s_factor(:, GT.prim);\n% \t\t\t\ts_dual = s_factor(:, GT.dual);\n\t\t\t\td_prim = flip_vec(grid3d.dl(:, GT.dual)); % GT.dual, not GT.prim\n\t\t\t\td_dual = flip_vec(grid3d.dl(:, GT.prim)); % GT.prim, not GT.dual\n\t\t\t\ts_prim = flip_vec(s_factor(:, GT.dual)); % GT.dual, not GT.prim\n\t\t\t\ts_dual = flip_vec(s_factor(:, GT.prim)); % GT.prim, not GT.dual\n\t\t\t\tmu = flip_vec(mu);\n\t\t\t\teps = flip_vec(eps);\n\t\t\t\tJ = neg_vec(flip_vec(J)); % pseudovector\n\n\t\t\t\tif isequal(solveropts.method, 'gpu')\n\t\t\t\t\tds_prim = mult_vec(d_prim, s_prim);\n\t\t\t\t\tds_dual = mult_vec(d_dual, s_dual);\n\t\t\t\t\tfigure;\n\t\t\t\t\tF0 = {zeros(grid3d.N), zeros(grid3d.N), zeros(grid3d.N)};\n\t\t\t\t\t[E, H] = fds(osc.in_omega0(), ...\n\t\t\t\t\t\t\t\t\tds_prim, ds_dual, ...\n\t\t\t\t\t\t\t\t\tmu, eps, ...\n\t\t\t\t\t\t\t\t\tF0, J, ...\n\t\t\t\t\t\t\t\t\tsolveropts.maxit, solveropts.tol, 'plot');\n\t\t\t\t\t% norm(A2 * ((1./e) .* (A1 * y)) - omega^2 * m .* y - A2 * (b ./ (-i*omega*e))) / norm(b) % Error for H-field wave equation.\n\t\t\t\telseif isequal(solveropts.method, 'aws')\n\t\t\t\t\tds_prim = mult_vec(d_prim, s_prim);\n\t\t\t\t\tds_dual = mult_vec(d_dual, s_dual);\n\t\t\t\t\tF0 = {zeros(grid3d.N), zeros(grid3d.N), zeros(grid3d.N)};\n% \t\t\t\t\tF0 = {rand(grid3d.N), rand(grid3d.N), rand(grid3d.N)};\n% \t\t\t\t\tF0 = {rand(1)*ones(grid3d.N), rand(1)*ones(grid3d.N), rand(1)*ones(grid3d.N)};\n\t\t\t\t\tcallback = maxwell(osc.in_omega0(), ...\n\t\t\t\t\t\t\t\t\tds_prim, ds_dual, ...\n\t\t\t\t\t\t\t\t\tmu, eps, ...\n\t\t\t\t\t\t\t\t\tF0, J, ...\n\t\t\t\t\t\t\t\t\tsolveropts.maxit, solveropts.tol);\n\t\t\t\t\twhile ~callback(); end\n\t\t\t\t\t[~, E, H] = callback();\n\t\t\t\tend\n\n\t\t\t\tE = neg_vec(flip_vec(E)); % pseudovector\n\t\t\t\tJ = neg_vec(flip_vec(J)); % pseudovector\n\t\t\t\tH = flip_vec(H);\n\t\t\tend\n\n\t\t\tpm.mark('solution calculation');\n\t\t\tif isequal(solveropts.method, 'iterative')\n\t\t\t\t%% Report the iterative solution process.\n\t\t\t\tsemilogy(1:length(resvec), resvec);\n\t\t\t\tfprintf('\\t# of iteration steps = %d\\n', iter);\n\t\t\t\tfprintf('\\trelative residual error = %e\\n', relres);\n\t\t\tend\n\t\t\tfprintf('solve for: %s-field\\n', char(solveropts.eqtype.f));\n\t\t\tfprintf('%s finishes.\\n\\n', mfilename);\n\t\tend\n\tend\n\t\n\tif solveropts.returnAandb\n%\t\t[A, b, g_from_f] = create_eq(solveropts.eqtype, solveropts.pml, osc.in_omega0(), eps, mu, s_factor, J, M, grid3d);\n\t\teq = MatrixEquation(solveropts.eqtype, solveropts.pml, osc.in_omega0(), eps, mu, s_factor, J, M, grid3d);\n\t\t\n\t\t[extra.A, extra.b] = eq.matrix_op();\n\t\t[~, ~, extra.GfromF] = eq.matrixfree_op();\n\tend\n\n\tif solveropts.returnDiv\n\t\t[Dive, Divm] = create_divs(ge, s_factor, grid3d);\n\t\textra.Dive = Dive;\n\t\textra.Divm = Divm;\n\tend\n\n\t% Construct Scalar3d objects.\n\tE_cell = cell(1, Axis.count);\n\tH_cell = cell(1, Axis.count);\n\tJ_cell = cell(1, Axis.count);\n\tM_cell = cell(1, Axis.count);\n\tfor w = Axis.elems\n\t\tif ~isempty(E)\n\t\t\tE_cell{w} = array2scalar(E{w}, grid3d, ge, FT.e, w, osc, PhysQ.E);\n\t\tend\n\t\t\n\t\tif ~isempty(H)\n\t\t\tH_cell{w} = array2scalar(H{w}, grid3d, ge, FT.h, w, osc, PhysQ.H);\n\t\tend\n\t\t\n\t\tJ_cell{w} = array2scalar(J{w}, grid3d, ge, FT.e, w, osc, PhysQ.J);\n\t\tM_cell{w} = array2scalar(M{w}, grid3d, ge, FT.h, w, osc, PhysQ.M);\n\tend\n\t\n\textra.grid3d = grid3d;\n\textra.J = J_cell;\n\textra.M = M_cell;\n\textra.eps = eps_node;\n\textra.mu = mu_node;\nend\n", "meta": {"author": "wsshin", "repo": "maxwellfdfd", "sha": "f7d583813781694c8a6f0533a91f56c2a78a9ee5", "save_path": "github-repos/MATLAB/wsshin-maxwellfdfd", "path": "github-repos/MATLAB/wsshin-maxwellfdfd/maxwellfdfd-f7d583813781694c8a6f0533a91f56c2a78a9ee5/io/maxwell_run.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.3174262591305011, "lm_q1q2_score": 0.17108742747700087}} {"text": "%% DEMO_aorta_build_passive_01\n% Below is a demonstration for:\n% \n% * Building geometry for a subject-specific aorta\n% * Creating the FEA mesh\n% * Coding the abaqus structure\n\n%% Keywords\n%\n% * ABAQUS\n% * aorta\n% * hexahedral elements, hex8\n\n%%\n\nclear; close all; clc;\n\n%% Directory\n\nsaveOn=0;\n\n%Define working directory\ndefaultFolder = fileparts(fileparts(mfilename('fullpath')));\nsavePath=fullfile(defaultFolder,'data','MAT');\nfileName='Concannon_aorta_segmentation.mat';\n\n%Define save names\nabaqusInpFileNamePart='tempModel';\nabaqusInpFileName=fullfile(savePath,[abaqusInpFileNamePart,'.inp']); %INP file name\nmatfileSaveName=fullfile(savePath,[abaqusInpFileNamePart,'.mat']); %INP file name\n\n%Load data as structure\ndataStruct=load(fullfile(savePath,fileName));\n\n%% Control parameters\n%Define smoothing Parameters\npointSpacing=1.7; %\nnumThickenSteps=2;\nsmoothFactorCentreLine=0.01; %Cubic smooth spline parameter [0-1] use empty to turn off\nsmoothFactorSegments=0.01; %Cubic smooth spline parameter [0-1], 0=straight line, 1=cubic\ntrunkSegmentReduceFactor=1; %\n\nnumSmoothTrunk=100; %\nnumSmoothPants_LAP=100; %Number of Laplacian smoothing iterations for Iliacs\nnumSmoothPants_HC=100; %Number of HC smoothing iterations for Iliacs\nnumSmoothBranchAttachments=100; %Number of smoothing iterations for branch origins (50)\nnumSmoothBranches=100; %Number of smoothing iterations for rest of branches\nnumOffsetSteps=1; %Number of steps taken to offset mesh by wall thickness\nnumSmoothOffset=2; %\nmethodSmoothOffset='LAP'; %Smoothing method Laplacian=agressive\nqualityMetricSmoothOffset=120; %\ndistSmoothGrowth=10; %\nnumHexSplit=1; %Split elements by factor\nt=1; %Time value corresponding to phase in cardiac cycle\n%Compressibility factor (Nolan, McGarry)\nkfactor=8.56;\n%Define thickness information\ndataStruct.WallThickness=[1.425\t0.9\t1\t1.025\t0.833333333\t0.891666667\t0.95\t0.975\t0.9\t0.825];\nthicknessIndexTransitionRegion=10; %Index of thickness at Iliac bifurcation\nthicknessIndexBifurcation=10; %Index of thickness distal to Iliac bifurcation\nthicknessIndicesBranches=[8 8 7 7 7 7 7]; %R_Renal_Ori,L_Renal_Ori,SMA_Ori,COE_Ori,LSA_Ori,LCCA_Ori,V_BCA_Ori\nwallThickness=dataStruct.WallThickness; %Raw data for wall thickness as a function of location\nnumThicknessLevels=numel(wallThickness);\n%Define material parameter information (from segment fitting [1-10])\nnumMaterials=100;\nmaterialIndicesSelect=linspace(1,10,10); %Plane indices to interpolate between\ndataStruct.mu=0.02; %Constant\ndataStruct.k1=0.0001; %Constant\ndataStruct.k2=1; %Constant\ndataStruct.kappa=0; %Constant\ndataStruct.theta1=90; %Circumferential\ndataStruct.theta2=-90; %Circumferential\ndataStruct.sigact=0; %Constant\ndataStruct.ke=0.1; %Constant\ndataStruct.Ee=[0.82 0.74 0.63 0.5 0.45 0.4 0.35 0.28 0.27 0.27];\ndataStruct.thetaE1=90; %Circumferential\ndataStruct.thetaE2=-90; %Circumferential\ndataStruct.iswitch=1; %[1=local; 2=global] %Constant\ndataStruct.xeps=[0.34 0.31 0.28 0.28 0.25 0.20 0.18 0.20 0.20 0.20];\ndataStruct.Vcol=[0.20 0.31 0.28 0.30 0.44 0.44 0.44 0.44 0.45 0.52];\ndataStruct.Vela=[0.30 0.28 0.25 0.22 0.22 0.22 0.24\t0.20 0.18 0.16];\ndataStruct.Vsmc=[0.20 0.20 0.20\t0.23 0.24 0.25 0.26\t0.26 0.27 0.27];\n%Acces data\nmu_data=dataStruct.mu;\nk1_data=dataStruct.k1;\nk2_data=dataStruct.k2;\nkappa_data=dataStruct.kappa;\ntheta1_data=dataStruct.theta1;\ntheta2_data=dataStruct.theta2;\nsigact_data=dataStruct.sigact;\nke_data=dataStruct.ke;\nEe_data=dataStruct.Ee;\nthetaE1_data=dataStruct.thetaE1;\nthetaE2_data=dataStruct.thetaE2;\nxeps_data=dataStruct.xeps;\nVcol_data=dataStruct.Vcol;\nVela_data=dataStruct.Vela;\nVsmc_data=dataStruct.Vsmc;\niswitch=dataStruct.iswitch;\n%Define plot color (black or white background)\ncolorMode=1;\nswitch colorMode\n case 1\n figStruct.ColorDef='white';\n figStruct.Color='w';\n case 2\n figStruct.ColorDef='black';\n figStruct.Color='k';\nend\n\n%% Access data structure components\nV_cent=dataStruct.Cent; %Centroid list\nsegmentCell=dataStruct.Points; %Lumen boundary coordinates\n\n%% Resampling aorta section contours\n%Resample boundary points so each plane has same number of points for lofting\n%Find number of points to use based on biggest circumference\nd=zeros(size(segmentCell,2),1);\nfor indNow=1:1:size(segmentCell,2)\n Vs_1=segmentCell{t,indNow}';\n d(indNow)=max(pathLength(Vs_1));\nend\nnSegment=round(max(d)/pointSpacing);\n%Resample\nsegmentCellSmooth=segmentCell;\nsegmentCellMean=segmentCell;\nw=ones(size(V_cent,1),1); %Cubic smoothing spline weights\nindexPlanePoints_V_cent=zeros(1,size(segmentCell,2)); %Indices of centre line points at sections\nfor indNow=1:1:size(segmentCell,2)\n %Resample section contour\n Vs_1=segmentCell{t,indNow}'; %Current contour\n Vs_1_smooth=evenlySampleCurve(Vs_1,nSegment,smoothFactorSegments,1); %Resample evenly\n Vs_1_mean=mean(Vs_1_smooth,1);\n segmentCellSmooth{t,indNow}=Vs_1_smooth';\n segmentCellMean{t,indNow}=Vs_1_mean;\n %Prepare for center line smoothing by setting weight vector\n [~,indVertex_1]=min(sqrt(sum((V_cent-Vs_1_mean(ones(size(V_cent,1),1),:)).^2,2))); %Index closest to section\n w(indVertex_1)=1e9; %Heigh weight at contour sections\n indexPlanePoints_V_cent(indNow)=indVertex_1; %Store index of closets\nend\n\n%% Smooth center line\n%Fit smoothing spline through centreline points for loft\nif ~isempty(smoothFactorCentreLine)\n V_cent_original=V_cent;\n d=pathLength(V_cent);\n V_cent = csaps(d,V_cent_original',smoothFactorCentreLine,d,w)'; %Smoothed\n cFigure(figStruct); hold on;\n h1=plotV(V_cent_original,'g.-','LineWidth',3,'MarkerSize',35);\n h2=plotV(V_cent,'r-','LineWidth',2,'MarkerSize',15);\n h3=plotV(V_cent(w==max(w),:),'b.','MarkerSize',40);\n legend([h1 h2 h3],{'Original','New','At contours'})\n axisGeom;\n drawnow;\nend\n\n%% Offsetting section curves outward if thickening is inward\nsegmentCellSmooth_pre=segmentCellSmooth;\n\nfor q=1:size(segmentCellSmooth,2)\n Vc=segmentCellSmooth{t,q}'; %Current curve vertices\n segmentCellSmooth{t,q}=curveOffset(Vc,wallThickness(q))';\nend\n\n\n%% Visualize offset curves\ncFigure(figStruct); hold on;\nplotV(V_cent,'b-','LineWidth',2,'MarkerSize',15);\nfor q=1:size(segmentCellSmooth,2)\n plotV(segmentCellSmooth_pre{t,q}','r.-','LineWidth',3,'MarkerSize',15);\n plotV(segmentCellSmooth{t,q}','g.-','LineWidth',3,'MarkerSize',15);\nend\naxisGeom;\ndrawnow;\n\n%% Perform main trunk loft\n% \n\n% Initialize figure with center line\nhf1=cFigure(figStruct); hold on;\nplotV(V_cent,'b.-','LineWidth',3,'markerSize',25);\naxisGeom;\ncamlight headlight;\ndrawnow;\nhp=gobjects(11,1);\nF_main_cell=cell(1,size(segmentCell,2)-1); %Faces cell\nV_main_cell=cell(1,size(segmentCell,2)-1); %Vertex cell\nC_main_gradient_cell=cell(1,size(segmentCell,2)-1); %Color/label dataa\nsegmentCurve_cell=cell(1,size(segmentCell,2)); %\n% Eb_main_cell=cell(1,size(segmentCell,2)-1);\nlogicBoundary=false(0,0);\nmaxC=0;\nindAdd=0;\n%Loft from one plane to next in loop along aorta\nfor indNow=1:1:(size(segmentCell,2)-1)\n Vs_1=segmentCell{t,indNow}';\n Vs_1=Vs_1(1:end-1,:);\n Vs_2=segmentCell{t,indNow+1}';\n Vs_2(1:end-1,:);\n Vs_1_smooth=segmentCellSmooth{t,indNow}';\n Vs_2_smooth=segmentCellSmooth{t,indNow+1}';\n Vs_1_mean=segmentCellMean{t,indNow};\n Vs_2_mean=segmentCellMean{t,indNow+1};\n d=pathLength(V_cent);\n %Get curve part for lofting\n [~,indVertex_1]=min(sqrt(sum((V_cent-Vs_1_mean(ones(size(V_cent,1),1),:)).^2,2))); %Start\n [~,indVertex_2]=min(sqrt(sum((V_cent-Vs_2_mean(ones(size(V_cent,1),1),:)).^2,2))); %End\n V_cent_part=V_cent(indVertex_1:indVertex_2,:);\n nPart=round(max(pathLength(V_cent_part))/pointSpacing);\n [V_cent_part_smooth] = evenlySampleCurve(V_cent_part,nPart,'spline',0);\n Vs_1_smooth=Vs_1_smooth-Vs_1_mean(ones(size(Vs_1_smooth,1),1),:);\n Vs_1_smooth=Vs_1_smooth+V_cent_part_smooth(ones(size(Vs_1_smooth,1),1),:);\n Vs_2_smooth=Vs_2_smooth-Vs_2_mean(ones(size(Vs_2_smooth,1),1),:);\n Vs_2_smooth=Vs_2_smooth+V_cent_part_smooth(size(V_cent_part_smooth,1)*ones(size(Vs_2_smooth,1),1),:);\n v1=vecnormalize(V_cent_part_smooth(2,:)-V_cent_part_smooth(1,:));\n [Q]=pointSetPrincipalDir(Vs_1_smooth-Vs_1_mean(ones(size(Vs_1_smooth,1),1),:));\n n1=Q(:,3)';\n if dot(v1,n1)<0\n n1=-n1;\n end\n v2=vecnormalize(V_cent_part_smooth(end,:)-V_cent_part_smooth(end-1,:));\n [Q]=pointSetPrincipalDir(Vs_2_smooth-Vs_2_mean(ones(size(Vs_2_smooth,1),1),:));\n n2=Q(:,3)';\n if dot(v2,n2)<0\n n2=-n2;\n end\n plotOn=0;\n nLoft=round(nPart/trunkSegmentReduceFactor);\n [Fs,Vs,Cs]=sweepLoft(Vs_1_smooth,Vs_2_smooth,n1,n2,V_cent_part_smooth,nLoft,0,plotOn);\n indLoftBottom=1:nLoft:size(Vs,1);\n indLoftTop=(nLoft:nLoft:size(Vs,1));\n segmentCurve_cell{indNow}=indLoftBottom+indAdd;\n if indNow==(size(segmentCell,2)-1)\n segmentCurve_cell{indNow+1}=indLoftTop+indAdd;\n end\n indAdd=indAdd+size(Vs,1);\n Eb=patchBoundary(Fs,Vs);\n logicBoundaryNow=false(size(Vs,1),1);\n logicBoundaryNow(unique(Eb(:)))=1;\n F_main_cell{indNow}=Fs;\n V_main_cell{indNow}=Vs;\n %Store color gradient information\n C_main_gradient_cell{indNow}=Cs+maxC;\n maxC=maxC+max(Cs);\n logicBoundary=[logicBoundary; logicBoundaryNow];\n \n %%\n % Plot Loft of main trunk\n figure(hf1);\n gpatch(Fs,Vs,'kw','kw',0.85);\n plotV(V_cent_part_smooth,'m.-','LineWidth',2,'markerSize',15);\n plotV(Vs_1_smooth,'r-','LineWidth',2);\n plotV(V_cent(indVertex_1,:),'r+','markerSize',25);\n plotV(Vs_2_smooth,'r-','LineWidth',2);\n axis off;\n xlim([140 200]); ylim([120 200]); zlim([20 370]);\n drawnow;\nend\n\n%% Material model\n%linearly interpolate parameters between planes\n% Get center line distance metric for each plane\nV_cent_crop=V_cent(indexPlanePoints_V_cent(1):indexPlanePoints_V_cent(end),:);\nindexPlanePoints_V_cent_crop=(indexPlanePoints_V_cent-indexPlanePoints_V_cent(1))+1;\nd=pathLength(V_cent_crop);\nd=d./max(d(:)); %Normalised curve length\ncurveLengthPlanePoints=d(indexPlanePoints_V_cent_crop);\n\n%mu_data=interp1(curveLengthPlanePoints(materialIndicesSelect),mu_data(materialIndicesSelect),curveLengthPlanePoints,'linear');\nEe_data=interp1(curveLengthPlanePoints(materialIndicesSelect),Ee_data(materialIndicesSelect),curveLengthPlanePoints,'linear');\nxeps_data=interp1(curveLengthPlanePoints(materialIndicesSelect),xeps_data(materialIndicesSelect),curveLengthPlanePoints,'linear');\nVcol_data=interp1(curveLengthPlanePoints(materialIndicesSelect),Vcol_data(materialIndicesSelect),curveLengthPlanePoints,'linear');\nVela_data=interp1(curveLengthPlanePoints(materialIndicesSelect),Vela_data(materialIndicesSelect),curveLengthPlanePoints,'linear');\n\n%% Main trunk\n% Join element sets to form main trunk and form colour information\nC_main=[];\nfor q=1:1:numel(F_main_cell)\n C_main=[C_main; q*ones(size(F_main_cell{q},1),1)];\nend\n[F_main,V_main,C_path]=joinElementSets(F_main_cell,V_main_cell,C_main_gradient_cell);\n%Scale color gradient for wall thickness interpolation\nC_path = rescale(C_path,1,numThicknessLevels);\nF_main=fliplr(F_main); %Invert orientation\n[F_main,V_main,ind1,indFix]=mergeVertices(F_main,V_main);\nfor q=1:1:numel(segmentCurve_cell)\n segmentCurve_cell{q}=indFix(segmentCurve_cell{q});\nend\nlogicBoundary=logicBoundary(ind1);\n\n% Perform Smoothing on main trunk\ncontrolParameter.n=numSmoothTrunk;\ncontrolParameter.Method='HC';\ncontrolParameter.RigidConstraints=find(logicBoundary); %Ensure smoothing cannot change coordinates of planes of interest\n[V_main]=patchSmooth(F_main,V_main,[],controlParameter);\n% Plot\ncFigure(figStruct);\nsubplot(1,2,1); hold on;\ntitle('Segments')\nplotV(V_cent,'k.-','LineWidth',3,'markerSize',25);\ngpatch(F_main,V_main,C_main,'k');\npatchNormPlot(F_main,V_main,1,'v'); %Check normals of elements all facing outward\nfor q=1:1:numel(segmentCurve_cell)\n plotV(V_main(segmentCurve_cell{q},:),'b.-','LineWidth',5,'markerSize',35);\nend\nplotV(V_main(logicBoundary,:),'r.','markerSize',25);\naxisGeom;\ncolormap(gca,gjet(250)); icolorbar;\ncamlight headlight;\nlighting gouraud;\nsubplot(1,2,2); hold on;\ntitle('Continuous')\nplotV(V_cent,'k.-','LineWidth',3,'markerSize',25);\ngpatch(F_main,V_main,C_path,'k');\nplotV(V_main(logicBoundary,:),'r.','markerSize',25);\n% patchNormPlot(F_main,V_main,1,'v');\naxisGeom;\ncolormap(gca,gjet(250)); colorbar;\ncamlight headlight;\nlighting gouraud;\ndrawnow;\n\n%%\n\nE_rings=[F_main(:,[1 2]); fliplr(F_main(:,[3 4]))];\nE_rings=uniqueIntegerRow(E_rings);\n\n%% Load Iliac Branch Data\n%Right Origin\nV_R_ori=dataStruct.R_Ori(1:end-1,:);\nV_R_ori=resampleCurve(V_R_ori,pointSpacing,1);\nV_R_ori(:,1)=V_R_ori(:,1);\nV_R_ori=curveOffset(V_R_ori,wallThickness(end));\n\n%Left Origin\nV_L_ori=dataStruct.L_Ori(1:end-1,:);\nV_L_ori=resampleCurve(V_L_ori,pointSpacing,1);\nV_L_ori(:,1)=V_L_ori(:,1)-1;\nV_L_ori=curveOffset(V_L_ori,wallThickness(end));\n\n%Left End\nV_L_Iliac=dataStruct.L_Iliac(1:end-1,:);\nV_L_Iliac=resampleCurve(V_L_Iliac,pointSpacing,1);\nV_L_Iliac=curveOffset(V_L_Iliac,wallThickness(end));\n\n%Right End\nV_R_Iliac=dataStruct.R_Iliac(1:end-1,:);\nV_R_Iliac=resampleCurve(V_R_Iliac,pointSpacing,1);\nV_R_Iliac=curveOffset(V_R_Iliac,wallThickness(end));\n\n%Bifurcation Data\nV_bifurc=dataStruct.bifurc;\nV_bifurc=curveOffset(V_bifurc,wallThickness(end));\n\n%% Resample curve to have same number of points as main trunk for loft\nEb_all=patchBoundary(F_main,V_main);\nEb_lowerSegment=patchBoundary(F_main(C_main==max(C_main),:),V_main);\nEb_lower=Eb_lowerSegment(all(ismember(Eb_lowerSegment,Eb_all),2),:);\nindLowerCurve=edgeListToCurve(Eb_lower);\nindLowerCurve=indLowerCurve(1:end-1);\nindLowerCurve=indLowerCurve(:);\nV_main_lowerCurve=V_main(indLowerCurve,:);\nif isPolyClockwise(V_bifurc)~=isPolyClockwise(V_main_lowerCurve)\n V_bifurc=flipud(V_bifurc);\nend\nV_bifurc=evenlySampleCurve(V_bifurc,size(V_main_lowerCurve,1),'spline',1); %resample\n[~,indMin]=minDist(V_main_lowerCurve(1,:),V_bifurc);\nif indMin>1\n V_bifurc=[V_bifurc(indMin:end,:); V_bifurc(1:indMin-1,:)];\nend\n% Mesh transition region\ncPar.closeLoopOpt=1;\ncPar.patchType='quad';\n[F_add,V_add,indStart,indEndBifurc]=polyLoftLinear(V_main_lowerCurve,V_bifurc,cPar);\nF_add=fliplr(F_add);\nC_add=ones(size(F_add,1),1);\nF_main=[F_main; F_add+size(V_main,1)];\nindEndBifurc=indEndBifurc+size(V_main,1);\nV_main=[V_main; V_add];\nC_main=[C_main; C_add+max(C_main)];\nC_path=[C_path; thicknessIndexTransitionRegion.*ones(size(C_add))];\n[F_main,V_main,~,indFix]=mergeVertices(F_main,V_main);\nindLowerCurve=indFix(indLowerCurve);\nindEndBifurc=indFix(indEndBifurc);\nE_rings=indFix(E_rings);\nfor q=1:1:numel(segmentCurve_cell)\n segmentCurve_cell{q}=indFix(segmentCurve_cell{q});\nend\n\n%% Perform Smoothing on Transition Region\nindTouch=indLowerCurve(:);\nnumSmoothGrowSteps=3;\nfor q=1:1:numSmoothGrowSteps\n logicFacesTouch=any(ismember(F_main,indTouch),2);\n indTouch=F_main(logicFacesTouch,:);\nend\nsmoothControlParameters.n=numSmoothPants_HC;\nsmoothControlParameters.Method='HC';\nsmoothControlParameters.RigidConstraints=[unique(F_main(~logicFacesTouch,:)); indLowerCurve];\n[V_main]=patchSmooth(F_main,V_main,[],smoothControlParameters);\n\n%% \n% Plot Main and Transition Region\ncFigure(figStruct); hold on;\ngpatch(F_main,V_main,logicFacesTouch,'none');\npatchNormPlot(F_main,V_main);\nplotV(V_main(indLowerCurve,:),'r.-','markerSize',25);\nplotV(V_main(indEndBifurc,:),'g.-','markerSize',25);\nfor q=1:1:numel(segmentCurve_cell)\n plotV(V_main(segmentCurve_cell{q},:),'b.-','LineWidth',5,'markerSize',35);\nend\naxisGeom;\ncolormap gjet;\ncamlight headlight;\nlighting flat;\ndrawnow;\n\n%% Pinched ellipse to two circle split\nns=ceil(abs(mean(V_main(indEndBifurc,3))-mean(V_R_ori(:,3)))/pointSpacing)+1;\nV_cell={V_main(indEndBifurc,:),V_R_ori,V_L_ori};\npatchType='quad';\nsplitMethod='nearMid';\ncontrolParSmooth.Method='LAP';\ncontrolParSmooth.n=numSmoothPants_LAP;\n[F_split,V_split,curveIndices,C_split]=splitCurveSetMesh(V_cell,ns,patchType,controlParSmooth,splitMethod,1);\n\n%%\n% Plot\ncFigure(figStruct); hold on;\n% gpatch(F_main,V_main,'kw','k');\ngpatch(F_split,V_split,C_split,'k');\npatchNormPlot(F_split,V_split);\nplotV(V_main(indEndBifurc,:),'r.-','markerSize',25);\n% plotV(V_split(curveIndices{1},:),'g.-','markerSize',25);\naxisGeom;\ncolormap gjet;\ncamlight headlight;\ndrawnow;\n\n%% Ensure all points for curves are clockwise for loft\nindEndBifurc_split=curveIndices{1}; indEndBifurc_split=indEndBifurc_split(:);\nindBranch11=curveIndices{2}; indBranch11=indBranch11(:);\nindBranch21=curveIndices{3}; indBranch21=indBranch21(:);\nV_branch12=evenlySampleCurve(V_L_Iliac,numel(indBranch11),'spline',1);\nV_branch22=evenlySampleCurve(V_R_Iliac,numel(indBranch21),'spline',1);\nV_branch11=V_split(indBranch11,:);\nif ~isPolyClockwise(V_branch11)\n indBranch11=flipud(indBranch11);\n V_branch11=V_split(indBranch11,:);\nend\nV_branch21=V_split(indBranch21,:);\nif ~isPolyClockwise(V_branch21)\n indBranch21=flipud(indBranch21);\n V_branch21=V_split(indBranch21,:);\nend\nif ~isPolyClockwise(V_branch22)\n V_branch22=flipud(V_branch22);\nend\nif ~isPolyClockwise(V_branch12)\n V_branch12=flipud(V_branch12);\nend\n[~,indMin]=min(V_branch12(:,1));\nif indMin>1\n V_branch12=[V_branch12(indMin:end,:); V_branch12(1:indMin-1,:)];\nend\n[~,indMin]=min(V_branch22(:,1));\nif indMin>1\n V_branch22=[V_branch22(indMin:end,:); V_branch22(1:indMin-1,:)];\nend\n\n%% Define points for iliac extensions and Loft\nV_loft_cell1{1}=V_branch11;\nV_loft_cell2{1}=V_branch12;\nV_loft_cell1{2}=V_branch21;\nV_loft_cell2{2}=V_branch22;\nV_loft_cent_cell{1}=dataStruct.Cent_I_R;\nV_loft_cent_cell{2}=dataStruct.Cent_I_L;\nF_iliac_cell=cell(1,2);\nV_iliac_cell=cell(1,2);\nfor q=1:1:2\n V1=V_loft_cell1{q};\n V2=V_loft_cell2{q};\n Vc=V_loft_cent_cell{q};\n [~,indMin]=minDist(mean(V1,1),Vc);\n if indMin>1\n Vc=Vc(indMin:end,:);\n end\n Vc(1,:)=mean(V1,1); %Overide first point with mean of segment\n np=ceil(max(pathLength(Vc))/pointSpacing)+1;\n Vc = evenlySampleCurve(Vc,np,'spline',0);\n \n %%\n % plot loft paths and profile\n cFigure(figStruct); hold on;\n plotV(V1,'b.-','markerSize',25);\n plotV(V2,'r.-','markerSize',25);\n plotV(Vc,'g.-','markerSize',25);\n axisGeom;\n colormap gjet;\n camlight headlight;\n lighting gouraud;\n drawnow;\n \n %%\n V2 = evenlySampleCurve(V2,size(V1,1),'spline',1);\n v1=vecnormalize(Vc(2,:)-Vc(1,:));\n [Q]=pointSetPrincipalDir(V1-Vc(ones(size(V1,1),1),:));\n n1=Q(:,3)';\n if dot(v1,n1)<0\n n1=-n1;\n end\n v2=vecnormalize(Vc(end,:)-Vc(end-1,:));\n [Q]=pointSetPrincipalDir(V2-Vc(size(Vc,1)*ones(size(V2,1),1),:));\n n2=Q(:,3)';\n if dot(v2,n2)<0\n n2=-n2;\n end\n pointSpacingNow=mean(diff(pathLength(V1)));\n np=ceil(max(pathLength(Vc))/pointSpacingNow);\n Vc = evenlySampleCurve(Vc,np,'spline',0);\n [F_loft,V_loft,C_loft]=sweepLoft(V1,V2,n1,n2,Vc,size(Vc,1),0,0);\n F_iliac_cell{q}=F_loft;\n V_iliac_cell{q}=V_loft;\nend\nF_branch1=F_iliac_cell{1};\nV_branch1=V_iliac_cell{1};\nF_branch2=F_iliac_cell{2};\nV_branch2=V_iliac_cell{2};\n\n%%\n% Plot Iliac extension Loft\ncFigure(figStruct); hold on;\n% gpatch(F_main,V_main,C_main,'k');\n% gpatch(F_main(C_main==max(C_main),:),V_main,'kw','none');\ngpatch(F_split,V_split,C_split,'k');\ngpatch(F_branch1,V_branch1,'gw');\npatchNormPlot(F_branch1,V_branch1);\ngpatch(F_branch2,V_branch2,'bw');\npatchNormPlot(F_branch2,V_branch2);\nplotV(V_main(indEndBifurc,:),'r.-','markerSize',25);\nplotV(V_branch11,'g.-','markerSize',25);\nplotV(V_branch12,'g.-','markerSize',25);\nplotV(V_branch21,'b.-','markerSize',25);\nplotV(V_branch22,'b.-','markerSize',25);\naxisGeom;\ncolormap gjet;\ncamlight headlight;\nlighting gouraud;\ndrawnow;\n\n%% Join Iliac extensions to Bifurcation\n[Fp,Vp,Cp]=joinElementSets({F_split,F_branch1,F_branch2},{V_split,V_branch1,V_branch2});\n[Fp,Vp,~,indFix]=mergeVertices(Fp,Vp);\nEb_p=patchBoundary(Fp,Vp);\nindEndBifurc_split=indFix(indEndBifurc_split);\nindBranch11=indFix(indBranch11);\nindBranch21=indFix(indBranch21);\n%%Smooth Iliacs\nindTouch=[indBranch11(:); indBranch21(:)];\nnumSmoothGrowSteps=3;\nfor q=1:1:numSmoothGrowSteps\n logicFacesTouch=any(ismember(Fp,indTouch),2);\n indTouch=Fp(logicFacesTouch,:);\nend\nsmoothControlParameters.n=numSmoothPants_HC;\nsmoothControlParameters.Method='HC';\nsmoothControlParameters.RigidConstraints=[unique(Fp(~logicFacesTouch,:)); indEndBifurc_split];\n[Vp]=patchSmooth(Fp,Vp,[],smoothControlParameters);\n\n%%\n% Plot Iliacs\ncFigure(figStruct); hold on;\ngpatch(Fp,Vp,logicFacesTouch,'k');\npatchNormPlot(Fp,Vp);\nplotV(Vp(indBranch11,:),'r-','LineWidth',3)\nplotV(Vp(indBranch21,:),'r-','LineWidth',3)\naxisGeom;\ncolormap gjet;\ncamlight headlight;\nlighting gouraud;\ndrawnow;\n\n%%\n% Add to main trunk\nF_main=[F_main; Fp+size(V_main,1)];\nindBranch11=indBranch11+size(V_main,1);\nindBranch21=indBranch21+size(V_main,1);\nV_main=[V_main; Vp];\nC_main=[C_main; Cp+max(C_main)];\nC_path=[C_path; thicknessIndexBifurcation.*ones(size(Cp))];\nC_path_mat=C_path; %Copy over path color data for material assignments\n[F_main,V_main,~,indFix]=mergeVertices(F_main,V_main);\nindLowerCurve=indFix(indLowerCurve);\nindBranch11=indFix(indBranch11);\nindBranch21=indFix(indBranch21);\nE_rings=indFix(E_rings);\n\nfor q=1:1:numel(segmentCurve_cell)\n segmentCurve_cell{q}=indFix(segmentCurve_cell{q});\nend\n%\nindTouch=[indLowerCurve(:); indBranch11(:); indBranch21(:)];\nnGrowthSteps=round(distSmoothGrowth/pointSpacing);\nfor q=1:1:numSmoothGrowSteps\n logicFacesTouch=any(ismember(F_main,indTouch),2);\n indTouch=F_main(logicFacesTouch,:);\nend\nind1=F_main(~logicFacesTouch,:);\nindRigid=unique([ind1(:); indBranch11(:); indBranch21(:)]);\nsmoothControlParameters.Tolerance=0.01;\nsmoothControlParameters.n=numSmoothPants_HC;\nsmoothControlParameters.Method='HC';\nsmoothControlParameters.RigidConstraints=indRigid;\n[V_main]=patchSmooth(F_main,V_main,[],smoothControlParameters);\n%\ncFigure(figStruct); hold on;\ngpatch(F_main,V_main,logicFacesTouch,'k');\n% patchNormPlot(F_main,V_main);\nplotV(V_main(indLowerCurve,:),'r.-','markerSize',25);\nplotV(V_main(indBranch11,:),'r.-','markerSize',25);\nplotV(V_main(indBranch21,:),'r.-','markerSize',25);\nfor q=1:1:numel(segmentCurve_cell)\n plotV(V_main(segmentCurve_cell{q},:),'b.-','LineWidth',5,'markerSize',35);\nend\naxisGeom;\ncolormap gjet;\ncamlight headlight;\nlighting gouraud;\ndrawnow;\n\n%% Load Branch data\n\n%Other branches\nV_L_Renal_Ori=dataStruct.L_Renal_Ori(1:end-1,:);\nV_L_Renal_Ori=resampleCurve(V_L_Renal_Ori,pointSpacing,1);\nV_L_Renal_Ori=curveOffset(V_L_Renal_Ori,wallThickness(7));\nV_L_Renal=dataStruct.L_Renal(1:end-1,:);\nV_L_Renal=resampleCurve(V_L_Renal,pointSpacing,1);\nV_L_Renal=curveOffset(V_L_Renal,wallThickness(7));\nV_Cent_L_Renal=dataStruct.Cent_Renal_L;\nV_Cent_L_Renal=resampleCurve(V_Cent_L_Renal,pointSpacing,0);\n\nV_R_Renal_Ori=dataStruct.R_Renal_Ori(1:end-1,:);\nV_R_Renal_Ori=resampleCurve(V_R_Renal_Ori,pointSpacing,1);\nV_R_Renal_Ori=curveOffset(V_R_Renal_Ori,wallThickness(7));\n\nV_R_Renal=dataStruct.R_Renal(1:end-1,:);\nV_R_Renal=resampleCurve(V_R_Renal,pointSpacing,1);\nV_R_Renal=curveOffset(V_R_Renal,wallThickness(7));\nV_Cent_R_Renal=dataStruct.Cent_Renal_R;\nV_Cent_R_Renal=resampleCurve(V_Cent_R_Renal,pointSpacing,0);\n\nV_SMA_Ori=dataStruct.SMA_O(1:end-1,:);\nV_SMA_Ori=resampleCurve(V_SMA_Ori,pointSpacing,1);\nV_SMA_Ori=curveOffset(V_SMA_Ori,wallThickness(7));\n\nV_SMA=dataStruct.SMA(1:end-1,:);\nV_SMA=resampleCurve(V_SMA,pointSpacing,1);\nV_SMA=curveOffset(V_SMA,wallThickness(7));\nV_Cent_SMA=dataStruct.Cent_SMA;\nV_Cent_SMA=resampleCurve(V_Cent_SMA,pointSpacing,0);\nV_COE_Ori=dataStruct.COE_O(1:end-1,:);\nV_COE_Ori=resampleCurve(V_COE_Ori,pointSpacing,1);\nV_COE_Ori=curveOffset(V_COE_Ori,wallThickness(7));\nV_COE=dataStruct.COE(1:end-1,:);\nV_COE=resampleCurve(V_COE,pointSpacing,1);\nV_COE=curveOffset(V_COE,wallThickness(7));\nV_Cent_COE=dataStruct.Cent_Coeliac;\nV_Cent_COE=resampleCurve(V_Cent_COE,pointSpacing,0);\nV_BCA_Ori=dataStruct.BCA_O(1:end-1,:);\nV_BCA_Ori=resampleCurve(V_BCA_Ori,pointSpacing,1);\nV_BCA_Ori=curveOffset(V_BCA_Ori,wallThickness(2));\nV_BCA=dataStruct.BCA(1:end-1,:);\nV_BCA=resampleCurve(V_BCA,pointSpacing,1);\nV_BCA=curveOffset(V_BCA,wallThickness(2));\nV_Cent_BCA=dataStruct.Cent_BCA;\nV_Cent_BCA=resampleCurve(V_Cent_BCA,pointSpacing,0);\nV_LCCA_Ori=dataStruct.LCCA_O(1:end-1,:);\nV_LCCA_Ori=resampleCurve(V_LCCA_Ori,pointSpacing,1);\nV_LCCA_Ori=curveOffset(V_LCCA_Ori,wallThickness(2));\nV_LCCA=dataStruct.LCCA(1:end-1,:);\nV_LCCA=resampleCurve(V_LCCA,pointSpacing,1);\nV_LCCA=curveOffset(V_LCCA,wallThickness(2));\nV_Cent_LCCA=dataStruct.Cent_LCCA;\nV_Cent_LCCA=resampleCurve(V_Cent_LCCA,pointSpacing,0);\nV_LSA_Ori=dataStruct.LSA_O(1:end-1,:);\nV_LSA_Ori=resampleCurve(V_LSA_Ori,pointSpacing,1);\nV_LSA_Ori=curveOffset(V_LSA_Ori,wallThickness(2));\nV_LSA=dataStruct.LSA(1:end-1,:);\nV_LSA=resampleCurve(V_LSA,pointSpacing,1);\nV_LSA=curveOffset(V_LSA,wallThickness(2));\nV_Cent_LSA=dataStruct.Cent_LSA;\nV_Cent_LSA=resampleCurve(V_Cent_LSA,pointSpacing,0);\n\n% Plot\ncFigure(figStruct); hold on;\ngpatch(F_main,V_main,C_main,0.65);\nplotV(V_R_Renal_Ori,'r.-','markerSize',5);\nplotV(V_R_Renal,'w.-','markerSize',5);\nplotV(V_L_Renal_Ori,'g.-','markerSize',5);\nplotV(V_L_Renal,'w.-','markerSize',5);\nplotV(V_COE_Ori,'w.-','markerSize',5);\nplotV(V_COE,'w.-','markerSize',5);\nplotV(V_SMA_Ori,'w.-','markerSize',5);\nplotV(V_SMA,'w.-','markerSize',5);\nplotV(V_BCA_Ori,'w.-','markerSize',5);\nplotV(V_BCA,'w.-','markerSize',5);\nplotV(V_LCCA_Ori,'w.-','markerSize',5);\nplotV(V_LCCA,'w.-','markerSize',5);\nplotV(V_LSA_Ori,'w.-','markerSize',5);\nplotV(V_LSA,'w.-','markerSize',5);\nxlim([140 200]); ylim([120 200]); zlim([20 370]);\naxisGeom;\ncolormap jet;\ncamlight headlight;\nlighting gouraud;\ndrawnow;\n\n%% Perform Extrude cut\n% Find Centroid of Ori and shoot vector in direction of nearest Centreline\n% point. Apply same vector to each point on Ori and every element on the\n% main trunk wall it touches is deleted. Loft then from deleted elements of\n% main to each branch ori\nV_cut=V_R_Renal_Ori;\nV_cut_cell={V_R_Renal_Ori,V_L_Renal_Ori,V_SMA_Ori,V_COE_Ori,...\n V_LSA_Ori,V_LCCA_Ori,V_BCA_Ori};\n%Loop over connections\nsmoothControlParameters.n=numSmoothBranchAttachments;\nsmoothControlParameters.Method='HC';\nhw = waitbar(0,'Please wait...');\nnumSteps=numel(V_cut_cell);\nV_endCurve_cell=cell(1,numSteps);\nC_main_max=max(C_main)+1;\nfor q=1:1:numSteps\n waitbar(q/numSteps,hw,['Processing case ',num2str(q),' of ',num2str(numSteps)]);\n VF=patchCentre(F_main,V_main); %Face centre coordinates\n [~,indMin]=minDist(mean(V_cut_cell{q},1),VF);\n c=C_path(indMin);\n [F_main,V_main,C_main,indEnd,logicRemoveFaces,segmentCurve_cell,E_rings]=circleCutExtrude(F_main,V_main,C_main,V_cent,V_cut_cell{q},pointSpacing,0,smoothControlParameters,segmentCurve_cell,E_rings);\n numFacesNewFeature=nnz(C_main==max(C_main));\n C_path=[C_path(~logicRemoveFaces); thicknessIndicesBranches(q)*ones(numFacesNewFeature,1)];\n C_path_mat=[C_path_mat(~logicRemoveFaces); c*ones(numFacesNewFeature,1)];\n V_endCurve_cell{q}=V_main(indEnd,:);\nend\nclose(hw);\n% plot\ncFigure(figStruct); hold on;\ngpatch(F_main,V_main,C_path,'k',1);\nfor q=1:1:numel(V_endCurve_cell)\n plotV(V_endCurve_cell{q},'m.-','markerSize',25);\nend\naxisGeom;\ncolormap gjet; colorbar;\ncamlight headlight;\ndrawnow;\n% plot\ncFigure(figStruct); hold on;\ngpatch(F_main,V_main,C_path_mat,'k',1);\naxisGeom;\ncolormap gjet; colorbar;\ncamlight headlight;\ndrawnow;\n\n% Resample branch ends and sweep\nV_loft_cell1=V_endCurve_cell;\nV_loft_cell2={V_R_Renal,V_L_Renal,V_SMA,V_COE,...\n V_LSA,V_LCCA,V_BCA};\nV_loft_cent_cell={V_Cent_R_Renal,V_Cent_L_Renal,V_Cent_SMA,V_Cent_COE,V_Cent_LSA,V_Cent_LCCA,V_Cent_BCA};\nF_branch_cell=cell(1,numel(V_endCurve_cell));\nV_branch_cell=cell(1,numel(V_endCurve_cell));\nindBranchTop_cell=cell(1,numel(V_endCurve_cell));\nindBranchBottom_cell=cell(1,numel(V_endCurve_cell));\nfor q=1:1:numel(V_endCurve_cell)\n V1=V_loft_cell1{q};\n pointSpacingNow=mean(diff(pathLength(V1)));\n V2=V_loft_cell2{q};\n Vc=V_loft_cent_cell{q};\n np=ceil(max(pathLength(Vc))/pointSpacingNow);\n Vc = evenlySampleCurve(Vc,np,'spline',0);\n V2 = evenlySampleCurve(V2,size(V1,1),'spline',1);\n v1=vecnormalize(Vc(2,:)-Vc(1,:));\n [Q]=pointSetPrincipalDir(V1-Vc(ones(size(V1,1),1),:));\n n1=Q(:,3)';\n if dot(v1,n1)<0\n n1=-n1;\n end\n v2=vecnormalize(Vc(end,:)-Vc(end-1,:));\n [Q]=pointSetPrincipalDir(V2-Vc(size(Vc,1)*ones(size(V2,1),1),:));\n n2=Q(:,3)';\n if dot(v2,n2)<0\n n2=-n2;\n end\n b2=vecnormalize(V2(2,:)-V2(1,:));\n a2=vecnormalize(V2(1,:)-mean(V2,1));\n c2=cross(b2,a2);\n if dot(n2,c2)<0\n V2=flipud(V2);\n end\n [F_loft,V_loft,C_loft]=sweepLoft(V1,V2,n1,n2,Vc,size(Vc,1),0,0);\n F_loft=fliplr(F_loft);\n indLoftBottom=1:size(Vc,1):size(V_loft,1);\n indLoftTop=(size(Vc,1):size(Vc,1):size(V_loft,1));\n F_branch_cell{q}=F_loft;\n V_branch_cell{q}=V_loft;\n if q>1\n sizAll=cellfun(@(x) size(x,1),V_branch_cell);\n indBranchTop_cell{q}=indLoftTop+sum(sizAll(1:q-1));\n indBranchBottom_cell{q}=indLoftBottom+sum(sizAll(1:q-1));\n else\n indBranchTop_cell{q}=indLoftTop;\n indBranchBottom_cell{q}=indLoftBottom;\n end\n % The below plot highlights each loft path in a loop\n % cFigure(figStruct); hold on;\n % title(num2str(q))\n % gpatch(F_main,V_main,'kw','none',0.5);\n % gpatch(F_loft,V_loft,'rw','r',1);\n % plotV(V_loft(indLoftBottom,:),'b.-','LineWidth',3);\n % plotV(V_loft(indLoftTop,:),'g.-','LineWidth',3);\n % % plotV(V1,'r.-','LineWidth',3);\n % % plotV(V2,'b.-','LineWidth',3);\n % % plotV(Vc,'k.-','LineWidth',3);\n % % quiverVec(Vc(1,:),n1,10,'k');\n % % quiverVec(Vc(end,:),n2,10,'k');\n % axisGeom;\n % camlight headlight;\n % drawnow;\nend\n%Join branches together\nVF=patchCentre(F_main,V_main);\n%Joining branches\n[F_branch,V_branch,C_branch]=joinElementSets(F_branch_cell,V_branch_cell);\n%Adding branches to main thing\nnumVerticesInitial=size(V_main,1);\nF_main=[F_main; F_branch+numVerticesInitial];\nV_main=[V_main; V_branch];\nC_main=[C_main; C_branch+max(C_main)];\nC_path_branch=thicknessIndicesBranches(C_branch);\nC_path=[C_path; C_path_branch(:)];\n\n%%\n% plot\ncFigure(figStruct); hold on;\ngpatch(F_main,V_main,'kw','none',0.5);\naxisGeom;\ncolormap gjet; colorbar;\ncamlight headlight;\ndrawnow;\nfor q=1:1:numel(V_cut_cell)\n V_mean_now=mean(V_cut_cell{q},1);\n plotV(V_mean_now,'r.','markerSize',25);\n [~,indMin]=minDist(V_mean_now,VF);\n plotV(VF(indMin,:),'b.','markerSize',25);\n c=C_path_mat(indMin);\n C_path_mat=[C_path_mat; c*ones(size(F_branch_cell{q},1),1)];\nend\n\n%%\n\n%Fix curve indices for joining sets\nfor q=1:1:numel(indBranchBottom_cell)\n indBranchTop_cell{q}=indBranchTop_cell{q}+numVerticesInitial;\n indBranchBottom_cell{q}=indBranchBottom_cell{q}+numVerticesInitial;\nend\n%merging nodes together\n[F_main,V_main,~,indFix]=mergeVertices(F_main,V_main);\n%Fix curve indices for merging\nfor q=1:1:numel(indBranchBottom_cell)\n indBranchTop_cell{q}=indFix(indBranchTop_cell{q})';\n indBranchBottom_cell{q}=indFix(indBranchBottom_cell{q})';\nend\nfor q=1:1:numel(segmentCurve_cell)\n segmentCurve_cell{q}=indFix(segmentCurve_cell{q});\nend\n\nE_rings=indFix(E_rings);\n\n% Snapping material color data to number of materials\nC_path_index=C_path_mat;\nC_path_mat=round(rescale(C_path_mat,1,numMaterials));\n\n%%\n% plot\ncFigure(figStruct); hold on;\ngpatch(F_main,V_main,C_path,'k',1);\naxisGeom;\ncolormap gjet; colorbar;\ncamlight headlight;\ndrawnow;\n\n%%\n%Smoothing of Branches\nindTouch=[indBranchBottom_cell{:}];\nnumSmoothGrowSteps=3;\nfor q=1:1:numSmoothGrowSteps\n logicFacesTouch=any(ismember(F_main,indTouch),2);\n indTouch=F_main(logicFacesTouch,:);\nend\n\nsmoothControlParameters.n=numSmoothBranches;\nsmoothControlParameters.Method='HC';\nsmoothControlParameters.RigidConstraints=unique(F_main(~logicFacesTouch,:));\n[V_main]=patchSmooth(F_main,V_main,[],smoothControlParameters);\n\n% Interpolating thicknesses\nthicknessData=dataStruct.WallThickness; %Thickness data\nindexData=1:1:numel(thicknessData); %Index data for x-axis for interpolation\nC_thickness=interp1(indexData,thicknessData,C_path,'spline');\n\n%%\n% plot\nhf=cFigure(figStruct); hold on;\ngtitle('Wall Thickness')\ngpatch(F_main,V_main,C_thickness,'k',1);\naxisGeom;\ncolormap(gjet(250)); colorbar;\ncamlight headlight;\ndrawnow;\n\n%% Inverting offset direction\n%Converting face thickness data to vertex data\nnodalThickness=faceToVertexMeasure(F_main,V_main,C_thickness);\n[~,~,N]=patchNormal(F_main,V_main);\n\n%%\n% plot\ncFigure(figStruct); hold on;\ngpatch(F_main,V_main,'kw','kw',0.5);\ntitle('Mesh Offset')\nquiverVec(V_main,-N.*nodalThickness,[],nodalThickness);\naxisGeom;\ncolormap(gjet(250)); colorbar;\ncamlight headlight;\ndrawnow;\n\n%% Thicken to create hexahedral elements\n[ET,VT,Fp1,Fp2]=patchThick(F_main,V_main,-1,nodalThickness,numThickenSteps);\nCT=repmat((1:1:size(F_main,1))',numThickenSteps,1);\n\nET=ET(:,[5:8 1:4]);\nFT_inner=Fp2;\nFT_outer=Fp1;\n\n[~,logicPositive]=hexVol(ET,VT);\n% logicPositive\nif any(logicPositive==0)\n error('Negative hex volume found');\nend\n\nC_ET_path_mat_index=C_path_mat;\nC_ET_path_index=C_path_index;\nindicesNodesInner=unique(FT_inner(:));\n% Find elements touching the branch ends\nindBranchTopAll=[indBranchTop_cell{:}]; %+size(V_main,1)*numThickenSteps;\nlogicBranchEndElement=any(ismember(ET,indBranchTopAll),2);\n\n%% Retrieve segment curve indices\nsegmentCurve_cell_outer=segmentCurve_cell;\nfor q=1:1:numel(segmentCurve_cell)\n segmentCurve_cell{q}=segmentCurve_cell{q}+size(V_main,1)*numThickenSteps;\nend\n\n[FT,CFT]=element2patch(ET,CT);\n\n%%\n% plot\ncFigure(figStruct); hold on;\ngpatch(FT,VT,CFT,'k',0.5);\ngpatch(FT_inner,VT,'g','k',1);\n\nfor q=1:1:numel(segmentCurve_cell)\n plotV(VT(segmentCurve_cell{q},:),'g.-','LineWidth',5,'markerSize',15);\nend\n\nfor q=1:1:numel(segmentCurve_cell)\n plotV(VT(segmentCurve_cell_outer{q},:),'r.-','LineWidth',5,'markerSize',15);\nend\n\naxisGeom;\ncolormap(gjet(250)); colorbar;\ncamlight headlight;\ndrawnow;\n\n%% Grouping ring edges and offset so they are on the inside\n\n%Offset indices inward\nE_rings=E_rings+size(V_main,1)*numThickenSteps;\n\n%Group indices to form rings\noptionStruct.outputType='label';\nG_rings=tesgroup(E_rings,optionStruct);\n\n%Compose ring cell\nringCurve_cell=cell(1,max(G_rings));\nfor q=1:1:max(G_rings)\n indList=edgeListToCurve(E_rings(G_rings==q,:)); %1=Ring number\n indList=indList(1:end-1);\n ringCurve_cell{q}=indList;\nend\n\n%% \n% plot\ncFigure(figStruct); hold on;\ngpatch(FT,VT,'kw','none',0.5);\n\nplotColors=gjet(max(G_rings));\nfor q=1:1:max(G_rings)\n hp=plotV(VT(ringCurve_cell{q},:),'b.-','LineWidth',5,'markerSize',15);\n% hp.Color=plotColors(q,:);\nend\n\naxisGeom;\ncolormap(gjet(250)); colorbar;\ncamlight headlight;\ndrawnow;\n\n%% Create color data for hex elements\n\nC_ET_path_mat_index=C_ET_path_mat_index(CT);\nC_ET_path_index=C_ET_path_index(CT);\nlogicBranchEndElement=logicBranchEndElement(CT); %Colors for original element indices (and sweeping steps)\n%%Define Inner Surface Set\nlogicElementsInner=any(ismember(ET,indicesNodesInner),2);\nindicesElementsInner=find(logicElementsInner);\n\n%%\n% plot\ncFigure(figStruct); hold on;\ngpatch(FT_inner,VT,'gw','none',0.5);\ngpatch(FT_outer,VT,'rw','none',0.5);\npatchNormPlot(FT_inner,VT)\naxisGeom;\ncolormap(gjet(250)); colorbar;\ncamlight headlight;\ndrawnow;\n\n%% Material Properties\n% Assign element material parameters\n% Derive interpolatable parameters [Vcol,Vela,Ee,xeps,mu]\nindexData=1:1:numel(xeps_data);\nindexDataInterp=linspace(1,numel(xeps_data),numMaterials);\nindexData_ET=1:1:numMaterials;\n\nxeps_vector=interp1(indexData,xeps_data,indexDataInterp,'spline');\nxeps_ET=interp1(indexData_ET,xeps_vector,C_ET_path_mat_index,'spline');\nEe_vector=interp1(indexData,Ee_data,indexDataInterp,'spline');\nEe_ET=interp1(indexData_ET,Ee_vector,C_ET_path_mat_index,'spline');\nVela_vector=interp1(indexData,Vela_data,indexDataInterp,'spline');\nVela_ET=interp1(indexData_ET,Vela_vector,C_ET_path_mat_index,'spline');\nVcol_vector=interp1(indexData,Vcol_data,indexDataInterp,'spline');\nVcol_ET=interp1(indexData_ET,Vcol_vector,C_ET_path_mat_index,'spline');\nVsmc_vector=interp1(indexData,Vsmc_data,indexDataInterp,'spline');\nVsmc_ET=interp1(indexData_ET,Vsmc_vector,C_ET_path_mat_index,'spline');\n\n%% Define Branch Ends Set\n[FT,CFT]=element2patch(ET,logicElementsInner);\n[~,CFT_logicBranchEndElement]=element2patch(ET,logicBranchEndElement);\n[~,CFT_path_mat]=element2patch(ET,C_ET_path_mat_index);\n[~,xeps_FT]=element2patch(ET,xeps_ET);\n[~,Ee_FT]=element2patch(ET,Ee_ET);\n[~,Vela_FT]=element2patch(ET,Vela_ET);\n[~,Vcol_FT]=element2patch(ET,Vcol_ET);\n[~,Vsmc_FT]=element2patch(ET,Vsmc_ET);\nindBoundary=tesBoundary(FT,VT);\nFb=FT(indBoundary,:);\nF1=sort(ET(:,[1 2 3 4]),2);\nF2=sort(ET(:,[5 6 7 8]),2);\nFT_boundary=FT(indBoundary,:);\nsizVirt=size(VT,1)*ones(1,size(FT,2));\nindVirt_F1=sub2indn(sizVirt,F1);\nindVirt_F2=sub2indn(sizVirt,F2);\nindVirt_FT_boundary=sub2indn(sizVirt,sort(FT_boundary,2));\nindVirt_FT=sub2indn(sizVirt,sort(FT,2));\nCFT_logicBranchEndElement=CFT_logicBranchEndElement & ismember(indVirt_FT,indVirt_FT_boundary); %Only keep boundary members\nCFT_logicBranchEndElement=CFT_logicBranchEndElement & ~ismember(indVirt_FT,indVirt_F1); %Cant be member of top\nCFT_logicBranchEndElement=CFT_logicBranchEndElement & ~ismember(indVirt_FT,indVirt_F2); %Cant be member of bottom\n\n%Nodes for boundary conditions\nindNodesFix=FT(CFT_logicBranchEndElement,:);\nindNodesFix=unique(indNodesFix(:));\n\n%%\n% plot full mesh\ncFigure(figStruct); hold on;\ngpatch(FT,VT,CFT_logicBranchEndElement,'r',1);\nxlim([140 200]); ylim([120 200]); zlim([20 370]);\naxisGeom;\ncolormap(gjet(250)); colorbar;\ncamlight headlight;\ndrawnow;\n\n%%\n% plot interpolated parameters \n\ncFigure(figStruct);\nsubplot(2,3,1);hold on;\ntitle('Indexing color');\ngpatch(FT(indBoundary,:),VT,CFT_path_mat(indBoundary,:),'none',1);\naxisGeom;\ncolormap(gjet(250)); colorbar;\ncamlight headlight;\n\nsubplot(2,3,2);hold on;\ntitle('xeps');\ngpatch(FT(indBoundary,:),VT,xeps_FT(indBoundary,:),'none',1);\naxisGeom;\ncolormap(gjet(250)); colorbar;\ncamlight headlight;\n\nsubplot(2,3,3);hold on;\ntitle('Ee');\ngpatch(FT(indBoundary,:),VT,Ee_FT(indBoundary,:),'none',1);\naxisGeom;\ncolormap(gjet(250)); colorbar;\ncaxis([min(Ee_data) max(Ee_data)]);\ncamlight headlight;\n\nsubplot(2,3,4);hold on;\ntitle('Vcol');\ngpatch(FT(indBoundary,:),VT,Vcol_FT(indBoundary,:),'none',1);\naxisGeom;\ncolormap(gjet(250)); colorbar;\ncamlight headlight;\n%axis off\n\nsubplot(2,3,5);hold on;\ntitle('Vela');\ngpatch(FT(indBoundary,:),VT,Vela_FT(indBoundary,:),'none',1);\naxisGeom;\ncolormap(gjet(250)); colorbar;\ncamlight headlight;\n%axis off\ndrawnow;\n\n%End of Model Generation steps\n\n%% Create ABAQUS structure\n% Setup structure to define an Abaqus inp file\n\n%%--> Heading\nabaqus_spec.Heading.COMMENT{1}='Job name: AORTA';\n\n%%--> Preprint\nabaqus_spec.Preprint.ATTR.echo='NO';\nabaqus_spec.Preprint.ATTR.model='NO';\nabaqus_spec.Preprint.ATTR.history='NO';\nabaqus_spec.Preprint.ATTR.contact='NO';\n\n%--> Part\n\n% Node\nnodeIds=(1:1:size(VT,1))';\nabaqus_spec.Part.COMMENT='This section defines the part geometry in terms of nodes and elements';\nabaqus_spec.Part.ATTR.name='Aorta';\nabaqus_spec.Part.Node={nodeIds,VT};\n\n% Element\nelementIds=(1:1:size(ET,1))';\nabaqus_spec.Part.Element{1}.ATTR.type='C3D8';\nabaqus_spec.Part.Element{1}.VAL={elementIds,ET};\n\n% Element sets\nfor q=1:1:numMaterials\n elementIdsSetNow=find(C_ET_path_mat_index==q);\n abaqus_spec.Part.Elset{q}.ATTR.elset=['MatSet-',num2str(q)];\n abaqus_spec.Part.Elset{q}.VAL=elementIdsSetNow';\nend\n\nsurfaceElementSetName='elementSetInnerSurface';\nabaqus_spec.Part.Elset{numMaterials+1}.ATTR.elset=surfaceElementSetName;\nabaqus_spec.Part.Elset{numMaterials+1}.ATTR.internal=''; %Remains hidden uppon import\nabaqus_spec.Part.Elset{numMaterials+1}.VAL=indicesElementsInner(:)';\n\n% Surfaces\nsidePick=1;\nabaqus_spec.Part.Surface{1}.ATTR.type='ELEMENT';\nabaqus_spec.Part.Surface{1}.ATTR.name=[surfaceElementSetName,'_side',num2str(sidePick)];\nabaqus_spec.Part.Surface{1}.VAL={surfaceElementSetName,['S',num2str(sidePick)]};\n\n% Sections\nfor q=1:1:numMaterials\n elementIdsSetNow=find(C_ET_path_mat_index==q);\n abaqus_spec.Part.Solid_section{q}.ATTR.elset=['MatSet-',num2str(q)];\n abaqus_spec.Part.Solid_section{q}.ATTR.material=['Mat_',num2str(q)];\nend\n\n%--> Assembly\nabaqus_spec.Assembly.ATTR.name='Assembly-1';\nabaqus_spec.Assembly.Instance.ATTR.name='Aorta-assembly';\nabaqus_spec.Assembly.Instance.ATTR.part='Aorta';\n\nabaqus_spec.Assembly.Nset{1}.ATTR.nset='NSet_Inner';\nabaqus_spec.Assembly.Nset{1}.ATTR.instance=abaqus_spec.Assembly.Instance.ATTR.name;\nabaqus_spec.Assembly.Nset{1}.VAL=indicesNodesInner;\n\n%Add segment curve node sets\nfor q=1:1:numel(segmentCurve_cell)\n indNow=numel(abaqus_spec.Assembly.Nset)+1;\n abaqus_spec.Assembly.Nset{indNow}.ATTR.nset=['Segment',num2str(q)];\n abaqus_spec.Assembly.Nset{indNow}.ATTR.instance=abaqus_spec.Assembly.Instance.ATTR.name;\n abaqus_spec.Assembly.Nset{indNow}.VAL=segmentCurve_cell{q};\nend\n\n%Add ring curve node sets\nfor q=1:1:numel(ringCurve_cell)\n indNow=numel(abaqus_spec.Assembly.Nset)+1;\n abaqus_spec.Assembly.Nset{indNow}.ATTR.nset=['Ring',num2str(q)];\n abaqus_spec.Assembly.Nset{indNow}.ATTR.instance=abaqus_spec.Assembly.Instance.ATTR.name;\n abaqus_spec.Assembly.Nset{indNow}.VAL=ringCurve_cell{q};\nend\n\n%Add fix node set\n% indNow=numel(abaqus_spec.Assembly.Nset)+1;\n% setNameFix=['Set-',num2str(indNow)];\n% abaqus_spec.Assembly.Nset{indNow}.ATTR.nset=setNameFix;\n% abaqus_spec.Assembly.Nset{indNow}.ATTR.instance=abaqus_spec.Assembly.Instance.ATTR.name;\n% abaqus_spec.Assembly.Nset{indNow}.VAL=indNodesFix';\n\n%%--> Material\nfor q=1:1:numMaterials\n abaqus_spec.Material{q}.ATTR.name=['mat_',num2str(q)];\n abaqus_spec.Material{q}.Depvar.VAL=13;\n abaqus_spec.Material{q}.User_Material.ATTR.constants=17;\n %Define material parameters\n mu_now=mu_data;\n k_now=mu_now*kfactor;\n D_now=2/k_now;\n k1_now=k1_data;\n k2_now=k2_data;\n kappa_now=kappa_data;\n theta1_now=theta1_data;\n theta2_now=theta2_data;\n sigact_now=sigact_data;\n ke_now=ke_data;\n Ee_now=Ee_vector(q);\n thetaE1_now=thetaE1_data;\n thetaE2_now=thetaE2_data;\n iswitch_now=iswitch;\n xeps_now=xeps_vector(q);\n Vcol_now=Vcol_vector(q);\n Vela_now=Vela_vector(q);\n Vsmc_now=Vsmc_vector(q);\n t=vec2strIntDouble([mu_now/2 D_now k1_now k2_now kappa_now theta1_now theta2_now sigact_now ke_now Ee_now thetaE1_now thetaE2_now iswitch_now xeps_now Vcol_now Vela_now Vsmc_now],'%6.7e');\n t=strwrap(t,8,', '); %Wrap to max width of 8 entries\n %abaqus_spec.User_Material{q}.VAL=t;\n abaqus_spec.Material{q}.User_Material.VAL=t;\nend\n%%--> Step\nabaqus_spec.Step.ATTR.name='Step-1';\nabaqus_spec.Step.ATTR.nlgeom='YES';\nabaqus_spec.Step.Static=[0.01 1 1e-6 0.01];\n\n% Boundary\n% setNameFix=abaqus_spec.Assembly.Nset{indNow}.ATTR.nset;\n% abaqus_spec.Step.Boundary{1}.VAL={setNameFix,[1,1]};\n% abaqus_spec.Step.Boundary{2}.VAL={setNameFix,[2,2]};\n% abaqus_spec.Step.Boundary{3}.VAL={setNameFix,[3,3]};\n\n%Output\n% abaqus_spec.Step.Restart.ATTR.write='';\n% abaqus_spec.Step.Restart.ATTR.frequency=0;\n%\n% abaqus_spec.Step.Output{1}.ATTR.field='';\n% abaqus_spec.Step.Output{1}.ATTR.variable='PRESELECT';\n% abaqus_spec.Step.Output{2}.ATTR.history='';\n% abaqus_spec.Step.Output{2}.ATTR.variable='PRESELECT';\n% abaqus_spec.Step.Node_print.ATTR.nset='all';\n% abaqus_spec.Step.Node_print.ATTR.frequency = 1;\n% abaqus_spec.Step.Node_print.VAL='COORD';\n% abaqus_spec.Step.El_print{1}.VAL='S';\n% abaqus_spec.Step.El_print{2}.VAL='E';\n\n% Creating the INP file\n% You can use |abaqusStruct2inp| to write the structure data to a file.\n\n%% \nif saveOn==1\n % Export INP file\n abaqusStruct2inp(abaqus_spec,abaqusInpFileName);\n\n saveStruct.ET=ET;\n saveStruct.FT=FT;\n saveStruct.VT=VT;\n saveStruct.Fb=Fb;\n saveStruct.segmentCurve_cell=segmentCurve_cell;\n saveStruct.abaqus_spec=abaqus_spec;\n save(matfileSaveName,'-struct','saveStruct');\n \n disp('inp file write complete')\nend\n\n%% FUNCTIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [Fs,Vs,Cs,indEnd,logicRemoveFaces,segmentCurve_cell,E_rings]=circleCutExtrude(F,V,C,V_cent,V_cut,pointSpacing,plotOn,smoothControlParameters,segmentCurve_cell,E_rings)\n\n%% Conver to triangles\nFt=[F(:,[1 2 3]);F(:,[3 4 1])];\n\n%% Resample center line\nnp=round(max(pathLength(V_cent))/pointSpacing);\nV_cent = evenlySampleCurve(V_cent,np,'spline',0);\n\n%% Get mean of cut curve, project to surface\n\nV_cut_mean=mean(V_cut,1);\n\nrMax=max(sqrt(sum((V_cut-V_cut_mean(ones(size(V_cut,1),1),:)).^2,2)));\n\n[~,indMin]=minDist(V_cut_mean,V_cent);\n\nv=V_cent(indMin,:)-V_cut_mean;\n\noptStruct.eps = 1e-6;\noptStruct.triangle = 'one sided';\noptStruct.ray = 'ray';\noptStruct.border = 'normal';\n\n[V_intersect,L_intersect,~] = triangleRayIntersection(V_cut_mean(ones(size(Ft,1),1),:),v(ones(size(Ft,1),1),:),V,Ft,optStruct);\n\nV_intersect=V_intersect(L_intersect,:);\n\nD=minDist(V,V_intersect);\n\nlogicRemoveVertices=D<=rMax;\n\nlogicRemoveFaces=any(logicRemoveVertices(F),2);\n\nEb_cut=patchBoundary(F(logicRemoveFaces,:),V);\nindCurveCut=edgeListToCurve(Eb_cut);\nindCurveCut=indCurveCut(1:end-1);\nindCurveCut=indCurveCut(:);\n\nlogicFlip=~any((Eb_cut(:,1)==indCurveCut(1))&(Eb_cut(:,2)==indCurveCut(2)));\nif logicFlip\n indCurveCut=flipud(indCurveCut);\nend\n\nV_curve_cut=V(indCurveCut,:);\n\n%Resample so they have the same amount of points\nnp=size(V_curve_cut,1);\nV_cut = evenlySampleCurve(V_cut,np,'spline',1);\n\n%Get appropriate start point\n[~,indMin]=minDist(V_cut(1,:),V_curve_cut);\nif indMin>1\n V_curve_cut=[V_curve_cut(indMin:end,:); V_curve_cut(1:indMin-1,:)];\nend\n\nV_curve_cut_mean=mean(V_curve_cut,1);\nV_cut_mean=mean(V_cut,1);\n\n% Check order again\nnq=round(0.25*np);\na1=dot(V_cut(nq,:)-V_cut_mean,V_curve_cut(nq,:)-V_curve_cut_mean);\n\nV_cut_test=flipud(V_cut);\na2=dot(V_cut_test(nq,:)-V_cut_mean,V_curve_cut(nq,:)-V_curve_cut_mean);\n\nif a2>a1\n V_cut=V_cut_test;\nend\n\n%Get appropriate start point\n[~,indMin]=minDist(V_cut(1,:),V_curve_cut);\nif indMin>1\n V_curve_cut=[V_curve_cut(indMin:end,:); V_curve_cut(1:indMin-1,:)];\nend\n\n%Minimize twist\nSSQD=zeros(np,1);\nfor q=1:1:np\n if q>1\n indSort=[q:np 1:q-1];\n else\n indSort=1:np;\n end\n V_curve_cut_test=V_curve_cut(indSort,:);\n SSQD(q)=sum(sqrt(sum((V_curve_cut_test-V_cut).^2,2)).^2);\nend\n\n%Get sort order\n[~,q]=min(SSQD);\nif q>1\n indSort=[q:np 1:q-1];\n V_curve_cut=V_curve_cut(indSort,:);\nend\n\n%%\n\nF=F(~logicRemoveFaces,:);\nC=C(~logicRemoveFaces);\n\n%% Loft\n\ncPar.closeLoopOpt=1;\ncPar.patchType='quad';\n\n[F_merge,V_merge,~,indEnd]=polyLoftLinear(V_curve_cut,V_cut,cPar);\nC_merge=max(C(:))+ones(size(F_merge,1),1);\n\n%%\n\n% if plotOn==1\n% cFigure(figStruct); hold on;\n% gpatch(F,V,C,'k',0.5);\n% gpatch(F_merge,V_merge,'g','k',1);\n% plotV(V_cent,'g.-','LineWidth',3,'markerSize',25);\n% plotV(V_cut,'r.-','LineWidth',3,'markerSize',25);\n% plotV(V_cut_mean,'r.','markerSize',50);\n% plotV(V_curve_cut,'b.-','LineWidth',3);\n% plotV(V_intersect,'b.','markerSize',50);\n% quiverVec(V_cut_mean,v,[],'r');\n% axisGeom;\n% colormap gjet;\n% camlight headlight;\n% drawnow;\n% end\n\n%%\n\n[Fs,Vs,Cs]=joinElementSets({F,F_merge},{V,V_merge},{C,C_merge});\nindEnd=indEnd+size(V,1);\n\n%% Constrained smoothing\n\nnGrowthSteps=2;\nlogicSmooth=any(ismember(Fs,indCurveCut),2);\nfor q=1:1:nGrowthSteps-1\n indTouch=unique(Fs(logicSmooth,:));\n logicSmooth=any(ismember(Fs,indTouch),2);\nend\n\nlogicSmooth=logicSmooth | Cs==max(Cs(:));\n\n[Fs,Vs,~,indFix]=mergeVertices(Fs,Vs); %Merging points\nindEnd=indFix(indEnd);\n\nfor q=1:1:numel(segmentCurve_cell)\n indSegment=segmentCurve_cell{q};\n indSegment=indSegment(indSegment>0);\n segmentCurve_cell{q}=indFix(indSegment);\nend\nE_rings=indFix(E_rings);\n\n[Fs,Vs,indFix]=patchCleanUnused(Fs,Vs); %removing unused at hole\nindEnd=indFix(indEnd);\nE_rings=indFix(E_rings);\nE_rings=E_rings(all(E_rings>0,2),:);\n\nfor q=1:1:numel(segmentCurve_cell)\n indSegment=segmentCurve_cell{q};\n indSegment=indSegment(indSegment>0);\n segmentCurve_cell{q}=indFix(indSegment);\nend\n\nindRigid=unique(Fs(~logicSmooth,:));\nindRigid=unique([indRigid(:);indEnd(:)]);\n\nEb=patchBoundary(Fs,Vs);\nsmoothControlParameters.RigidConstraints=unique([indRigid(:);Eb(:)]);\n[Vs]=patchSmooth(Fs,Vs,[],smoothControlParameters);\n\n%%\n\nif plotOn==1\n cFigure(figStruct); hold on;\n gpatch(Fs,Vs,logicSmooth,'k',1);\n patchNormPlot(Fs,Vs);\n plotV(Vs(indRigid,:),'b.','markerSize',25);\n axisGeom;\n colormap gjet;\n camlight headlight;\n drawnow;\nend\n\n\nend\n\n%%\nfunction V=resampleCurve(V,pointSpacing,closeLoopOpt)\n\nnp=ceil(max(pathLength(V))/pointSpacing);\nV = evenlySampleCurve(V,np,'spline',closeLoopOpt);\n\nend\n\n%%\n\nfunction [Vn]=curveOffset(V,wallThickness)\np1=mean(V,1); %Curve center\n\nvf=-vecnormalize(V-[V(2:end,:);V(1,:)]); %Allong curve path vectors\nvb=vecnormalize(V-[V(end,:);V(1:end-1,:)]); %Allong curve path vectors\nv=(vf+vb)/2;\n\nr=vecnormalize(V-p1); %Position vector wrt mean\nv1=vecnormalize(cross(v,r)); %perimeter quasi Z-vectors\nn=vecnormalize(cross(v1(ones(size(v,1),1),:),v)); %Outward normal vectors\nVn=(V+n*wallThickness); %Offset to create new curve\n\n% cFigure;\n% plotV(V,'k.-');\n% quiverVec(V,vf,3,'r');\n% quiverVec(V,vb,3,'b');\n% quiverVec(V,v,3,'g');\n% axisGeom\n% drawnow;\nend\n%% \n% _*GIBBON footer text*_ \n% \n% License: \n% \n% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for\n% image segmentation, image-based modeling, meshing, and finite element\n% analysis.\n% \n% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n", "meta": {"author": "gibbonCode", "repo": "GIBBON", "sha": "8178520664a6148db939eaea87e75b3cba4f2b4f", "save_path": "github-repos/MATLAB/gibbonCode-GIBBON", "path": "github-repos/MATLAB/gibbonCode-GIBBON/GIBBON-8178520664a6148db939eaea87e75b3cba4f2b4f/docs/DEMO_aorta_build_passive_01.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.3242354055108441, "lm_q1q2_score": 0.17097468679054245}} {"text": "function [ output_meta ] = meta2sicd_s1product( domnode, eof_domnode )\n%META2SICD_S1PRODUCT Converts Sentinel-1 annotation \"product\" XML file into SICD format\n%\n% Written by: Wade Schwartzkopf, NGA Research\n%\n% We do not populate the SICD Antenna field. An antenna pattern is given\n% in the metadata, but its not clear what you would use this for, so we\n% haven't bothered to convert to the SICD structure yet.\n%\n% //////////////////////////////////////////\n% /// CLASSIFICATION: UNCLASSIFIED ///\n% //////////////////////////////////////////\n\n%% Setup\nSECONDS_IN_A_DAY = 24*60*60;\nxp=javax.xml.xpath.XPathFactory.newInstance.newXPath();\n\n%% CollectionInfo\ncommon_meta.CollectionInfo.CollectorName = char(xp.evaluate(...\n 'product/adsHeader/missionId',domnode));\ncommon_meta.CollectionInfo.CollectType='MONOSTATIC';\ncommon_meta.CollectionInfo.RadarMode.ModeID = char(xp.evaluate(...\n 'product/adsHeader/mode',domnode));\nif common_meta.CollectionInfo.RadarMode.ModeID(1)=='S'\n common_meta.CollectionInfo.RadarMode.ModeType='STRIPMAP';\nelse\n % Actually TOPSAR. Not what we normally think of for DYNAMIC STRIPMAP,\n % but it is definitely not SPOTLIGHT (actually counter to the spotlight\n % beam motion), and it isn't STRIPMAP with a constant angle between the\n % beam and direction of travel either, so we use DYNAMIC STRIPMAP as a\n % catchall.\n common_meta.CollectionInfo.RadarMode.ModeType='DYNAMIC STRIPMAP';\nend\ncommon_meta.CollectionInfo.Classification='UNCLASSIFIED';\n\n%% ImageData\n% For SLC, the following test should always hold true:\nif strcmpi(xp.evaluate('product/imageAnnotation/imageInformation/pixelValue',domnode),'Complex') && ...\n strcmpi(xp.evaluate('product/imageAnnotation/imageInformation/outputPixels',domnode),'16 bit Signed Integer')\n common_meta.ImageData.PixelType = 'RE16I_IM16I';\nelse\n warning('META2SICD_S1PRODUCT:UNRECOGNIZED_SLC','SLC data should be 16-bit complex.');\nend\nnum_bursts = str2double(xp.evaluate(...\n 'count(product/swathTiming/burstList/burst)',domnode));\n% These two definitions of NumRows should always be the same for\n% non-STRIPMAP data (For STRIPMAP, samplesPerBurst is set to zero.) Number\n% of rows in burst should be the same as the full image. Both of these\n% numbers also should match the ImageWidth field of the measurement TIFF.\nif num_bursts>0\n common_meta.ImageData.NumRows = uint32(str2double(char(xp.evaluate(...\n 'product/swathTiming/samplesPerBurst',domnode))));\nelse % STRIPMAP\n common_meta.ImageData.NumRows = uint32(str2double(xp.evaluate(...\n 'product/imageAnnotation/imageInformation/numberOfSamples',domnode)));\nend\n% These NumCols definition will be different. Since each burst is its own\n% coherent data period, and thus SICD, we set the SICD metadata to describe\n% each individual burst.\nif num_bursts>0\n % Ths in the number of coumns in a single burst.\n common_meta.ImageData.NumCols = uint32(str2double(char(xp.evaluate(...\n 'product/swathTiming/linesPerBurst',domnode))));\nelse % STRIPMAP\n % This in the number of columns in the full TIFF measurement file, even\n % if it contains multiple bursts.\n common_meta.ImageData.NumCols = uint32(str2double(xp.evaluate(...\n 'product/imageAnnotation/imageInformation/numberOfLines',domnode)));\nend\n\ncommon_meta.ImageData.FirstRow = uint32(0);\ncommon_meta.ImageData.FirstCol = uint32(0);\ncommon_meta.ImageData.FullImage.NumRows = common_meta.ImageData.NumRows;\ncommon_meta.ImageData.FullImage.NumCols = common_meta.ImageData.NumCols;\n% SCP pixel within entire TIFF\ncenter_cols = round((-0.5 + (1:max(num_bursts,1))) * double(common_meta.ImageData.NumCols)) - 1;\ncenter_rows = repmat(round(double(common_meta.ImageData.NumRows)/2 - 1),size(center_cols));\n% SCP pixel within single burst image is the same for all burst, since east\n% burst is the same size\ncommon_meta.ImageData.SCPPixel.Col = center_cols(1);\ncommon_meta.ImageData.SCPPixel.Row = center_rows(1);\n\n%% GeoData\ncommon_meta.GeoData.EarthModel = 'WGS_84';\n% Initially, we just seed this with a rough value. Later we will put\n% in something more precise.\nnum_grid_points=str2double(xp.evaluate(...\n 'count(product/geolocationGrid/geolocationGridPointList/geolocationGridPoint)',domnode));\n[scp_col, scp_row, x, y, z] = deal(zeros(num_grid_points,1));\nfor j = 1:num_grid_points\n scp_col(j) = str2double(xp.evaluate(...\n ['product/geolocationGrid/geolocationGridPointList/geolocationGridPoint[' num2str(j) ']/line'],...\n domnode));\n scp_row(j) = str2double(xp.evaluate(...\n ['product/geolocationGrid/geolocationGridPointList/geolocationGridPoint[' num2str(j) ']/pixel'],...\n domnode));\n lat = str2double(xp.evaluate(...\n ['product/geolocationGrid/geolocationGridPointList/geolocationGridPoint[' num2str(j) ']/latitude'],...\n domnode));\n lon = str2double(xp.evaluate(...\n ['product/geolocationGrid/geolocationGridPointList/geolocationGridPoint[' num2str(j) ']/longitude'],...\n domnode));\n hgt = str2double(xp.evaluate(...\n ['product/geolocationGrid/geolocationGridPointList/geolocationGridPoint[' num2str(j) ']/height'],...\n domnode));\n % Can't interpolate across international date line -180/180 longitude,\n % so move to ECF space from griddata interpolation\n [x(j), y(j), z(j)] = geodetic_to_ecf(lat, lon, hgt);\nend\nscp_x = griddata(scp_col, scp_row, x, center_cols, center_rows);\nscp_y = griddata(scp_col, scp_row, y, center_cols, center_rows);\nscp_z = griddata(scp_col, scp_row, z, center_cols, center_rows);\n\n%% Grid\ncommon_meta.Grid.ImagePlane = upper(strtok(char(xp.evaluate(...\n 'product/generalAnnotation/productInformation/projection',domnode))));\ncommon_meta.Grid.Type = 'RGZERO';\ndelta_tau_s = 1/str2double(char(xp.evaluate(...\n 'product/generalAnnotation/productInformation/rangeSamplingRate',domnode)));\ncommon_meta.Grid.Row.SS = (SPEED_OF_LIGHT/2) * delta_tau_s;\n% common_meta.Grid.Row.SS = str2double(xp.evaluate(... % Another way to do it\n% 'product/imageAnnotation/imageInformation/rangePixelSpacing',domnode));\ncommon_meta.Grid.Row.Sgn = -1;\n% Justification for Sgn:\n% 1) \"Sentinel-1 Level 1 Detailed Algorithm Definition\" shows last step in\n% image formation as IFFT, which would mean a forward FFT (-1 Sgn) would be\n% required to transform back.\n% 2) The forward FFT of a sliding window shows the Doppler centroid\n% increasing as you move right in the image, which must be the case for the\n% TOPSAR collection mode which starts in a rear squint and transitions to a\n% forward squint (and are always right looking).\nfc = str2double(char(xp.evaluate(...\n 'product/generalAnnotation/productInformation/radarFrequency',domnode)));\ncommon_meta.Grid.Row.KCtr = 2*fc/SPEED_OF_LIGHT;\ncommon_meta.Grid.Row.DeltaKCOAPoly=0;\nspp_str = 'product/imageAnnotation/processingInformation/swathProcParamsList/swathProcParams/';\ncommon_meta.Grid.Row.ImpRespBW=2*str2double(xp.evaluate([spp_str 'rangeProcessing/processingBandwidth'],domnode))/SPEED_OF_LIGHT;\ncommon_meta.Grid.Row.WgtType.WindowName=upper(char(xp.evaluate(...\n [spp_str 'rangeProcessing/windowType'],domnode)));\nif strcmpi(common_meta.Grid.Row.WgtType.WindowName,'NONE')\n common_meta.Grid.Row.WgtType.WindowName = 'UNIFORM';\nelseif strcmpi(common_meta.Grid.Row.WgtType.WindowName,'HAMMING') % The usual Sentinel weighting\n common_meta.Grid.Row.WgtType.Parameter.name = 'COEFFICIENT';\n common_meta.Grid.Row.WgtType.Parameter.value = char(xp.evaluate(...\n [spp_str 'rangeProcessing/windowCoefficient'],domnode));\n a = str2double(common_meta.Grid.Row.WgtType.Parameter.value); % Generalized Hamming window parameter\n common_meta.Grid.Row.WgtFunct = raised_cos_fun(512,a);\n % Computation of broadening factor for uniform window is:\n % 2 * fzero(@(x) (sin(pi*x)/(pi*x)) - (1/sqrt(2)), .1)\n row_broadening_factor = 2*fzero(@(x) ...\n a*(sin(pi*x)/(pi*x)) + ((1-a)*(sin(pi*(x-1))/(pi*(x-1)))/2) + ...\n ((1-a)*(sin(pi*(x+1))/(pi*(x+1)))/2) - a/sqrt(2), .1);\n common_meta.Grid.Row.ImpRespWid = row_broadening_factor/common_meta.Grid.Row.ImpRespBW;\nend\ncommon_meta.Grid.Col.SS = str2double(xp.evaluate(...\n 'product/imageAnnotation/imageInformation/azimuthPixelSpacing',domnode));\ncommon_meta.Grid.Col.Sgn = -1; % Must be the same as Row.Sgn\ncommon_meta.Grid.Col.KCtr = 0;\ndop_bw=str2double(xp.evaluate([spp_str 'azimuthProcessing/processingBandwidth'],domnode)); % Doppler bandwidth\nss_zd_s=str2double(xp.evaluate(... % Image column spacing in zero doppler time (seconds)\n 'product/imageAnnotation/imageInformation/azimuthTimeInterval',...\n domnode)); % Sentinel-1 is always right-looking, so should always be positive\ncommon_meta.Grid.Col.ImpRespBW=dop_bw*ss_zd_s/common_meta.Grid.Col.SS; % Convert to azimuth spatial bandwidth (cycles per meter)\ncommon_meta.Grid.Col.WgtType.WindowName=upper(char(xp.evaluate(...\n [spp_str 'azimuthProcessing/windowType'],domnode)));\nif strcmpi(common_meta.Grid.Col.WgtType.WindowName,'NONE')\n common_meta.Grid.Col.WgtType.WindowName = 'UNIFORM';\nelseif strcmpi(common_meta.Grid.Col.WgtType.WindowName,'HAMMING') % The usual Sentinel weighting\n common_meta.Grid.Col.WgtType.Parameter.name = 'COEFFICIENT';\n common_meta.Grid.Col.WgtType.Parameter.value = char(xp.evaluate(...\n [spp_str 'azimuthProcessing/windowCoefficient'],domnode));\n a = str2double(common_meta.Grid.Col.WgtType.Parameter.value); % Generalized Hamming window parameter\n common_meta.Grid.Col.WgtFunct = raised_cos_fun(512,a);\n col_broadening_factor = 2*fzero(@(x) ...\n a*(sin(pi*x)/(pi*x)) + ((1-a)*(sin(pi*(x-1))/(pi*(x-1)))/2) + ...\n ((1-a)*(sin(pi*(x+1))/(pi*(x+1)))/2) - a/sqrt(2), .1);\n common_meta.Grid.Col.ImpRespWid = col_broadening_factor/common_meta.Grid.Col.ImpRespBW;\nend\n% We will compute Grid.Col.DeltaKCOAPoly separately per-burst later.\n% The following Grid fields will be computed later in derived_sicd_fields\n% Grid.Row/Col.WgtFunct\n% Grid.Row/Col.ImpRespWid\n% Grid.Row/Col.DeltaK1\n% Grid.Row/Col.DeltaK2\n\n%% Timeline\nprf=str2double(xp.evaluate(...\n 'product/generalAnnotation/downlinkInformationList/downlinkInformation/prf',domnode));\n% Because of calibration pulses, it is unlikely this PRF was maintained\n% through this entire period, but we don't currently include that detail.\ncommon_meta.Timeline.IPP.Set.IPPPoly=[0; prf];\n[azimuth_time_first_line, azimuth_time_frac] = datenum_w_frac(char(xp.evaluate(...\n 'product/imageAnnotation/imageInformation/productFirstLineUtcTime',...\n domnode))); % Always the left-most SICD column (of first bursts or entire STRIPMAP dataset), since Sentinel-1 is always right-looking\neta_mid = ss_zd_s * double(common_meta.ImageData.SCPPixel.Col); % Offset in zero Doppler time from first column to SCP column\n\n%% Position\n% Compute state vectors\nnum_state_vectors=str2double(xp.evaluate(...\n 'count(product/generalAnnotation/orbitList/orbit)',domnode));\nstate_vector_T = zeros(num_state_vectors,1);\nstate_vector_T_frac = zeros(num_state_vectors,1);\nstate_vector_pos = zeros(num_state_vectors,3);\nstate_vector_vel = zeros(num_state_vectors,3);\nfor i=1:num_state_vectors\n timeStamp = char(xp.evaluate(...\n ['product/generalAnnotation/orbitList/orbit[' num2str(i) ']/time'],...\n domnode));\n [state_vector_T(i), state_vector_T_frac(i)] = datenum_w_frac(timeStamp);\n\n state_vector_pos(i,1) = str2double(xp.evaluate(...\n ['product/generalAnnotation/orbitList/orbit[' num2str(i) ']/position/x'],...\n domnode));\n state_vector_pos(i,2) = str2double(xp.evaluate(...\n ['product/generalAnnotation/orbitList/orbit[' num2str(i) ']/position/y'],...\n domnode));\n state_vector_pos(i,3) = str2double(xp.evaluate(...\n ['product/generalAnnotation/orbitList/orbit[' num2str(i) ']/position/z'],...\n domnode));\n state_vector_vel(i,1) = str2double(xp.evaluate(...\n ['product/generalAnnotation/orbitList/orbit[' num2str(i) ']/velocity/x'],...\n domnode));\n state_vector_vel(i,2) = str2double(xp.evaluate(...\n ['product/generalAnnotation/orbitList/orbit[' num2str(i) ']/velocity/y'],...\n domnode));\n state_vector_vel(i,3) = str2double(xp.evaluate(...\n ['product/generalAnnotation/orbitList/orbit[' num2str(i) ']/velocity/z'],...\n domnode));\nend\n% If external orbit file was passed in, use it instead of orbit state files\n% in SLC annotation file\ncommon_meta.CollectionInfo.Parameter{4}.name = 'ORBIT_SOURCE';\nif exist('eof_domnode','var')\n % Use same time range as was used in SLC annotation file plus some\n % buffer to assure enough state vectors are selected, since we are\n % fitting to 5th order polynomial. EOF files have state vectors every\n % 10 seconds.\n buffer = max(5, (70-(max(state_vector_T)-min(state_vector_T))*SECONDS_IN_A_DAY)/2);\n timerange = [min(state_vector_T - (buffer/SECONDS_IN_A_DAY)) ...\n max(state_vector_T + (buffer/SECONDS_IN_A_DAY))];\n [state_vector_T, state_vector_T_frac, state_vector_pos, state_vector_vel] = ...\n get_osv_from_eof(eof_domnode, timerange);\n \n common_meta.CollectionInfo.Parameter{4}.value = char(xp.evaluate(... % Orbit file type\n 'Earth_Explorer_File/Earth_Explorer_Header/Fixed_Header/File_Type',eof_domnode));\nelse\n common_meta.CollectionInfo.Parameter{4}.value = 'SLC_INTERNAL';\nend\n\n%% RadarCollection\npol = char(xp.evaluate('product/adsHeader/polarisation',domnode));\ncommon_meta.RadarCollection.TxPolarization = pol(1);\ncommon_meta.RadarCollection.TxFrequency.Min = fc + str2double(xp.evaluate(...\n 'product/generalAnnotation/downlinkInformationList/downlinkInformation/downlinkValues/txPulseStartFrequency',domnode));\ncommon_meta.RadarCollection.Waveform.WFParameters.TxFreqStart = ...\n common_meta.RadarCollection.TxFrequency.Min;\ncommon_meta.RadarCollection.Waveform.WFParameters.TxPulseLength=str2double(xp.evaluate(...\n 'product/generalAnnotation/downlinkInformationList/downlinkInformation/downlinkValues/txPulseLength',domnode));\ncommon_meta.RadarCollection.Waveform.WFParameters.TxFMRate=str2double(xp.evaluate(...\n 'product/generalAnnotation/downlinkInformationList/downlinkInformation/downlinkValues/txPulseRampRate',domnode));\nbw = common_meta.RadarCollection.Waveform.WFParameters.TxPulseLength*...\n common_meta.RadarCollection.Waveform.WFParameters.TxFMRate;\ncommon_meta.RadarCollection.TxFrequency.Max = common_meta.RadarCollection.TxFrequency.Min + bw;\ncommon_meta.RadarCollection.Waveform.WFParameters.TxRFBandwidth=bw;\ncommon_meta.RadarCollection.Waveform.WFParameters.RcvDemodType='CHIRP';\ncommon_meta.RadarCollection.Waveform.WFParameters.RcvFMRate=0; % True for RcvDemodType='CHIRP'\ncommon_meta.RadarCollection.Waveform.WFParameters.ADCSampleRate=str2double(char(xp.evaluate(...\n 'product/generalAnnotation/productInformation/rangeSamplingRate',domnode))); % Raw not decimated\n% After decimation would be:\n% output_meta.RadarCollection.Waveform.WFParameters.ADCSampleRate=str2double(xp.evaluate(...\n% 'product/generalAnnotation/downlinkInformationList/downlinkInformation/downlinkValues/rangeDecimation/samplingFrequencyAfterDecimation',domnode));\nnum_swl = str2double(xp.evaluate(...\n 'count(product/generalAnnotation/downlinkInformationList/downlinkInformation/downlinkValues/swlList/swl)',domnode));\nfor i = 1:num_swl % We could have multiple receive window lengths across the collect\n common_meta.RadarCollection.Waveform.WFParameters(i) = common_meta.RadarCollection.Waveform.WFParameters(1);\n common_meta.RadarCollection.Waveform.WFParameters(i).RcvWindowLength=str2double(xp.evaluate(...\n ['product/generalAnnotation/downlinkInformationList/downlinkInformation/downlinkValues/swlList/swl[' num2str(i) ']/value'],domnode));\nend\n\n%% ImageFormation\ncommon_meta.ImageFormation.RcvChanProc=struct('NumChanProc',1,'PRFScaleFactor',1);\ncommon_meta.ImageFormation.TxRcvPolarizationProc=[pol(1) ':' pol(2)];\n% RcvChanProc.ChanIndex must be populated external to this since it depends\n% on how the polarization were ordered in manifest file.\n% Assume image formation uses all data\ncommon_meta.ImageFormation.TStartProc=0;\ncommon_meta.ImageFormation.TxFrequencyProc.MinProc=...\n common_meta.RadarCollection.TxFrequency.Min;\ncommon_meta.ImageFormation.TxFrequencyProc.MaxProc=...\n common_meta.RadarCollection.TxFrequency.Max;\ncommon_meta.ImageFormation.ImageFormAlgo='RMA';\n% From the Sentinel-1 Level 1 Detailed Algorithm Definition document\nif common_meta.CollectionInfo.RadarMode.ModeID(1)=='S'\n common_meta.ImageFormation.STBeamComp='GLOBAL'; %STRIPMAP\nelse\n common_meta.ImageFormation.STBeamComp='SV'; %TOPSAR\nend\ncommon_meta.ImageFormation.ImageBeamComp='SV';\ncommon_meta.ImageFormation.AzAutofocus='NO';\ncommon_meta.ImageFormation.RgAutofocus='NO';\n\n%% RMA\n% \"Sentinel-1 Level 1 Detailed Algorithm Definition\" document seems to most\n% closely match the RangeDoppler algorithm (with accurate secondary range\n% compression or \"option 2\" as described in the Cumming and Wong book).\ncommon_meta.RMA.RMAlgoType = 'RG_DOP';\ncommon_meta.RMA.ImageType = 'INCA';\ntau_0 = str2double(char(xp.evaluate(... % tau_0 is notation from ESA deramping paper\n 'product/imageAnnotation/imageInformation/slantRangeTime',domnode)));\ncommon_meta.RMA.INCA.R_CA_SCP = (SPEED_OF_LIGHT/2) * (tau_0 + ...\n (double(common_meta.ImageData.SCPPixel.Row) * delta_tau_s));\ncommon_meta.RMA.INCA.FreqZero = fc;\n% If we use the Doppler Centroid as defined directly in the manifest.safe\n% metadata, then the center of frequency support Col.DeltaKCOAPoly does not\n% correspond to RMA.INCA.DopCentroidPoly. However, we will compute\n% TimeCOAPoly later to match a newly computed Doppler Centroid based off of\n% DeltaKCOAPoly, assuming that the the COA is at the peak signal (fdop_COA\n% = fdop_DC).\ncommon_meta.RMA.INCA.DopCentroidCOA = true;\n\n%% Doppler centroid\n% Get common (non-burst specific) parameters we will need for Doppler\n% centroid and rate computations later\nnum_dc_estimates_az=str2double(xp.evaluate(...\n 'count(product/dopplerCentroid/dcEstimateList/dcEstimate)',domnode));\nfor i = 1:num_dc_estimates_az\n [dc_az_time_s(i), dc_az_time_frac(i)] = datenum_w_frac(char(xp.evaluate(...\n ['product/dopplerCentroid/dcEstimateList/dcEstimate[' num2str(i) ']/azimuthTime'],...\n domnode)));\n % How to interpret the various representations of Doppler Centroid in\n % the Sentinel 1 XML:\n % This implementation allows for estimates at different azimuth times\n % to have different numbers of fineDce values, but I don't know if that\n % ever actually happens.\n % num_dc_estimates_rg=str2double(xp.evaluate(...\n % ['count(product/dopplerCentroid/dcEstimateList/dcEstimate[' num2str(i) ']/fineDceList/fineDce)'],domnode));\n % [tSR, freq] = deal(zeros(num_dc_estimates_rg,1));\n % for j = 1:num_dc_estimates_rg\n % tSR(j) = str2double(xp.evaluate(... % Two-way slant range (s)\n % ['product/dopplerCentroid/dcEstimateList/dcEstimate[' num2str(i) ']/fineDceList/fineDce[' num2str(j) ']/slantRangeTime'],...\n % domnode));\n % freq(j) = str2double(xp.evaluate(... % Doppler estimate\n % ['product/dopplerCentroid/dcEstimateList/dcEstimate[' num2str(i) ']/fineDceList/fineDce[' num2str(j) ']/frequency'],...\n % domnode));\n % end\n dc_t0(i) = str2double(xp.evaluate(...\n ['product/dopplerCentroid/dcEstimateList/dcEstimate[' num2str(i) ']/t0'],...\n domnode));\n % % data_dc_poly should be equal to:\n % % polyfit(tSR-dc_t0, freq, 2)\n data_dc_poly{i} = str2num(xp.evaluate(...\n ['product/dopplerCentroid/dcEstimateList/dcEstimate[' num2str(i) ']/dataDcPolynomial'],...\n domnode));\n % % rms_dc_poly should be equal to:\n % % rms(freq - polyval(polyfit(tSR-dc_t0, freq, 2), tSR-dc_t0))\n % rms_dc_poly = str2num(xp.evaluate(...\n % ['product/dopplerCentroid/dcEstimateList/dcEstimate[' num2str(i) ']/dataDcRmsError'],...\n % domnode));\n % % An alternative method for computing the Doppler polynomial. Uses the\n % % Doppler centroid estimate from orbit geometry. Much smoother.\n % geom_dc_poly = str2num(xp.evaluate(...\n % ['product/dopplerCentroid/dcEstimateList/dcEstimate[' num2str(i) ']/geometryDcPolynomial'],...\n % domnode));\n % freq=polyval(geom_dc_poly(end:-1:1),tSR-dc_t0); % Samples at the same points as fineDceList\n \n % Of all these options, we will use dataDcPolynomial, since that's what\n % they use in the ESA document on TOPS SLC deramping. The data-derived\n % samples are not always particularly smooth, nor are they sampled very\n % densely, so its not clear how accurate this polynomial representation\n % is.\nend\nnum_azfm_rates=str2double(xp.evaluate(...\n 'count(product/generalAnnotation/azimuthFmRateList/azimuthFmRate)',...\n domnode));\nfor i = 1:num_azfm_rates\n [az_t_s(i), az_t_frac(i)] = datenum_w_frac(char(xp.evaluate(...\n ['product/generalAnnotation/azimuthFmRateList/azimuthFmRate[' ...\n num2str(i) ']/azimuthTime'],domnode)));\n az_t0(i) = str2double(xp.evaluate(...\n ['product/generalAnnotation/azimuthFmRateList/azimuthFmRate[' ...\n num2str(i) ']/t0'],domnode)).';\n % Two different ways we have seen in XML for storing the FM Rate polynomial\n if strcmpi('true',xp.evaluate(...\n ['boolean(product/generalAnnotation/azimuthFmRateList/azimuthFmRate[' ...\n num2str(i) ']/azimuthFmRatePolynomial)'],domnode))\n k_a_poly{i} = str2num(xp.evaluate(...\n ['product/generalAnnotation/azimuthFmRateList/azimuthFmRate[' ...\n num2str(i) ']/azimuthFmRatePolynomial'],domnode)).';\n else\n for j=1:3 % Assume hard coded to 3\n k_a_poly{i}(j)=str2double(xp.evaluate(... % Doppler FM rate with regard to raw time\n ['product/generalAnnotation/azimuthFmRateList/azimuthFmRate[' ...\n num2str(i) ']/c' num2str(j-1) ],...\n domnode));\n end\n end\nend\n\n% Azimuth steering rate (constant, not dependent on burst or range)\nk_psi = str2double(char(xp.evaluate(...\n 'product/generalAnnotation/productInformation/azimuthSteeringRate',domnode)));\nk_psi = k_psi*pi/180; % Convert from degrees/sec into radians/sec\n\n\n%% Compute per/burst metadata\noutput_meta = cell(num_bursts,1);\nfor i = 1:max(num_bursts,1)\n output_meta{i} = common_meta;\n \n %% CollectionInfo\n % These values are needed to generate CoreName later, but we will be\n % have to wait until after Timeline to fully generate that string,\n % since we include date in it.\n if strcmpi('true',xp.evaluate('boolean(product/imageAnnotation/imageInformation/sliceNumber)',domnode))\n slice = str2double(xp.evaluate(...\n 'product/imageAnnotation/imageInformation/sliceNumber',domnode));\n else\n slice = 0;\n end\n swath = char(xp.evaluate('product/adsHeader/swath',domnode));\n % Sensor specific portions of metadata\n output_meta{i}.CollectionInfo.Parameter{1}.name = 'SLICE';\n output_meta{i}.CollectionInfo.Parameter{1}.value = num2str(slice);\n output_meta{i}.CollectionInfo.Parameter{2}.name = 'SWATH';\n output_meta{i}.CollectionInfo.Parameter{2}.value = swath;\n output_meta{i}.CollectionInfo.Parameter{3}.name = 'BURST';\n output_meta{i}.CollectionInfo.Parameter{3}.value = num2str(i);\n \n %% ImageData.ValidData\n % Get valid bounds of burst from metadata. Assume a rectangular valid\n % area-- not totally true, but all that seems to be defined by the\n % product XML metadata.\n if num_bursts>0 % Valid data does not seem to be defined for STRIPMAP data...\n firstSamples = str2num(char(xp.evaluate(...\n ['product/swathTiming/burstList/burst[' num2str(i) ']/firstValidSample'],domnode)));\n lastSamples = str2num(char(xp.evaluate(...\n ['product/swathTiming/burstList/burst[' num2str(i) ']/lastValidSample'],domnode)));\n valid_cols = (firstSamples>=0)&(lastSamples>=0);\n first_col = find(valid_cols,1,'first') - 1; % SICD zero-based vs MATLAB one-based\n last_col = find(valid_cols,1,'last') - 1; % SICD zero-based vs MATLAB one-based\n first_row = max(firstSamples(valid_cols)); % Sentinel XML and SICD both zero-based, no -1 needed\n last_row = min(lastSamples(valid_cols)); % Sentinel XML and SICD both zero-based\n % From SICD spec: Vertices ordered clockwise with vertex 1\n % determined by: (1) minimum row index, (2) minimum column index if\n % 2 vertices exist with minimum row index.\n output_meta{i}.ImageData.ValidData.Vertex(1).Row = first_row;\n output_meta{i}.ImageData.ValidData.Vertex(1).Col = first_col;\n output_meta{i}.ImageData.ValidData.Vertex(2).Row = first_row;\n output_meta{i}.ImageData.ValidData.Vertex(2).Col = last_col;\n output_meta{i}.ImageData.ValidData.Vertex(3).Row = last_row;\n output_meta{i}.ImageData.ValidData.Vertex(3).Col = last_col;\n output_meta{i}.ImageData.ValidData.Vertex(4).Row = last_row;\n output_meta{i}.ImageData.ValidData.Vertex(4).Col = first_col;\n end\n \n %% Timeline\n if num_bursts>0\n % This is the first and last zero doppler times of the columns in\n % the burst. This isn't really what we mean by CollectStart and\n % CollectDuration in SICD (really we want first and last pulse\n % times), but its all we have.\n [start_s, start_frac] = datenum_w_frac(char(xp.evaluate(...\n ['product/swathTiming/burstList/burst[' num2str(i) ']/azimuthTime'],domnode)));\n first_line_relative_start = 0; % CollectStart is zero Doppler time of first column\n else % STRIPMAP\n [start_s, start_frac] = datenum_w_frac(char(xp.evaluate(...\n 'product/generalAnnotation/downlinkInformationList/downlinkInformation/firstLineSensingTime',domnode)));\n % Maybe CollectStart/CollectDuration should be set by\n % product/imageAnnotation/imageInformation/productFirstLineUtcTime\n % and productLastLineUtcTime. This would make it consistent with\n % non-stripmap which just defines first and last zero doppler\n % times, but is not really consistent with what SICD generally\n % means by CollectStart/CollectDuration.\n [stop_s, stop_frac] = datenum_w_frac(char(xp.evaluate(...\n 'product/generalAnnotation/downlinkInformationList/downlinkInformation/lastLineSensingTime',domnode)));\n output_meta{i}.Timeline.CollectStart = start_s + (start_frac/SECONDS_IN_A_DAY);\n output_meta{i}.Timeline.CollectDuration = ...\n round((stop_s - start_s)*SECONDS_IN_A_DAY) + (stop_frac-start_frac);\n first_line_relative_start = ... % Convert from UTC to relative to start\n round((azimuth_time_first_line-start_s)*SECONDS_IN_A_DAY) + ... % Convert to seconds\n (azimuth_time_frac-start_frac); % Handle fractional seconds\n end\n\n % After we have start_s, we can generate CoreName\n output_meta{i}.CollectionInfo.CoreName = [...\n ... % Prefix with the NGA CoreName standard format\n upper(datestr(start_s,'ddmmmyy')) ...\n common_meta.CollectionInfo.CollectorName ...\n ... % The following core name is unique within all Sentinel-1\n ...% coherent data periods:\n num2str(str2double(xp.evaluate(...\n 'product/adsHeader/missionDataTakeId',domnode)),'%07u') '_' ... % Is 7 digits enough for the life of the mission?\n num2str(slice, '%02u') '_' ... % Slice\n swath '_' ... % Swath\n num2str(i, '%02u')]; % Burst\n \n %% Position\n % Polynomial is computed with respect to time from start of burst\n state_vector_T_burst = round((state_vector_T-start_s)*SECONDS_IN_A_DAY) + ... % Convert from days to secs\n (state_vector_T_frac-start_frac); % Handle fractional seconds\n % sv2poly.m shows ways to determine best polynomial order, but 5th is almost always best\n polyorder = min(5, numel(state_vector_T_burst) - 1);\n P_x = polyfit(state_vector_T_burst, state_vector_pos(:,1), polyorder);\n P_y = polyfit(state_vector_T_burst, state_vector_pos(:,2), polyorder);\n P_z = polyfit(state_vector_T_burst, state_vector_pos(:,3), polyorder);\n output_meta{i}.Position.ARPPoly.X = P_x(end:-1:1).';\n output_meta{i}.Position.ARPPoly.Y = P_y(end:-1:1).';\n output_meta{i}.Position.ARPPoly.Z = P_z(end:-1:1).';\n\n %% RMA\n % Sentinel-1 is always right-looking, so TimeCAPoly should never have\n % to be \"flipped\" for left-looking cases.\n output_meta{i}.RMA.INCA.TimeCAPoly = first_line_relative_start + eta_mid; % SCP zero Doppler time relative to start\n output_meta{i}.RMA.INCA.TimeCAPoly(2,1) = ss_zd_s/common_meta.Grid.Col.SS; % Convert zero doppler spacing from sec/pixels to sec/meters\n\n %% Doppler centroid\n % We choose the single Doppler centroid polynomial closest to the\n % center of the current burst.\n dc_est_times = round((dc_az_time_s-start_s) * SECONDS_IN_A_DAY) + ... % Convert from days to secs\n (dc_az_time_frac-start_frac); % Handle fractional seconds\n [~,dc_poly_ind] = min(abs(dc_est_times - output_meta{i}.RMA.INCA.TimeCAPoly(1)));\n % Shift polynomial from origin at dc_t0 (reference time for Sentinel\n % polynomial) to SCP time (reference time for SICD polynomial)\n range_time_scp = common_meta.RMA.INCA.R_CA_SCP*2/SPEED_OF_LIGHT;\n % The Doppler centroid field in the Sentinel-1 metadata is not\n % complete, so we cannot use it directly. That description of Doppler\n % centroid by itself does not vary by azimuth although the\n % Col.DeltaKCOAPoly we see in the data definitely does. We will define\n % DopCentroidPoly differently later down in the code. We also comment\n % out any definition of TimeCOAPoly based off of this DopCentroidPoly\n % definition, since it is wrong without some further adjustment.\n % dop_rate_poly_rg_shifted = polyshift(data_dc_poly{dc_poly_ind}(:), ...\n % range_time_scp - dc_t0(dc_poly_ind));\n % % Scale 1D polynomial to from Hz/s^n to Hz/m^n\n % output_meta{i}.RMA.INCA.DopCentroidPoly = dop_rate_poly_rg_shifted.*...\n % (2/SPEED_OF_LIGHT).^(0:(length(dop_rate_poly_rg_shifted)-1)).';\n\n %% Doppler rate\n % Total Doppler rate is a combination of the Doppler FM rate and the\n % Doppler rate introduced by the scanning of the antenna.\n % We pick a single velocity magnitude at closest approach to represent\n % the entire burst. This is valid, since the magnitude of the velocity\n % changes very little.\n pos_coefs = [P_x(:) P_y(:) P_z(:)];\n % Velocity is derivate of position.\n vel_coefs=pos_coefs(1:end-1,:).*repmat(((size(pos_coefs,1)-1):-1:1)',[1 3]);\n vel_x = polyval(vel_coefs(:,1), output_meta{i}.RMA.INCA.TimeCAPoly(1));\n vel_y = polyval(vel_coefs(:,2), output_meta{i}.RMA.INCA.TimeCAPoly(1));\n vel_z = polyval(vel_coefs(:,3), output_meta{i}.RMA.INCA.TimeCAPoly(1));\n vm_ca = sqrt(vel_x.^2 + vel_y.^2 + vel_z.^2); % Magnitude of the velocity at SCP closest approach\n % Compute FM Doppler Rate, k_a\n % We choose the single azimuth FM rate polynomial closest to the\n % center of the current burst.\n az_rate_times = round((az_t_s-start_s) * SECONDS_IN_A_DAY) + ... % Convert from days to secs\n (az_t_frac-start_frac); % Handle fractional seconds\n [~,az_rate_poly_ind] = min(abs(az_rate_times - output_meta{i}.RMA.INCA.TimeCAPoly(1)));\n % SICD's Doppler rate seems to be FM Doppler rate, not total Doppler rate\n % Shift polynomial from origin at az_t0 (reference time for Sentinel\n % polynomial) to SCP time (reference time for SICD polynomial)\n DR_CA = polyshift(k_a_poly{az_rate_poly_ind}(:), ...\n range_time_scp - az_t0(az_rate_poly_ind));\n % Scale 1D polynomial to from Hz/s^n to Hz/m^n\n DR_CA = DR_CA.*(2/SPEED_OF_LIGHT).^(0:(numel(DR_CA)-1)).';\n % Polynomial representing range as a function of range distance from SCP\n r_ca = [output_meta{i}.RMA.INCA.R_CA_SCP; 1];\n % RMA.INCA.DRateSFPoly is a function of Doppler rate.\n output_meta{i}.RMA.INCA.DRateSFPoly = - conv(DR_CA, r_ca) * ...\n SPEED_OF_LIGHT / (2 * fc * (vm_ca^2)); % Assumes a SGN of -1\n \n %% TimeCOAPoly\n % TimeCOAPoly = TimeCA + (DopCentroid/dop_rate); % True if DopCentroidCOA = true\n % Since we don't know how to evaluate this equation analytically, we\n % could evaluate samples of it across our image and fit a 2D polynomial\n % to it later.\n POLY_ORDER = 2; % Same order of native metadata polynomials to describe Doppler Centroid, azimuth fm rate, etc.\n grid_samples = POLY_ORDER + 1; % in each dimension\n % For debugging, this lets us compute phase for every pixel:\n % cols = linspace(1, double(output_meta{i}.ImageData.NumCols), output_meta{i}.ImageData.NumCols);\n % rows = linspace(1, double(output_meta{i}.ImageData.NumRows), output_meta{i}.ImageData.NumRows);\n cols = round(linspace(1, double(output_meta{i}.ImageData.NumCols), grid_samples));\n rows = round(linspace(1, double(output_meta{i}.ImageData.NumRows), grid_samples));\n coords_az_m = double(cols - (output_meta{i}.ImageData.SCPPixel.Col+1)) * ...\n output_meta{i}.Grid.Col.SS;\n coords_rg_m = double(rows - (output_meta{i}.ImageData.SCPPixel.Row+1)) * ...\n output_meta{i}.Grid.Row.SS;\n timeca_sampled = sicd_polyval2d(output_meta{i}.RMA.INCA.TimeCAPoly(:).',coords_az_m,coords_rg_m);\n % dopcentroid_sampled = sicd_polyval2d(output_meta{i}.RMA.INCA.DopCentroidPoly,coords_az_m,coords_rg_m);\n doprate_sampled = sicd_polyval2d(DR_CA,coords_az_m,coords_rg_m);\n % timecoa_sampled = timeca_sampled + (dopcentroid_sampled./doprate_sampled);\n \n %% Grid.Col.DeltaKCOAPoly\n % Reference: Definition of the TOPS SLC deramping function for products\n % generated by the S-1 IPF, COPE-GSEG-EOPG-TN-14-0025\n tau = tau_0 + delta_tau_s * (0:double(common_meta.ImageData.NumRows-1)); % Range time for each sample\n % The vm_ca used here is slightly different than the ESA deramp\n % document, since the document interpolates the velocity values given\n % rather than the position values, which is what we do here.\n k_s = (2 * vm_ca / SPEED_OF_LIGHT) * fc * k_psi; % Doppler rate as introduced by antenna steering, k_s\n k_a = polyval(k_a_poly{az_rate_poly_ind}(end:-1:1), tau - az_t0(az_rate_poly_ind)); % Doppler FM rate\n k_t = (k_a * k_s)./(k_a - k_s); % Total Doppler Centroid Rate\n f_eta_c= polyval(data_dc_poly{dc_poly_ind}(end:-1:1), tau - dc_t0(dc_poly_ind)); % Doppler Centroid\n % This old implementation was imprecise. The limits were one more than\n % the spacing. Should have been a -1 in here somewhere. New\n % formulation is clearer (at least to me). -WCS\n % eta = linspace(-double(output_meta{i}.ImageData.NumCols)*ss_zd_s/2, ...\n % double(output_meta{i}.ImageData.NumCols)*ss_zd_s/2, ...\n % double(output_meta{i}.ImageData.NumCols));\n eta = (-double(output_meta{i}.ImageData.SCPPixel.Col) * ss_zd_s) + ...\n (0:double(output_meta{i}.ImageData.NumCols-1))*ss_zd_s;\n eta_c = - f_eta_c./k_a; % Beam center crossing time. TimeCOA in SICD terminology\n eta_ref = eta_c - eta_c(1);\n [eta_grid, eta_ref_grid] = ndgrid(eta(cols), eta_ref(rows));\n eta_arg = eta_grid - eta_ref_grid;\n k_t_grid = repmat(k_t(rows),numel(cols),1);\n f_eta_c_grid = repmat(f_eta_c(rows),numel(cols),1);\n deramp_phase = k_t_grid.*(eta_arg.^2)/2;\n demod_phase = f_eta_c_grid.*eta_arg;\n total_phase = deramp_phase + demod_phase; % Sampled phase correction for deramping and demodding\n\n %% Least squares fit for 2D polynomials\n % A*x = b\n [coords_az_m_2d, coords_rg_m_2d] = ndgrid(coords_az_m, coords_rg_m);\n a = zeros(numel(total_phase), (POLY_ORDER+1)^2);\n for k = 0:POLY_ORDER\n for j = 0:POLY_ORDER\n a(:,k*(POLY_ORDER+1)+j+1) = (coords_rg_m_2d(:).^j).*(coords_az_m_2d(:).^k);\n end\n end\n % b_coa = zeros((POLY_ORDER+1)^2,1);\n b_phase = zeros((POLY_ORDER+1)^2,1);\n for k=1:((POLY_ORDER+1)^2)\n % b_coa(k)=sum(timecoa_sampled(:).*a(:,k)); % center of aperture\n b_phase(k)=sum(total_phase(:).*a(:,k)); % phase to deramp in azimuth\n end\n A=zeros((POLY_ORDER+1)^2);\n for k=1:((POLY_ORDER+1)^2)\n for j=1:((POLY_ORDER+1)^2)\n A(k,j)=sum(a(:,k).*a(:,j));\n end\n end\n % MATLAB often flags these as badly scaled, but results still appear valid\n old_warning_state=warning('off','MATLAB:nearlySingularMatrix');\n % x_coa=A\\b_coa;\n x_phase=A\\b_phase;\n warning(old_warning_state);\n phase=reshape(x_phase, POLY_ORDER+1, POLY_ORDER+1);\n % output_meta{i}.Grid.TimeCOAPoly=reshape(x_coa, POLY_ORDER+1, POLY_ORDER+1);\n % DeltaKCOAPoly is derivative of phase in Col direction\n output_meta{i}.Grid.Col.DeltaKCOAPoly = phase(:,2:end) .* ...\n repmat((1:(size(phase,2)-1)),size(phase,1),1);\n \n %% DopCentroidPoly/TimeCOAPoly\n % Another way to derive the Doppler Centroid, which is back-calculated\n % from the ESA-documented azimuth deramp phase function.\n output_meta{i}.RMA.INCA.DopCentroidPoly = output_meta{i}.Grid.Col.DeltaKCOAPoly * ...\n common_meta.Grid.Col.SS / ss_zd_s;\n dopcentroid2_sampled = sicd_polyval2d(output_meta{i}.RMA.INCA.DopCentroidPoly, coords_az_m, coords_rg_m);\n timecoa_sampled = timeca_sampled + (dopcentroid2_sampled./doprate_sampled);\n % Convert sampled TimeCOA to polynomial\n b_coa = zeros((POLY_ORDER+1)^2,1);\n for k=1:((POLY_ORDER+1)^2)\n b_coa(k)=sum(timecoa_sampled(:).*a(:,k)); % center of aperture\n end\n old_warning_state=warning('off','MATLAB:nearlySingularMatrix');\n x_coa=A\\b_coa;\n warning(old_warning_state);\n output_meta{i}.Grid.TimeCOAPoly=reshape(x_coa, POLY_ORDER+1, POLY_ORDER+1);\n\n %% Timeline\n % We don't know the precise start and stop time of each burst (as in\n % the times of first and last pulses), so we use the min and max COA\n % time, which is a closer approximation than the min and max zero\n % Doppler times. At least COA times will not overlap between bursts.\n if num_bursts>0 % STRIPMAP case uses another time origin different from first zero Doppler time\n time_offset = min(timecoa_sampled(:));\n % Datetime more precise than serial date number. This precision is\n % important for TOPSAR burst relationships. Datetime introduced in\n % MATLAB 2014b.\n output_meta{i}.Timeline.CollectStart = ... % Without fractional seconds\n datetime(start_s,'ConvertFrom','datenum');\n output_meta{i}.Timeline.CollectStart.Second = ... % With fraction seconds\n output_meta{i}.Timeline.CollectStart.Second + start_frac + time_offset;\n output_meta{i}.Timeline.CollectDuration = ...\n max(timecoa_sampled(:)) - min(timecoa_sampled(:));\n % Adjust all SICD fields that were dependent on start time\n % Time is output of polynomial:\n output_meta{i}.Grid.TimeCOAPoly(1) = ...\n output_meta{i}.Grid.TimeCOAPoly(1) - time_offset;\n output_meta{i}.RMA.INCA.TimeCAPoly(1) = ...\n output_meta{i}.RMA.INCA.TimeCAPoly(1) - time_offset;\n % Time is input of polynomial:\n for j = 'XYZ'\n output_meta{i}.Position.ARPPoly.(j) = ...\n polyshift(output_meta{i}.Position.ARPPoly.(j),time_offset);\n end\n end\n output_meta{i}.Timeline.IPP.Set.TStart=0;\n output_meta{i}.Timeline.IPP.Set.TEnd=output_meta{i}.Timeline.CollectDuration;\n output_meta{i}.Timeline.IPP.Set.IPPStart=uint32(0);\n output_meta{i}.Timeline.IPP.Set.IPPEnd=uint32(floor(output_meta{i}.Timeline.CollectDuration*prf)); % An approximation\n output_meta{i}.ImageFormation.TEndProc=output_meta{i}.Timeline.CollectDuration;\n\n %% GeoData\n % Rough estimate of SCP (interpolated from metadata geolocation grid)\n % to bootstrap (point_image_to_ground uses it only to find tangent to\n % ellipsoid.) Then we will immediately replace it with a more precise\n % value from point_image_to_ground and the SICD sensor model.\n output_meta{i}.GeoData.SCP.ECF.X = scp_x(i);\n output_meta{i}.GeoData.SCP.ECF.Y = scp_y(i);\n output_meta{i}.GeoData.SCP.ECF.Z = scp_z(i);\n % Note that blindly using the heights in the geolocationGridPointList\n % can result in some confusing results. Since the scenes can be\n % extremely large, you could easily be using a height in your\n % geolocationGridPointList that is very high, but still have ocean\n % shoreline in your scene. Blindly projecting the the plane tangent to\n % the inflated ellipsoid at SCP could result in some badly placed\n % geocoords in Google Earth. Of course, one must always be careful\n % with ground projection and height variability, but probably even more\n % care is warranted in this data than even usual due to large scene\n % sizes and frequently steep graze angles.\n % Note also that some Sentinel-1 data we have see has different heights\n % in the geolocation grid for polarimetric channels from the same\n % swath/burst!?!\n llh = ecf_to_geodetic([output_meta{i}.GeoData.SCP.ECF.X ...\n output_meta{i}.GeoData.SCP.ECF.Y output_meta{i}.GeoData.SCP.ECF.Z]);\n output_meta{i}.GeoData.SCP.LLH.Lat = llh(1);\n output_meta{i}.GeoData.SCP.LLH.Lon = llh(2);\n output_meta{i}.GeoData.SCP.LLH.HAE = llh(3);\n % Now that SCP has been populated, populate GeoData.SCP more precisely.\n ecf = point_image_to_ground([common_meta.ImageData.SCPPixel.Row; common_meta.ImageData.SCPPixel.Col], output_meta{i});\n output_meta{i}.GeoData.SCP.ECF.X=ecf(1);\n output_meta{i}.GeoData.SCP.ECF.Y=ecf(2);\n output_meta{i}.GeoData.SCP.ECF.Z=ecf(3);\n llh=ecf_to_geodetic([output_meta{i}.GeoData.SCP.ECF.X output_meta{i}.GeoData.SCP.ECF.Y output_meta{i}.GeoData.SCP.ECF.Z]);\n output_meta{i}.GeoData.SCP.LLH.Lat=llh(1);\n output_meta{i}.GeoData.SCP.LLH.Lon=llh(2);\n output_meta{i}.GeoData.SCP.LLH.HAE=llh(3);\n\n %% SCPCOA (and other stuff)\n output_meta{i} = derived_sicd_fields(output_meta{i});\nend\n\nend\n\n\n% Reproduces hamming functionality from the MATLAB Signal Processing\n% Toolbox, but allows for arbitrary coefficients of raised cosine.\nfunction w = raised_cos_fun(n, coef)\n w = coef - (1-coef)*cos(2*pi*(0:ceil(n/2)-1)'/(n-1));\n if ~rem(n,2)\n w = [w; w(end:-1:1)];\n else\n w = [w; w(end-1:-1:1)];\n end\nend\n\n% MATLAB's datenum function won't handle precise times down under a\n% millisecond, because 1) It won't accept a format with more than 3 .FFF in\n% the string description of the date format and 2) the resulting serial\n% date number is stored in days from 00-JAN-0000 and just doesn't have\n% enough bits to handle fractional seconds to the level we want. Here we\n% handle the fractional seconds separately so we can read date with the\n% precision we need.\nfunction [datenum_s, datenum_frac] = datenum_w_frac(datestring)\n datenum_s = datenum(datestring,'yyyy-mm-ddTHH:MM:SS');\n datenum_frac = str2double(regexp(datestring,'\\.\\d*','match'));\n if isnan(datenum_frac), datenum_frac = 0; end;\nend\n\n% Works on both restituted orbit files and precise orbit ephemerides orbit\n% files. Time range is a two-element vector of MATLAB date numbers.\n% Returned state vectors will be within a second of these bounds.\nfunction [ times_sec, times_frac, pos, vel ] = get_osv_from_eof( eof_domnode, time_range )\n\nSECONDS_IN_A_DAY = 24*60*60;\n\nosv_list = eof_domnode.getElementsByTagName('OSV');\n[times_sec, times_frac] = deal(zeros(osv_list.getLength,1));\n[pos, vel] = deal(zeros(osv_list.getLength,3));\nvalid = false(osv_list.getLength,1);\nfor i = 1:osv_list.getLength\n % Orbit files have 3 times (TAI, UTC, and UT1)\n % We choose UTC here, since 1) that is what is used in the orbit state\n % vectors in the SLC annotation file and 2) that is the SICD standard.\n % Restituted orbit files seem to have state vectors as the exact same\n % UTC times as those in the state vectors in the SLC annotation files,\n % while precise orbit files have state vectors on whole UTC seconds.\n time_reference = 'UTC';\n time_date_str = char(osv_list.item(i-1).getElementsByTagName(time_reference).item(0).getFirstChild().getData());\n time_date_str(1:strfind(time_date_str,'='))=''; % Remove 'UTC='\n [times_sec(i), times_frac(i)]= datenum_w_frac(time_date_str);\n if (nargin < 2) || ... % If no time ranges were passed in, read in all\n (((times_sec(i) - time_range(2)) - (1/SECONDS_IN_A_DAY) <= 0) && ...\n ((times_sec(i) - time_range(1)) + (1/SECONDS_IN_A_DAY) >= 0))\n pos(i,1) = str2double(osv_list.item(i-1).getElementsByTagName('X').item(0).getFirstChild().getData());\n pos(i,2) = str2double(osv_list.item(i-1).getElementsByTagName('Y').item(0).getFirstChild().getData());\n pos(i,3) = str2double(osv_list.item(i-1).getElementsByTagName('Z').item(0).getFirstChild().getData());\n vel(i,1) = str2double(osv_list.item(i-1).getElementsByTagName('VX').item(0).getFirstChild().getData());\n vel(i,2) = str2double(osv_list.item(i-1).getElementsByTagName('VY').item(0).getFirstChild().getData());\n vel(i,3) = str2double(osv_list.item(i-1).getElementsByTagName('VZ').item(0).getFirstChild().getData());\n valid(i) = true;\n if ~strcmpi('NOMINAL', osv_list.item(i-1).getElementsByTagName('Quality').item(0).getFirstChild().getData())\n warning('META2SICD_S1PRODUCT:DEGRADED_EPHEMERIS', ...\n 'Ephemeris found in requested file is of degraded quality.');\n end\n end\nend\nif ~any(valid)\n error('META2SICD_S1PRODUCT:NON_OVERLAPPING_EOF','EOF file does not span the same times as SLC.');\nend\npos = pos(valid,:);\nvel = vel(valid,:);\ntimes_sec = times_sec(valid);\ntimes_frac = times_frac(valid);\n\n% XPath version. Goes MUCH slower! Don't use.\n% xp=javax.xml.xpath.XPathFactory.newInstance.newXPath();\n% base_xpath = 'Earth_Explorer_File/Data_Block/List_of_OSVs/OSV';\n% num_grid_points=str2double(xp.evaluate(['count(' base_xpath ')'],dom_node));\n% for i = 1:num_grid_points\n% time_date_str = char(xp.evaluate([base_xpath '[' num2str(i) ']/UTC'],dom_node));\n% time_date_str(1:strfind(time_date_str,'='))=''; % Remove 'UTC='\n% [times_sec(i), times_frac(i)]= datenum_w_frac(time_date_str);\n% pos(i,1) = str2double(xp.evaluate([base_xpath '[' num2str(i) ']/X'],dom_node));\n% pos(i,2) = str2double(xp.evaluate([base_xpath '[' num2str(i) ']/Y'],dom_node));\n% pos(i,3) = str2double(xp.evaluate([base_xpath '[' num2str(i) ']/Z'],dom_node));\n% end\n\nend\n\n\n% //////////////////////////////////////////\n% /// CLASSIFICATION: UNCLASSIFIED ///\n% //////////////////////////////////////////", "meta": {"author": "ngageoint", "repo": "MATLAB_SAR", "sha": "6291feff8e200d387e271f49ec09b1acd5514c4e", "save_path": "github-repos/MATLAB/ngageoint-MATLAB_SAR", "path": "github-repos/MATLAB/ngageoint-MATLAB_SAR/MATLAB_SAR-6291feff8e200d387e271f49ec09b1acd5514c4e/IO/complex/sentinel1/meta2sicd_s1product.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526660244837, "lm_q2_score": 0.2974699363766585, "lm_q1q2_score": 0.16951403630637238}} {"text": "function [position,janelas,messages]= twavef_detector(heasig,samp,time,position,w,intervalo,messages)\n% script which identifies T wave, as well as its onset and offset\n% implementation of changes to improve FN and reduce mean error utilizando a escala 5\n%\n%\n%Input Parameters:\n% heasig: struct vector with header information\n% samp: samples included in the current excerpt (borders excluded)\n% time: QRS times in inedexes refering the interval included in the current excerpt (borders excluded)\n% position: struct vector with the detected points\n% w: matrix with WT scales 1 to 5\n% intervalo: numeration of the beats processed in this segment\n%\n%Output Parameters:\n% janelas: T wave seach windows\n% actualized parameters: position\n%\n% Rute Almeida\n% based on twave.m by Juan Pablo Mart�nez Cort�s\n% Last update: Rute Almeida 07FEB2012\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%\n% Designed for MATLAB Version R12; tested with MATLAB Version R13\n%\n%%%%%% Constants and Thresholds !!!!!!!!!!!!!!!!!!!!!!!!!\nif ~isfield(messages.setup.wavedet,'Kton')\n messages.setup.wavedet.Kton = 4; % 2 4!\nend\nif ~isfield(messages.setup.wavedet,'Ktoff')\n messages.setup.wavedet.Ktoff = 2.5;% 3.5 3!\nend\nif ~isfield(messages.setup.wavedet,'umbraldetT')\n messages.setup.wavedet.umbraldetT = 0.25; % We use umbraldet*sqrt(mean(w(time(i):time(i+1),4).^2))\nend\nif ~isfield(messages.setup.wavedet,'umbralsig')\n messages.setup.wavedet.umbralsig = 1/8; % To decide if there are really 2, 1 or no peak\n %threshold to decide if there is or not a significative\n % T wave.3!\nend\nif ~isfield(messages.setup.wavedet,'rrant_mintol')\n messages.setup.wavedet.rrant_mintol = 0.5; % minimum time in sec admited for current RR to be used in T wave delineation or in Exponentially averaged RR\nend\nif ~isfield(messages.setup.wavedet,'rrant_maxtol')\n messages.setup.wavedet.rrant_maxtol = 1.5; % max time in sec admited for current RR to be used in Exponentially averaged RR\nend\nif ~isfield(messages.setup.wavedet,'rrant_average')\n messages.setup.wavedet.rrant_average = [0.8 0.2]; % Exponentially averaged RR weights\nend\nif ~isfield(messages.setup.wavedet,'inivent_tol')\n messages.setup.wavedet.inivent_tol = 0.1;\nend\nif ~isfield(messages.setup.wavedet,'inivent_tol_S')\n messages.setup.wavedet.inivent_tol_S=0.05; % sec\nend\nif ~isfield(messages.setup.wavedet,'finvent_tol')\n messages.setup.wavedet.finvent_tol=0.240;% sec % it would be nioce to make it depend on round(rrmed/2)\nend\nif ~isfield(messages.setup.wavedet,'finvent_max')\n messages.setup.wavedet.finvent_max=0.6;% sec\nend\nif ~isfield(messages.setup.wavedet,'scale')\n messages.setup.wavedet.scale=4;\nend\nif ~isfield(messages.setup.wavedet,'scale2')\n messages.setup.wavedet.scale2=5;\nend\nif ~isfield(messages.setup.wavedet,'scalezerocros')\n messages.setup.wavedet.scalezerocros=3;\nend\nif ~isfield(messages.setup.wavedet,'scalezerocros2') %for twavetask5\n messages.setup.wavedet.scalezerocros2=4;\nend\n\nif ~isfield(messages.setup.wavedet,'min_vent')\n messages.setup.wavedet.min_vent=0.1;%sec\nend\nif ~isfield(messages.setup.wavedet,'Tmax_Tmin_time_min')\n messages.setup.wavedet.Tmax_Tmin_time_min=0.2;%0.15;%sec %10 ENE2012: 150 ms es poco\nend\nif ~isfield(messages.setup.wavedet,'Tmax_Tmin_bifasic')\n messages.setup.wavedet.Tmax_Tmin_bifasic=2.5;\nend\nif ~isfield(messages.setup.wavedet,'T_bound_tol')\n messages.setup.wavedet.T_bound_tol=0.12;%sec\nend\nKton=messages.setup.wavedet.Kton;\nKtoff=messages.setup.wavedet.Ktoff;\numbraldetT = messages.setup.wavedet.umbraldetT;\numbralsig = messages.setup.wavedet.umbralsig;\nrrant_mintol=messages.setup.wavedet.rrant_mintol;\nrrant_maxtol=messages.setup.wavedet.rrant_maxtol;\nrrant_average=messages.setup.wavedet.rrant_average;\ninivent_tol= messages.setup.wavedet.inivent_tol;\ninivent_tol_S=messages.setup.wavedet.inivent_tol_S;\nfinvent_tol=messages.setup.wavedet.finvent_tol;\nfinvent_max= messages.setup.wavedet.finvent_max;\nscale=messages.setup.wavedet.scale;\nscale2=messages.setup.wavedet.scale2;\nscalezerocros=messages.setup.wavedet.scalezerocros;\nscalezerocros2=messages.setup.wavedet.scalezerocros2; %#ok\nmin_vent=messages.setup.wavedet.min_vent;%sec\nTmax_Tmin_time_min= messages.setup.wavedet.Tmax_Tmin_time_min;%sec\nTmax_Tmin_bifasic=messages.setup.wavedet.Tmax_Tmin_bifasic;% extra criteria\nT_bound_tol=messages.setup.wavedet.T_bound_tol;\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nif isempty(heasig)\n \nend\n% janelas=[];\n% endwinT=[];\n\n% Initialization of auxiliary variables\nif length(time)>1\n rrant = time(2)-time(1);\nelse\n aux=find(position.qrs~=0);\n if length(aux)>1\n rrant= diff(position.qrs(aux(end-1):aux(end))); %18MAR09\n else\n rrant=messages.setup.wavedet.freq;\n end\nend\n\n%18MAR09 % for the case in which the first RR is very wrong AGO2011\nif rrantrrant_maxtol*messages.setup.wavedet.freq;\n messages.warnings=[messages.warnings {['RR lower than' rrant_mintol*messages.setup.wavedet.freq ' ms or higher than' rrant_maxtol*messages.setup.wavedet.freq ' found in twavef']}];\n rrant=rrant_mintol*messages.setup.wavedet.freq;%Jul2011\nend\n\nT = []; Tprima=[]; picon=[]; picoff=[]; Ton=[]; Toff=[]; tipoT=[];\n% minapos = []; minppos=[]; maxapos=[]; maxppos=[]; mina=[]; minp=[]; maxa=[];\n% maxp=[];\npicon_keep=[];%multileadchange\npicoff_keep=[];%multileadchange\nlead_keep=[];%multileadchange\n\n\n\n%figure\n%%%plot(messages.lixo)\n% hold on\njanelas=NaN*ones(length(time),3);\nendwinT=NaN*ones(length(time),1);\nfor i = 1:length(time) % For each beat\n \n \n \n if (i>1),\n if (rrant_maxtol*rrant>(time(i)-time(i-1)))&&(time(i)-time(i-1)>rrant_mintol*rrant),\n rrmed = rrant_average(1)*rrant + rrant_average(2)*(time(i)-time(i-1));% Exponentially averaged RR new value\n else\n rrmed = rrant; % Exponentially averaged RR old value\n end\n else % Only for the first in each segment of the ECG\n rrmed = rrant;\n end\n rrant = rrmed; % For next segment\n inivent = round(inivent_tol*messages.setup.wavedet.freq); % Begining of window\n \n \n %Rute multilead 03.Dec.04\n \n %if ~isempty(pos.S(i)), % If there is an S wave\n % inivent = max(inivent, pos.S(i)-pos.qrs(i)+round(0.05*messages.setup.wavedet.freq));\n % end\n \n if ~isempty(position.S(i+intervalo(1)-1));\n inivent = max(inivent, position.S(i+intervalo(1)-1)-samp(1)+1-time(i)+round(inivent_tol_S*messages.setup.wavedet.freq));\n end\n \n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% changed 13/06/02 Rute\n %if rrmed >= messages.setup.wavedet.freq, %\n %if rrmed <= messages.setup.wavedet.freq, % 21AGO09 % for rrmed < 1 seg finiven=finvent_max seg\n if rrmed <= messages.setup.wavedet.freq && i~=length(time) && (rrant_maxtol*rrant>(time(i+1)-time(i)))&&(time(i+1)-time(i)>rrant_mintol*rrant) %02FEB2011\n finvent = round(finvent_max*messages.setup.wavedet.freq); % End of window\n else\n finvent = round(rrmed*finvent_max);\n end\n \n \n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% changed 13/06/02 Rute\n if i~=length(time), % For last beat in the segment\n %finvent = min(finvent,time(i+1)-time(i)-round(finvent_tol*messages.setup.wavedet.freq));\n %finvent = min(finvent,time(i+1)-time(i)-min(round((time(i+1)-time(i))*1/3),round(finvent_tol*messages.setup.wavedet.freq)));\n finvent = min(finvent,time(i+1)-time(i)-min(round((time(i+1)-time(i))*0.4),round(finvent_tol*messages.setup.wavedet.freq)));\n elseif i~=1%Rute 18MAR09\n finvent = min(finvent,time(i)-time(i-1)-round(finvent_tol*messages.setup.wavedet.freq));\n elseif length(aux)>1\n finvent = min(finvent,diff(position.qrs(aux(end-1):aux(end)))-round(finvent_tol*messages.setup.wavedet.freq));%Rute 18MAR09\n end\n \n % We work at scale 4 (in general).\n if isempty(position.QRSoff(i+intervalo(1)-1)), % Should never happen, but...\n begwin = min(inivent + time(i),length(w)); %Rute 4Jul2011\n else\n begwin = min(max(inivent + time(i), position.QRSoff(i+intervalo(1)-1)-samp(1)+1+1),length(w));%Rute 4Jul2011\n % if QRSoff is bad anoated it can miss T wave...\n end\n \n endwin = max(1,min(finvent + time(i),length(w))); %% Rute 20/05/02\n janelas(i,:)=[i begwin endwin];\n endwinT(i)=endwin;\n %%%%plot([begwin endwin ], messages.lixo([begwin endwin]),'*g')\n \n % Positive maxima and negative minima in the window\n maxpos = begwin + modmax(w(begwin+1:endwin,scale),2,0,+1);\n minpos = begwin + modmax(w(begwin+1:endwin,scale),2,0,-1);\n [maxim ind] = max(w(maxpos,scale)); % The biggest of the positive\n maxpos = maxpos(ind);\n [minim ind] = min(w(minpos,scale)); % The biggest of the negative\n minpos = minpos(ind);\n \n if isempty(maxpos), % If no local positive maximum\n % The maximum will be the first\n % or the last sample\n if (w(begwin,scale)>=w(endwin,scale)) && w(begwin,scale)>0,\n maxpos = begwin; maxim = w(maxpos,scale);\n elseif (w(endwin,scale)>=w(begwin,scale)) && w(endwin,scale)>0,\n maxpos = endwin; maxim = w(maxpos,scale);\n end\n end\n if isempty(minpos), % if no local negative minimum\n % the minimum will be the first\n % or the last sample\n if (w(begwin,scale)<=w(endwin,scale)) && w(begwin,scale)<0,\n minpos = begwin; minim = w(minpos,scale);\n elseif (w(endwin,scale)<=w(begwin,scale)) && w(endwin,scale)<0,\n minpos = endwin; minim = w(minpos,scale);\n end\n end\n \n absmax = abs(maxim);\n absmin = abs(minim);\n \n if iumbraldetT*veficaz)|(absmin>umbraldetT*veficaz));\n if isempty(hay_onda)\n hay_onda = 0;\n end\n % Rute 18/06/02\n \n if endwin-begwin<(min_vent*messages.setup.wavedet.freq) || isnan(hay_onda)% se a janela tem amplitude menor do que min_vent seg enato nao existe onda T\n hay_onda =0;\n end\n \n % Is there a wave?\n if hay_onda,\n if absmax >= absmin, % the greatest modulus maximum is the maximum\n % Now we search the two minima nearest to maxpos, one before and one after\n minapos = max(modmax(w(begwin+1:maxpos-1,scale),2,0,-1));\n minapos = begwin + minapos; % Position of the negative minimum before the maximum\n if isempty(minapos) && (maxpos ~= begwin) && (w(begwin,scale)<0),\n minapos = begwin;% If no local minimum before the maximum, take the first sample\n end\n minppos = min(modmax(w(maxpos+1:endwin,scale),2,0,-1));\n minppos = maxpos + minppos; % Position of the positive maximum after the minimum\n if isempty(minppos) && (maxpos ~= endwin) && (w(endwin,scale)<0),\n minppos = endwin; % If no local minimum after the maximum, take the last sample\n end\n \n mina = abs(w(minapos,scale)); % Amplitude of minimum before maximum\n minp = abs(w(minppos,scale)); % Amplitude of minimum after maximum\n \n if (mina < umbralsig*absmax), % If mina is not big enough\n mina =[]; % forget it\n \n elseif (maxpos-minapos>Tmax_Tmin_time_min*messages.setup.wavedet.freq), %or if ther are more than Tmax_Tmin_time_min sec to maxpos\n mina = [];\n end\n if (minp < umbralsig*absmax), % If minp is not big enough\n minp =[]; % forget it\n elseif (minppos-maxpos>Tmax_Tmin_time_min*messages.setup.wavedet.freq), % and also if there are more than Tmax_Tmin_time_min sec to maxpos\n minp =[];\n end\n \n if ~isnan(mina)&~isnan(minp), %#ok %%% NUEVO JP\n if (mina >= minp)&&(minp < umbralsig*absmax*Tmax_Tmin_bifasic),\n minp = [];\n elseif (minp> mina)&&(mina < umbralsig*absmax*Tmax_Tmin_bifasic),\n mina = [];\n end\n end\n \n % Test which modulus maxima are significative and find zero crossings\n if isempty(mina),\n if isempty(minp),\n tipoT = 2; % only upwards T wave\n if maxpos - minapos > 2, % if not !!!!!!!!!!!\n ind = zerocros(flipud(w(minapos:maxpos,scalezerocros))); %Scale scalezerocros !!!\n T = maxpos - ind +1; % Zero crossing = T wave position\n picoff = maxpos; %wavelet peak to detect offset\n elseif isempty(minapos); % If there were no minimum, there is no zero crossing\n T = picant (w(begwin:maxpos,scale),maxpos); % Take the minimum at scale scale\n if ~isempty(T) %%%%%%%%%%%% 14/06/02 Rute\n picoff = maxpos;\n else\n picoff = []; % if did not exist a peak in scale scale there is no T\n end %%%%%%%%%%%% 14/06/02 Rute\n else %%%%%%%%%%%%%%%%%%%%% nao faz nada!!!!!!! % 12/06/02 Rute\n messages.warnings=[messages.warnings {'unknown case: unable to classify T wave' }];\n end\n else % minp exists (is significative) but mina not\n tipoT = 0; \t\t%normal T wave\n if minppos -maxpos >2, % if not!!!!!!???\n ind = zerocros(w(maxpos:minppos,scalezerocros)); %% 07/06/02 Rute\n if isempty(ind) %%%%%%%%%%%%%%Rute 03/09/02\n ind = zerocros(w(maxpos:minppos,scale));\n end %%%%%%%%%%%%%%Rute 03/09/02\n T = maxpos + ind -1;\n picon = maxpos;\t\t% For determining onset and offset\n picoff = minppos;\n else %%%%%%%%%%%%%%%%%%%%% nao faz nada!!!!!!! % 12/06/02 Rute\n messages.warnings=[messages.warnings {'unknown case: unable to classify T wave'}];\n end\n end\n else\n if isempty(minp), % mina exists (is significative) but minp not\n tipoT = 1; \t%inverted T wave\n if maxpos -minapos >2, % if not !!!!!!!!!\n ind = zerocros(w(minapos:maxpos,scalezerocros)); % wavelet zero crossing is T wave peak %% 07/06/02 Rute\n if isempty(ind)%%%%%%%%%%%%%%Rute 03/09/02\n ind = zerocros(w(minapos:maxpos,scale)); % wavelet zero crossing is T wave peak %% 03/09/02 Rute\n end %%%%%%%%%%%%%%Rute 03/09/02\n T = minapos + ind -1;\n picon = minapos;\n picoff = maxpos;\n else %%%%%%%%%%%%%%%%%%%%% nao faz nada!!!!!!! % 12/06/02 Rute\n messages.warnings=[messages.warnings {'unknown case: unable to classify T wave'}];\n end\n else % both mina and minp are significative. Biphasic wave.\n tipoT = 5;\t% biphasic neg-pos T wave\n if maxpos - minapos > 2, %!!!!!!!!!!!!\n ind = zerocros(flipud(w(minapos:maxpos,scalezerocros))); %% 07/06/02 Rute\n if isempty(ind) %%%%%%%%%%%%%%Rute 03/09/02\n ind = zerocros(flipud(w(minapos:maxpos,scale))); %% 03/09/02 Rute\n \n end%%%%%%%%%%%%%%Rute 03/09/02\n T = maxpos - ind +1;\n picon = minapos;\n else %%%%%%%%%%%%%%%%%%%%% nao faz nada!!!!!!! % 12/06/02 Rute\n messages.warnings=[messages.warnings {'unknown case: unable to classify T wave'}];\n end\n if minppos - maxpos > 2, %!!!!!!!!!!!!\n ind = zerocros(flipud(w(maxpos:minppos,scalezerocros))); %% 07/06/02 Rute\n if isempty(ind)%%%%%%%%%%%%%%Rute 03/09/02\n %ind = zerocros(flipud(w(minapos:maxpos,scale))); %% 03/09/02 Rute %18.11.05 DUVIDA\n %DUVIDA 18Nov05\n ind = zerocros(flipud(w(maxpos:minppos,scale))); %% 03/09/02 Rute\n end %%%%%%%%%%%%%%Rute 03/09/02\n %Tprima = maxpos + ind -1;\n %DUVIDA 18Nov05\n Tprima = minppos- ind +1;\n picoff = minppos;\n else %%%%%%%%%%%%%%%%%%%%% nao faz nada!!!!!!! % 12/06/02 Rute\n messages.warnings=[messages.warnings {'unknown case: unable to classify T wave'}];\n end\n end\n end\n else % If the greatest modulus maximum is the minimum\n % Search two maxima, one before and one after the minimum\n maxapos = max(modmax(w(begwin+1:minpos-1,scale),2,0,1));\n maxapos = begwin + maxapos;\n if isempty(maxapos) && (minpos ~= begwin) && (w(begwin,scale)>0),\n maxapos = begwin;\n end\n maxppos = min(modmax(w(minpos+1:endwin,scale),2,0,1));\n maxppos = minpos + maxppos;\n if isempty(maxppos) && (minpos ~= endwin) && (w(endwin,scale)>0),\n maxppos = endwin;\n end\n maxa = abs(w(maxapos,scale));\n maxp = abs(w(maxppos,scale)) ; % See if they are significative\n if (maxa < umbralsig*absmin)\n maxa =[];\n elseif (minpos-maxapos>Tmax_Tmin_time_min*messages.setup.wavedet.freq),\n maxa = [];\n end\n if (maxp < umbralsig*absmin),\n maxp =[];\n elseif (maxppos-minpos>Tmax_Tmin_time_min*messages.setup.wavedet.freq),\n maxp = [];\n end\n if ~isnan(maxa)&~isnan(maxp), %#ok %%% NUEVO JP\n if (maxa >= maxp)&&(maxp < umbralsig*absmin*Tmax_Tmin_bifasic),\n maxp = [];\n elseif (maxp> maxa)&&(maxa < umbralsig*absmin*Tmax_Tmin_bifasic),\n maxa = [];\n end\n end\n % Test which modulus maxima are significative and find zero crossings\n if isempty(maxa),\n if isempty(maxp),\n tipoT = 3; % only downwards T wave\n if minpos - maxapos > 2, %!!!!!!!!\n ind = zerocros(flipud(w(maxapos:minpos,scalezerocros))); %Scale scalezerocros\n if isempty(ind) %%%%%%%%%%%%%%Rute 03/09/02\n ind = zerocros(flipud(w(maxapos:minpos,scale)));\n end %%%%%%%%%%%%%%Rute 03/09/02\n T = minpos - ind +1;\n picoff = minpos;\n elseif isempty(maxapos); % If there were no maximum, there is no zero crossing.\n T = picant (w(begwin:minpos,scale),minpos); % minimo en escala scale.\n if ~isempty(T) %%%%%%%%%%%% 14/06/02 Rute\n picoff = minpos;\n else\n picoff = []; % if did not exist a peak in scale scale there is no T\n end %%%%%%%%%%%% 14/06/02 Rute\n else %%%%%%%%%%%%%%%%%%%%% nao faz nada!!!!!!! % 12/06/02 Rute\n messages.warnings=[messages.warnings {'unknown case: unable to classify T wave'}];\n end\n else % maxp is signficative, but not maxa\n tipoT = 1; %inverted T wave\n if maxppos -minpos >2, % !!!!!!\n ind = zerocros(w(minpos:maxppos,scalezerocros)); %% 07/06/02 Rute\n if isempty(ind) %%%%%%%%%%%%%%Rute 03/09/02\n ind = zerocros(w(minpos:maxppos,scale)); %% 03/09/02 Rute\n end %%%%%%%%%%%%%%Rute 03/09/02\n T = minpos + ind -1;\n picon = minpos;\t\t% For calculating onset and offset\n picoff = maxppos;\n else %%%%%%%%%%%%%%%%%%%%% nao faz nada!!!!!!! % 12/06/02 Rute\n messages.warnings=[messages.warnings {'unknown case: unable to classify T wave'}];\n end\n end\n else\n if isempty(maxp), % maxa is significative, but not maxp\n tipoT = 0; %normal T wave\n if minpos -maxapos >2,\n ind = zerocros(w(maxapos:minpos,scalezerocros)); %% 07/06/02 Rute\n if isempty(ind) %%%%%%%%%%%%%%%%%%%% 03/09/02 Rute\n ind = zerocros(w(maxapos:minpos,scale)); %% 03/09/02 Rute\n end %%%%%%%%%%%%%%%%%%%% 03/09/02 Rute\n T = maxapos + ind -1;\n picon = maxapos;\n picoff = minpos;\n else %%%%%%%%%%%%%%%%%%%%% nao faz nada!!!!!!! % 12/06/02 Rute\n messages.warnings=[messages.warnings {'unknown case: unable to classify T wave'}];\n end\n else % both maxa and maxp are significative. Biphasic wave.\n tipoT = 4;\t% biphasic pos-neg T wave\n if minpos - maxapos > 2, %!!!!!!!!!!!\n ind = zerocros(flipud(w(maxapos:minpos,scalezerocros))); %% 07/06/02 Rute\n if isempty(ind) %%%%%%%%%%%%%%%%%%%% 03/09/02 Rute\n ind = zerocros(flipud(w(maxapos:minpos,scale))); %% 03/09/02 Rute\n end %%%%%%%%%%%%%%%%%%%% 03/09/02 Rute\n T = minpos - ind +1;\n picon = maxapos;\n else %%%%%%%%%%%%%%%%%%%%% nao faz nada!!!!!!! % 12/06/02 Rute\n messages.warnings=[messages.warnings {'unknown case: unable to classify T wave'}];\n end\n if maxppos - minpos > 2, %!!!!!!!!!!!!\n ind = zerocros(flipud(w(minpos:maxppos,scalezerocros))); %% 07/06/02 Rute\n if isempty(ind) %%%%%%%%%%%%%%%%%%%% 03/09/02 Rute\n %ind = zerocros(flipud(w(minapos:maxpos,scale))); %% 03/09/02 Rute %18.11.05 DUVIDA\n %DUVIDA 18Nov05\n ind = zerocros(flipud(w(minpos:maxppos,scale))); %% 03/09/02 Rute\n end %%%%%%%%%%%%%%%%%%%% 03/09/02 Rute\n %Tprima = minpos + ind -1; %18.11.05 DUVIDA\n %DUVIDA 18Nov05\n Tprima = maxppos- ind +1;\n picoff = maxppos;\n else %%%%%%%%%%%%%%%%%%%%% nao faz nada!!!!!!! % 12/06/02 Rute\n messages.warnings=[messages.warnings {'unknown case: unable to classify T wave'}];\n end\n end\n end\n end\n \n % T wave onset and offset detection\n %if isempty(T), picon=[]; picoff=[]; end\n \n picon_keep=[picon_keep picon]; %#ok %multileadchange\n picoff_keep=[picoff_keep picoff]; %#ok %multileadchange\n lead_keep=[lead_keep scale]; %#ok %multileadchange\n \n if ~isempty(picon),\n Ton = searchon (picon, w(max(begwin,picon-round(T_bound_tol*messages.setup.wavedet.freq)):picon,scale), Kton);\n end\n if ~isempty(picoff),\n Toff=searchoff(picoff, w(picoff:min([size(w,1) picoff+round(T_bound_tol*messages.setup.wavedet.freq) ]) ,scale) , Ktoff);\n if (Toff > endwin),\n Toff = endwin;\n end\n end\n else\n %% using scale 5 07/06/02 Rute %%%%%%%%%%%%%%%%%%%%%%%%%%%\n %% Neste momento usa-se a mesma janela e os mesmos limiares que para a escala scale\n \n maxpos = begwin + modmax(w(begwin+1:endwin,scale2),2,0,+1);\n minpos = begwin + modmax(w(begwin+1:endwin,scale2),2,0,-1);\n [maxim ind] = max(w(maxpos,scale2)); % The biggest of the positive\n maxpos = maxpos(ind);\n [minim ind] = min(w(minpos,scale2)); % The biggest of the negative\n minpos = minpos(ind);\n if isempty(maxpos), % If no local positive maximum\n % The maximum will be the first\n % or the last sample\n if (w(begwin,scale2)>=w(endwin,scale2)) && w(begwin,scale2)>0,\n maxpos = begwin; maxim = w(maxpos,scale2);\n elseif (w(endwin,scale2)>=w(begwin,scale2)) && w(endwin,scale2)>0,\n maxpos = endwin; maxim = w(maxpos,scale2);\n end\n end\n if isempty(minpos), % if no local negative minimum\n % the minimum will be the first\n % or the last sample\n if (w(begwin,scale2)<=w(endwin,scale2)) && w(begwin,scale2)<0,\n minpos = begwin; minim = w(minpos,scale2);\n elseif (w(endwin,scale2)<=w(begwin,scale2)) && w(endwin,scale2)<0,\n minpos = endwin; minim = w(minpos,scale2);\n end\n end\n \n absmax = abs(maxim);\n absmin = abs(minim);\n if iumbraldetT*veficaz)|(absmin>umbraldetT*veficaz));\n \n if endwin-begwin<(min_vent*messages.setup.wavedet.freq) % se a janela tem amplitude menor do que min_vent seg enato nao existe onda T\n hay_ondascale2 =0;\n end\n if hay_ondascale2,\n t5; % procurar na escala scale2 10/07/02 Rute\n picon_keep=[picon_keep picon];%#ok %multileadchange\n picoff_keep=[picoff_keep picoff];%#ok%multileadchange\n lead_keep=[lead_keep scale2];%#ok%multileadchange\n end\n end\n % Is there a wave\n %% utilizar a escala scale2 07/06/02 Rute %%%%%%%%%%%%%%%%%%%%%%%%%%%\n \n % Filling the structure with positions\n if isempty(Ton), Ton = NaN; end;\n if isempty(Toff), Toff = NaN; end;\n if isempty(T), T=NaN; end;\n if isnan(T),\n picon_keep=[picon_keep NaN]; %#ok%multileadchange\n picoff_keep=[picoff_keep NaN]; %#ok%multileadchange\n lead_keep=[lead_keep NaN]; %#ok%multileadchange\n end\n if isempty(Tprima), Tprima=NaN; end;\n if isempty(tipoT), tipoT=NaN; end;\n pos.Tscale(i)=scale;\n pos.Ton(i) = Ton;\n pos.Toff(i) = Toff;\n pos.T(i) = T;\n pos.Tprima(i) = Tprima;\n pos.Ttipo(i) = tipoT;\n %%%plot([Toff(~isnan(Toff))], messages.lixo([Toff(~isnan(Toff))]),'*r')\n T = []; Tprima=[]; picon=[]; picoff=[]; Ton=[]; Toff=[]; tipoT=[];\n% minapos = []; minppos=[]; maxapos=[]; maxppos=[]; mina=[]; minp=[]; maxa=[];\n% maxp=[];\n \nend\nposition.Tscale(intervalo(1):intervalo(2)) = pos.Tscale;\nposition.Ton(intervalo(1):intervalo(2)) = pos.Ton+samp(1)-1;\nposition.Toff(intervalo(1):intervalo(2))= pos.Toff+samp(1)-1;\nposition.T(intervalo(1):intervalo(2)) = pos.T+samp(1)-1;\nposition.Tprima(intervalo(1):intervalo(2)) = pos.Tprima+samp(1)-1;\nposition.Ttipo(intervalo(1):intervalo(2)) = pos.Ttipo;", "meta": {"author": "cliffordlab", "repo": "PhysioNet-Cardiovascular-Signal-Toolbox", "sha": "eec46e75e0b95c379ecb68cb0ebee0c4c9f54605", "save_path": "github-repos/MATLAB/cliffordlab-PhysioNet-Cardiovascular-Signal-Toolbox", "path": "github-repos/MATLAB/cliffordlab-PhysioNet-Cardiovascular-Signal-Toolbox/PhysioNet-Cardiovascular-Signal-Toolbox-eec46e75e0b95c379ecb68cb0ebee0c4c9f54605/Tools/ECG_Analysis_Tools/MV/Tools/Annotation_generator/twavef_detector.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832058771036, "lm_q2_score": 0.3140505321516081, "lm_q1q2_score": 0.16926796262648414}} {"text": "function [qrs,jpoints] = wqrsm_fast(data,fs,PWfreq,TmDEF,jflag)\n% The swqrsm detector rewrited from swqrsm.c\n% rewrited by Giulia Da Poian, August 7, 2018\n% use struct swqrsm instead of global varaibles\n% giulia.da.poian@emory.com\n%\n% input:\n% data: ECG data, the swqrsm.c used the data in raw adus, if the input \n% data is in physical units, when the function found the peak-peak \n% value < 10, it will multiply the value by WFDB_DEFGAIN (200)\n% fs: sampling frequency (default: 125)\n% PWfreq: power line (mains) frequency, in Hz (default: 60)\n% TmDEF: minimum threshold value (default: 100)\n% jflag: annotate J-points (ends of QRS complexes) (default: 0)\n% output:\n% qrs: QRS fiducial mark in samples\n% jpoints:J-points annotation, if jflag==1\n%\n% Matlab code based on:\n% file: swqrsm.c\t\tWei Zong 23 October 1998\n% \t\t\tLast revised: 9 April 2010 (by G. Moody)\n% -----------------------------------------------------------------------------\n% swqrsm: Single-lead QRS detector based on length transform\n% Copyright (C) 1998-2010 Wei Zong\n% \n% This program is free software; you can redistribute it and/or modify it under\n% the terms of the GNU General Public License as published by the Free Software\n% Foundation; either version 2 of the License, or (at your option) any later\n% version.\n% \n% This program is distributed in the hope that it will be useful, but WITHOUT ANY\n% WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\n% PARTICULAR PURPOSE. See the GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License along with\n% this program; if not, write to the Free Software Foundation, Inc., 59 Temple\n% Place - Suite 330, Boston, MA 02111-1307, USA.\n% \n% You may contact the author by e-mail (wzong@mit.edu) or postal mail\n% (MIT Room E25-505, Cambridge, MA 02139, USA). For updates to this software,\n% please visit PhysioNet (http://www.physionet.org/).\n% ------------------------------------------------------------------------------\n% \n% This program analyzes an ECG signal, detecting QRS onsets and J-points, using\n% a nonlinearly-scaled ECG curve length feature. This version has been optimized\n% for ECGs sampled at 125 Hz, but it can analyze ECGs sampled at any frequency\n% using on-the-fly resampling provided by the WFDB library.\n% \n% `swqrsm' can process records containing any number of signals, but it uses only\n% one signal for QRS detection (signal 0 by default; this can be changed using\n% the `-s' option, see below). 'swqrsm' has been optimized for adult human ECGs.\n% For other ECGs, it may be necessary to experiment with the input sampling\n% frequency and the time constants.\n% ----------------------------------------------------------------------\n% This matlab version has updates to deal with a variable sampling \n% frequency but has not been exhanstively tested. \n% ----- Add notes here:\n%\n%\n\nif nargin<5\njflag = 0;\nend\nif nargin<4\nTmDEF = 100;\nend\nif nargin<3\nPWfreq = 60;\nend\nif nargin<2\nfs = 125;\nend\n\nswqrsm.BUFLN = 16384; %\t/* must be a power of 2, see ltsamp() */\nEYE_CLS = 0.25; % /* eye-closing period is set to 0.25 sec (250 ms) */ \nMaxQRSw = 0.13; % /* maximum QRS width (130ms) */ \nNDP\t= 2.5; % /* adjust threshold if no QRS found in NDP seconds */\nPWFreqDEF = PWfreq; % /* power line (mains) frequency, in Hz (default) */\n% TmDEF = 100; %\t/* minimum threshold value (default) */\nWFDB_DEFGAIN = 200.0; % /* default value for gain (adu/physical unit) */\n\ntimer_d=0;\ngain=WFDB_DEFGAIN;\nswqrsm.lfsc = fix(1.25*gain*gain/fs);\t% /* length function scale constant */\nPWFreq = PWFreqDEF;\t% /* power line (mains) frequency, in Hz */\n\n% test data is physical units (mV) or raw adus units\ndatatest=data(1:fix(length(data)/fs)*fs);\nif length(datatest)>fs\ndatatest=reshape(datatest,fs,[]);\nend\ntest_ap=median(max(datatest)-min(datatest));\nif test_ap<10 % peak-peak < 10 mV, may physical units\ndata=data*gain;\nend\n\nswqrsm.data = data;\nswqrsm.lbuf = zeros(swqrsm.BUFLN,1);\nswqrsm.ebuf = zeros(swqrsm.BUFLN,1);\nswqrsm.ebuf(1:end)=fix(sqrt(swqrsm.lfsc));\nswqrsm.lt_tt = 0;\nswqrsm.aet = 0;\nswqrsm.Yn = 0;\nswqrsm.Yn1 = 0;\nswqrsm.Yn2 = 0;\n\nqrs = [];\njpoints = [];\n\nTm = fix(TmDEF / 5.0);\n% spm = 60 * fs;\n% next_minute = from + spm;\nswqrsm.LPn = fix(fs/PWFreq); %\t\t/* The LP filter will have a notch at the power line (mains) frequency */\nif (swqrsm.LPn > 8) \nswqrsm.LPn = 8;\t% /* avoid filtering too agressively */\nend\nswqrsm.LP2n = 2 * swqrsm.LPn;\nEyeClosing = fix(fs * EYE_CLS); % /* set eye-closing period */\nExpectPeriod = fix(fs * NDP); % /* maximum expected RR interval */\nswqrsm.LTwindow = fix(fs * MaxQRSw); % /* length transform window size */\n\n% for i=1:2000\n% ltdata(i)=ltsamp(i);\n% end\n% /* Average the first 8 seconds of the length-transformed samples\n% to determine the initial thresholds Ta and T0. The number of samples\n% in the average is limited to half of the ltsamp buffer if the sampling\n% frequency exceeds about 2 KHz. */\n\nt1 = fs*8;\nif t1> fix(swqrsm.BUFLN*0.9)\n t1=swqrsm.BUFLN/2;\nend\n\nT0=0;\nfor t=1:t1\n swqrsm = ltsamp(t,swqrsm);\n T0 = T0 + swqrsm.lt_data;\nend\n\nT0 = T0 / t1;\nTa = 3 * T0;\n\n% /* Main loop */\nt=1;\nlearning=1;\nwhile t t1) \n learning = 0;\n T1 = T0;\n t = 1;\t% /* start over */\n else\n T1 = 2*T0;\n end\n end\n\n % /* Compare a length-transformed sample against T1. */\n swqrsm = ltsamp(t,swqrsm);\n if ( swqrsm.lt_data > T1) %\t/* found a possible QRS near t */\n timer_d = 0; % /* used for counting the time after previous QRS */\n maxd = swqrsm.lt_data;\n mind = maxd;\n for tt = t+1:t + fix(EyeClosing/2)\n swqrsm = ltsamp(tt,swqrsm);\n if (swqrsm.lt_data > maxd) \n maxd = swqrsm.lt_data;\n end\n end\n for tt = t-1:-1:t - fix(EyeClosing/2)\n swqrsm = ltsamp(tt,swqrsm);\n if (swqrsm.lt_data < mind) \n mind = swqrsm.lt_data;\n end\n end\n if (maxd > mind+10) % /* There is a QRS near tt */\n % /* Find the QRS onset (PQ junction) */\n onset = fix(maxd/100) + 2;\n tpq = t - 5;\n for tt = t:-1:t - fix(EyeClosing/2)\n swqrsm = ltsamp(tt,swqrsm);\n swqrsm_1 = ltsamp(tt-1,swqrsm);\n swqrsm_2 = ltsamp(tt-2,swqrsm_1);\n swqrsm_3 = ltsamp(tt-3,swqrsm_2);\n swqrsm_4 = ltsamp(tt-4,swqrsm_3);\n if (swqrsm.lt_data - swqrsm_1.lt_data < onset && swqrsm_1.lt_data - swqrsm_2.lt_data < onset && swqrsm_2.lt_data - swqrsm_3.lt_data < onset && swqrsm_3.lt_data - swqrsm_4.lt_data < onset) \n swqrsm = swqrsm_4;\n tpq = tt - swqrsm.LP2n; %\t/* account for phase shift */\n break;\n end\n end\n\n if (learning~=1) \n % /* Check that we haven't reached the end of the record. */\n if tpq>length(data)\n break;\n end\n % /* Record an annotation at the QRS onset */\n qrs = [qrs tpq];\n\n % J-points processing\n if (jflag)\n tj = t+5;\n for tt=t:t + fix(EyeClosing/2)\n swqrsm = ltsamp(tt, swqrsm);\n if swqrsm.lt_data > maxd - fix(maxd/10)\n tj = tt;\n break;\n end\n end\n if tj>length(data)\n break;\n end\n % Record an annotation at the J-point\n jpoints = [jpoints tj];\n end\n end\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 = t + EyeClosing;\n end\n\n elseif (learning~=1) \n % \t /* Once past the learning period, decrease threshold if no QRS\n % \t was detected recently. */\n timer_d = timer_d + 1;\n if timer_d > ExpectPeriod && Ta > Tm\n Ta = Ta -1;\n T1 = Ta / 3;\n end\n end\n t = t+1;\nend\n\nend\n\nfunction swqrsm = ltsamp(t,swqrsm)\n % /* ltsamp() returns a sample of the length transform of the input at time t.\n % Since this program analyzes only one signal, ltsamp() does not have an\n % input argument for specifying a signal number; rather, it always filters\n % and returns samples from the signal designated by the global variable\n % 'sig'. The caller must never \"rewind\" by more than swqrsm.BUFLN samples (the\n % length of ltsamp()'s buffers). */\n while (t > swqrsm.lt_tt) \n swqrsm.Yn2 = swqrsm.Yn1;\n swqrsm.Yn1 = swqrsm.Yn;\n v0=swqrsm.data(1);\n v1=swqrsm.data(1);\n v2=swqrsm.data(1);\n if swqrsm.lt_tt>0 && swqrsm.lt_tt<=length(swqrsm.data)\n v0 = swqrsm.data(swqrsm.lt_tt);\n end\n if swqrsm.lt_tt-swqrsm.LPn>0 && (swqrsm.lt_tt-swqrsm.LPn)<=length(swqrsm.data)\n v1 = swqrsm.data(swqrsm.lt_tt-swqrsm.LPn);\n end \n if swqrsm.lt_tt-swqrsm.LP2n>0 && (swqrsm.lt_tt-swqrsm.LP2n)<=length(swqrsm.data)\n v2 = swqrsm.data(swqrsm.lt_tt-swqrsm.LP2n);\n end\n if v0~=-32768 && v1~=-32768 && v2~=-32768\n swqrsm.Yn = 2*swqrsm.Yn1 - swqrsm.Yn2 + v0 - 2*v1 + v2;\n end\n dy = fix((swqrsm.Yn - swqrsm.Yn1) / swqrsm.LP2n);\t%\t/* lowpass derivative of input */\n swqrsm.lt_tt=swqrsm.lt_tt+1;\n swqrsm.et = fix(sqrt(swqrsm.lfsc +dy*dy)); % /* length transform */\n id = mod(swqrsm.lt_tt,swqrsm.BUFLN);\n if id == 0\n id = swqrsm.BUFLN;\n end\n swqrsm.ebuf(id) = swqrsm.et;\n id2 = mod(swqrsm.lt_tt-swqrsm.LTwindow,swqrsm.BUFLN);\n if id2 == 0\n id2 = swqrsm.BUFLN;\n end\n swqrsm.aet = swqrsm.aet + (swqrsm.et - swqrsm.ebuf(id2));\n swqrsm.lbuf(id) = swqrsm.aet;\n % \t/* swqrsm.lbuf contains the average of the length-transformed samples over\n % \t the interval from tt-swqrsm.LTwindow+1 to tt */\n end\n \n id3 = mod(t,swqrsm.BUFLN);\n if id3 == 0\n id3 = swqrsm.BUFLN;\n end\n swqrsm.lt_data = swqrsm.lbuf(id3);\nend", "meta": {"author": "cliffordlab", "repo": "PhysioNet-Cardiovascular-Signal-Toolbox", "sha": "eec46e75e0b95c379ecb68cb0ebee0c4c9f54605", "save_path": "github-repos/MATLAB/cliffordlab-PhysioNet-Cardiovascular-Signal-Toolbox", "path": "github-repos/MATLAB/cliffordlab-PhysioNet-Cardiovascular-Signal-Toolbox/PhysioNet-Cardiovascular-Signal-Toolbox-eec46e75e0b95c379ecb68cb0ebee0c4c9f54605/Tools/ECG_Analysis_Tools/PeakDetection_SQI/wqrsm_fast.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.2909808539178129, "lm_q1q2_score": 0.1658162111158212}} {"text": "%sim_lcmrawbasis.m\n%Jamie Near, McGill University 2014.\n%Modified (greatly simplified) for new FID-A spin system definitions, 2018.\n%\n% USAGE:\n% [RF,out]=sim_lcmrawbasis(n,sw,Bfield,linewidth,metab,tau1,tau2,addref,makeraw,seq)\n% \n% DESCRIPTION:\n% Generate an LCModel .RAW file to be used as an individual metabolite basis \n% spectrum in an LCModel basis set. The relevant characteristics of the\n% acquisition can be specified (pulse sequence, number of points, spectral\n% width, etc)\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% tau1 = first echo time in [ms] (if seq='st' or 'l', tau1 = TE)\n% tau2 = second echo time in [ms]. (Used in Press, but not used in SE or LASER.\n% If seq='st', tau2=TM).\n% addref = add reference at 0ppm (for use in LCModel makebasis) ['y' or 'n']\n% makeraw = make output file for lcmodel ['y' or 'n']\n% seq = pulse sequence ['se' for Spin Echo, 'p' for Press, 'st' for Steam, or 'l' for LASER]\n% metab = one of the following choices\n% 'H2O' = Water\n% 'Ala' = Alanine\n% 'Asp' = Aspartate\n% 'PCh' = PhosphoCholine\n% 'Cr' = Creatine\n% 'PCr' = PhosphoCreatine\n% 'GABA' = Gamma-aminobutyric acid (kaiser)\n% 'Gln' = Glutamine\n% 'Glu' = Glutamate\n% 'GSH' = Glutathione\n% 'Gly' = Glycine\n% 'Ins' = Myo-inositol\n% 'Lac' = Lactate\n% 'NAA' = N-acetyl aspartate\n% 'Scyllo' = Scyllo-inositol\n% 'Tau' = Taurine\n% 'Asc' = Ascorbate (Vitamin C)\n% 'bHB' = beta-Hydroxybutyrate\n% 'bHG' = beta-Hydroxyglutarate\n% 'Glc' = Glucose\n% 'NAAG' = N-acetyl aspartyl glutamate\n% 'GPC' = Glycero-phosphocholine\n% 'PE' = Phosphoryl ethanolamine\n% 'Ser' = Serine\n%\n% OUTPUTS:\n% RF = not used.\n% out = Simulated basis spectrum in FID-A structure format. \n\nfunction [RF,out]=sim_lcmrawbasis(n,sw,Bfield,linewidth,metab,tau1,tau2,addref,makeraw,seq)\n\n\nload('spinSystems.mat');\n\neval(['sys=sys' metab ';']);\nspins=0;\nfor k=1:length(sys)\n spins=spins+length(sys(k).shifts);\nend\ndisp(['simulating metabolite ' metab ' with ' num2str(spins) ' spins... Please Wait...']);\nswitch seq\n case 'se'\n out = sim_spinecho(n,sw,Bfield,linewidth,sys,tau1);\n case 'p'\n out = sim_press(n,sw,Bfield,linewidth,sys,tau1,tau2);\n case 'st'\n out = sim_steam(n,sw,Bfield,linewidth,sys,tau1,tau2);\n case 'l'\n out = sim_laser(n,sw,Bfield,linewidth,sys,tau1);\n otherwise\n disp(['ERROR: Sequence ' seq 'not recognized!!!']);\nend\n\nif addref=='y'||addref=='Y'\n addref=1;\nelseif addref=='n'||addref=='N'\n addref=0;\nend\n\nif addref\n sysRef.J=0;\n sysRef.shifts=0;\n sysRef.name='Ref_0ppm';\n sysRef.scaleFactor=1;\n switch seq\n case 'se'\n ref = sim_spinecho(n,sw,Bfield,linewidth,sysRef,tau1);\n case 'p'\n ref = sim_press(n,sw,Bfield,linewidth,sysRef,tau1,tau2);\n case 'st'\n ref = sim_steam(n,sw,Bfield,linewidth,sysRef,tau1,tau2);\n case 'l'\n ref = sim_laser(n,sw,Bfield,linewidth,sysRef,tau1);\n otherwise\n disp(['ERROR: Sequence ' seq 'not recognized!!!']);\n end\n out=op_addScans(out,ref);\nend\n\nif makeraw=='y'||makeraw=='Y'\n makeraw=1;\nelseif makeraw=='n'||makeraw=='N'\n makeraw=0;\nend\n\nif makeraw\n RF=io_writelcmraw(out,[metab '.RAW'],metab);\nelse\n RF=[];\nend\n\n\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/simulationTools/sim_lcmrawbasis.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665999540697, "lm_q2_score": 0.2782567996876011, "lm_q1q2_score": 0.16491351138495117}} {"text": "%% Example: Carbon Ion Treatment Plan\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 carbon ion dose calculation plan including variable RBE optimization\n% (iii) how to inversely optimize the pencil beam intensities based on the\n% RBE-weighted dose\n% (iv) how to inversely optimize the pencil beam intensities based on the\n% biological effect\n% (v) how to change the tissues' radiobiological characteristics\n% (vi) how to recalculated the dose considering 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 liver\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('LIVER.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 the most\n% important cornerstones of your treatment plan.\n%%\n% First of all, we need to define what kind of radiation modality we would\n% like to use. Possible values are photons, protons or carbon. In this\n% example we would like to use carbon ions for treatment planning. Next, we\n% need to define a treatment machine to correctly load the corresponding \n% base data. matRad features generic base data in the file\n% 'carbon_Generic.mat'; consequently the machine has to be set accordingly\npln.radiationMode = 'carbon'; \npln.machine = 'Generic';\n\n%%\n% Define the flavor of biological optimization for treatment planning along\n% with the quantity that should be used for optimization. Possible values \n% are (none: physical optimization; const_RBExD: constant RBE of 1.1; \n% LEMIV_effect: effect-based optimization; LEMIV_RBExD: optimization of \n% RBE-weighted dose. As we use carbon ions, we decide to use base data from \n% the local effect model IV and want to optimize the RBE-weighted dose. \n% Therefore we set bioOptimization to LEMIV_RBExD\npln.propOpt.bioOptimization = 'LEMIV_RBExD'; \n\n%%\n% The remaining plan parameters are set like in the previous example files\npln.numOfFractions = 30;\npln.propStf.gantryAngles = 315;\npln.propStf.couchAngles = 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%%\n% Let's have a closer look on the stf.ray sub-structure which contains the \n% actual beam/ray geometry information. For illustration purposes we want \n% to show the last ray. Besides geometrical information about the position \n% and orientation of the ray, we can also find pencil beam information. If \n% the ray coincides with the target, pencil beams were defined along the \n% ray from target entry to target exit. \ndisplay(stf.ray(end));\n\n%%\n% Here are the energies selected on the last ray: \ndisplay(stf.ray(end).energy);\n\n%% Dose Calculation\ndij = matRad_calcParticleDose(ct,stf,pln,cst);\n\n%% Inverse Optimization for IMPT based on RBE-weighted dose\n% The goal of the fluence optimization is to find a set of bixel/spot \n% weights which yield the best possible dose distribution according to the\n% clinical objectives and constraints underlying the radiation treatment.\nresultGUI = matRad_fluenceOptimization(dij,cst,pln);\n\n%% Plot the Resulting Dose Slice\n% Let's plot the transversal iso-center dose slice\nslice = round(pln.propStf.isoCenter(3)./ct.resolution.z);\nfigure,\nimagesc(resultGUI.RBExDose (:,:,slice)),colorbar, colormap(jet);\n\n%% Inverse Optimization for IMPT based on biological effect\n% To perform a dose optimization for carbon ions we can also use the\n% biological effect instead of the RBE-weighted dose. Therefore we have to\n% change the optimization mode and restart the optimization\npln.propOpt.bioOptimization = 'LEMIV_effect'; \nresultGUI_effect = matRad_fluenceOptimization(dij,cst,pln);\n\n%% Visualize differences\n% Through optimzation based on the biological effect we obtain a slightly\n% different dose distribution as visualized by the following dose\n% difference map\nfigure;\nimagesc(resultGUI.RBExDose (:,:,slice)-resultGUI_effect.RBExDose(:,:,slice));\ncolorbar;\ncolormap(jet);\n\n%% Change Radiosensitivity\n% The previous treatment plan was optimized using an photon alpha-beta \n% ratio of 2 for all tissues. Now, Let's change the radiosensitivity by \n% adapting alphaX. This will change the photon alpha-beta ratio\n% from 2 to 10.\nfor i = 1:size(cst,1)\n cst{i,5}.alphaX = 0.5;\n cst{i,5}.TissueClass = 2;\nend\n\n%% Recalculate Plan\n% Let's use the existing optimized pencil beam weights and recalculate the RBE weighted dose\nresultGUI_tissue = matRad_calcDoseDirect(ct,stf,pln,cst,resultGUI.w);\n\n%% Result Comparison\n% Let's compare the new recalculation against the optimization result.\nplane = 3;\ndoseWindow = [0 max([resultGUI_effect.RBExDose(:); resultGUI_tissue.RBExDose(:)])];\n\nfigure,\nmatRad_plotSliceWrapper(gca,ct,cst,1,resultGUI_effect.RBExDose,plane,slice,[],[],colorcube,[],doseWindow,[]);\ntitle('original plan')\nfigure,\nmatRad_plotSliceWrapper(gca,ct,cst,1,resultGUI_tissue.RBExDose,plane,slice,[],[],colorcube,[],doseWindow,[]);\ntitle('manipulated plan')\n%% \n% At this point we would like to see the absolute difference of the original optimization and the \n% recalculation. \nabsDiffCube = resultGUI_effect.RBExDose-resultGUI_tissue.RBExDose;\nfigure,\nmatRad_plotSliceWrapper(gca,ct,cst,1,absDiffCube,plane,slice,[],[],colorcube);\ntitle('absolute difference')\n%%\n% Plot both doses with absolute difference and gamma analysis\n[gammaCube,gammaPassRate,hfigure]=matRad_compareDose(resultGUI_effect.RBExDose, resultGUI.RBExDose, ct, cst,[1 1 1],'on');\n\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/examples/matRad_example7_carbon.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381372136563, "lm_q2_score": 0.3007455664065234, "lm_q1q2_score": 0.16442907075236857}} {"text": "function [sourcemodel, cfg] = ft_prepare_leadfield(cfg, data)\n\n% FT_PREPARE_LEADFIELD computes the forward model for many dipole locations\n% on a regular 2D or 3D sourcemodel and stores it for efficient inverse modelling\n%\n% Use as\n% [sourcemodel] = ft_prepare_leadfield(cfg, data)\n%\n% It is necessary to input the data on which you want to perform the\n% inverse computations, since that data generally contain the gradiometer\n% information and information about the channels that should be included in\n% the forward model computation. The data structure can be either obtained\n% from FT_PREPROCESSING, FT_FREQANALYSIS or FT_TIMELOCKANALYSIS. If the data is empty,\n% all channels will be included in the forward model.\n%\n% The configuration should contain\n% cfg.channel = Nx1 cell-array with selection of channels (default = 'all'),\n% see FT_CHANNELSELECTION for details\n%\n% The positions of the sources can be specified as a regular 3-D\n% sourcemodel that is aligned with the axes of the head coordinate system\n% cfg.xgrid = vector (e.g. -20:1:20) or 'auto' (default = 'auto')\n% cfg.ygrid = vector (e.g. -20:1:20) or 'auto' (default = 'auto')\n% cfg.zgrid = vector (e.g. 0:1:20) or 'auto' (default = 'auto')\n% cfg.resolution = number (e.g. 1 cm) for automatic sourcemodel generation\n% Alternatively the position of a few sources at locations of interest can\n% be specified, for example obtained from an anatomical or functional MRI\n% cfg.sourcemodel.pos = N*3 matrix with position of each source\n% cfg.sourcemodel.inside = N*1 vector with boolean value whether sourcemodel point is inside brain (optional)\n% cfg.sourcemodel.dim = [Nx Ny Nz] vector with dimensions in case of 3-D sourcemodel (optional)\n%\n% The volume conduction model of the head should be specified as\n% cfg.headmodel = structure with volume conduction model, see FT_PREPARE_HEADMODEL\n%\n% The EEG or MEG sensor positions can be present in the data or can be specified as\n% cfg.elec = structure with electrode positions or filename, see FT_READ_SENS\n% cfg.grad = structure with gradiometer definition or filename, see FT_READ_SENS\n%\n% Optionally, you can modify the leadfields by reducing the rank (i.e.\n% remove the weakest orientation), or by normalizing each column.\n% cfg.reducerank = 'no', or number (default = 3 for EEG, 2 for MEG)\n% cfg.normalize = 'yes' or 'no' (default = 'no')\n% cfg.normalizeparam = depth normalization parameter (default = 0.5)\n% cfg.backproject = 'yes' or 'no' (default = 'yes') determines when reducerank is applied\n% whether the lower rank leadfield is projected back onto the original\n% linear subspace, or not.\n%\n% Depending on the type of headmodel, some additional options may be\n% specified.\n%\n% For OPENMEEG based headmodels:\n% cfg.openmeeg.batchsize = scalar (default 100e3), number of dipoles\n% for which the leadfield is computed in a\n% single call to the low-level code. Trades off\n% memory efficiency for speed.\n% cfg.openmeeg.dsm = 'no'/'yes', reuse existing DSM if provided\n% cfg.openmeeg.keepdsm = 'no'/'yes', option to retain DSM (no by default)\n% cfg.openmeeg.nonadaptive = 'no'/'yes'\n%\n% For SINGLESHELL based headmodels:\n% cfg.singleshell.batchsize = scalar or 'all' (default 1), number of dipoles\n% for which the leadfield is computed in a\n% single call to the low-level code. Trades off\n% memory efficiency for speed.\n%\n% To facilitate data-handling and distributed computing you can use\n% cfg.inputfile = ...\n% If you specify this option the input data will be read from a *.mat\n% file on disk. This mat files should contain only a single variable named 'data',\n% corresponding to the input structure.\n%\n% See also FT_SOURCEANALYSIS, FT_DIPOLEFITTING, FT_PREPARE_HEADMODEL, FT_PREPARE_SOURCEMODEL\n\n% Undocumented local options:\n% cfg.feedback\n% cfg.sel50p = 'no' (default) or 'yes'\n% cfg.lbex = 'no' (default) or a number that corresponds with the radius\n% cfg.mollify = 'no' (default) or a number that corresponds with the FWHM\n\n% Copyright (C) 2004-2013, 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% these are used by the ft_preamble/ft_postamble function and scripts\nft_revision = '$Id$';\nft_nargin = nargin;\nft_nargout = nargout;\n\n% do the general setup of the function\nft_defaults\nft_preamble init\nft_preamble debug\nft_preamble 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 return\nend\n\n% the data can be passed as input arguments or can be read from disk\nhasdata = exist('data', 'var');\n\nif ~hasdata\n % the data variable will be passed to the prepare_headmodel function below\n % where it would be used for channel selection\n data = [];\nelse\n % check if the input data is valid for this function\n data = ft_checkdata(data);\nend\n\n% check if the input cfg is valid for this function\ncfg = ft_checkconfig(cfg, 'renamed', {'hdmfile', 'headmodel'});\ncfg = ft_checkconfig(cfg, 'renamed', {'vol', 'headmodel'});\ncfg = ft_checkconfig(cfg, 'renamed', {'grid', 'sourcemodel'});\ncfg = ft_checkconfig(cfg, 'renamed', {'om', 'openmeeg'});\ncfg = ft_checkconfig(cfg, 'renamed', {'elecfile', 'elec'});\ncfg = ft_checkconfig(cfg, 'renamed', {'gradfile', 'grad'});\ncfg = ft_checkconfig(cfg, 'renamed', {'optofile', 'opto'});\n\n% set the defaults\ncfg.normalize = ft_getopt(cfg, 'normalize', 'no');\ncfg.normalizeparam = ft_getopt(cfg, 'normalizeparam', 0.5);\ncfg.lbex = ft_getopt(cfg, 'lbex', 'no');\ncfg.sel50p = ft_getopt(cfg, 'sel50p', 'no');\ncfg.feedback = ft_getopt(cfg, 'feedback', 'text');\ncfg.mollify = ft_getopt(cfg, 'mollify', 'no');\ncfg.patchsvd = ft_getopt(cfg, 'patchsvd', 'no');\ncfg.backproject = ft_getopt(cfg, 'backproject', 'yes'); % determines whether after rank reduction the subspace projected leadfield is backprojected onto the original space\n% cfg.reducerank = ft_getopt(cfg, 'reducerank', 'no'); % the default for this depends on EEG/MEG and is set below\n\ncfg = ft_checkconfig(cfg, 'renamed', {'tightgrid', 'tight'}); % this is moved to cfg.sourcemodel.tight by the subsequent createsubcfg\ncfg = ft_checkconfig(cfg, 'renamed', {'sourceunits', 'unit'}); % this is moved to cfg.sourcemodel.unit by the subsequent createsubcfg\n\n% put the low-level options pertaining to the sourcemodel in their own field\ncfg = ft_checkconfig(cfg, 'createsubcfg', {'sourcemodel'});\n% move some fields from cfg.sourcemodel back to the top-level configuration\ncfg = ft_checkconfig(cfg, 'createtopcfg', {'sourcemodel'});\n\n% this code expects the inside to be represented as a logical array\ncfg.sourcemodel = ft_checkconfig(cfg.sourcemodel, 'renamed', {'pnt' 'pos'});\ncfg = ft_checkconfig(cfg, 'inside2logical', 'yes');\n\nif strcmp(cfg.sel50p, 'yes') && strcmp(cfg.lbex, 'yes')\n ft_error('subspace projection with either lbex or sel50p is mutually exclusive');\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% collect and preprocess the electrodes/gradiometer and head model\n[headmodel, sens, cfg] = prepare_headmodel(cfg, data);\n\n% set the default for reducing the rank of the leadfields\nif ft_senstype(sens, 'eeg')\n cfg.reducerank = ft_getopt(cfg, 'reducerank', 3);\nelse\n cfg.reducerank = ft_getopt(cfg, 'reducerank', 2);\nend\n\n% construct the sourcemodel for which the leadfield will be computed\ntmpcfg = keepfields(cfg, {'sourcemodel', 'mri', 'headshape', 'symmetry', 'smooth', 'threshold', 'spheremesh', 'inwardshift', 'xgrid' 'ygrid', 'zgrid', 'resolution', 'tight', 'warpmni', 'template', 'showcallinfo'});\ntmpcfg.headmodel = headmodel;\nif ft_senstype(sens, 'eeg')\n tmpcfg.elec = sens;\nelseif ft_senstype(sens, 'meg')\n tmpcfg.grad = sens;\nend\nsourcemodel = ft_prepare_sourcemodel(tmpcfg);\n\n% check whether units are equal (NOTE: this was previously not required,\n% this check can be removed if the underlying bug is resolved. See\n% http://bugzilla.fieldtriptoolbox.org/show_bug.cgi?id=2387\nif ~isfield(headmodel, 'unit') || ~isfield(sourcemodel, 'unit') || ~isfield(sens, 'unit')\n ft_warning('cannot determine the units of all geometric objects required for leadfield computation (headmodel, sourcemodel, sensor configuration). THIS CAN LEAD TO WRONG RESULTS! (refer to http://bugzilla.fieldtriptoolbox.org/show_bug.cgi?id=2387)');\nelse\n if ~strcmp(headmodel.unit, sourcemodel.unit) || ~strcmp(sourcemodel.unit, sens.unit)\n ft_error('geometric objects (headmodel, sourcemodel, sensor configuration) are not expressed in the same units (this used to be allowed, and will be again in the future, but for now there is a bug which prevents a correct leadfield from being computed; see http://bugzilla.fieldtriptoolbox.org/show_bug.cgi?id=2387)');\n end\nend\n\n% find the indices of all sourcemodel points that are inside the brain\ninsideindx = find(sourcemodel.inside);\n\nif ft_headmodeltype(headmodel, 'openmeeg')\n \n ft_hastoolbox('openmeeg', 1); % add to path (if not yet on path)\n \n % repeated system calls to the openmeeg executable makes it rather slow\n % calling it once is much more efficient\n fprintf('calculating leadfield for all positions at once, this may take a while...\\n');\n\n if(~isfield(cfg,'openmeeg'))\n cfg.openmeeg = [];\n end\n batchsize = ft_getopt(cfg.openmeeg, 'batchsize',100e3); % number of voxels per DSM batch; set to e.g. 1000 if not much RAM available\n dsm = ft_getopt(cfg.openmeeg, 'dsm'); % reuse existing DSM if provided\n keepdsm = ft_getopt(cfg.openmeeg, 'keepdsm', 'no'); % retain DSM\n nonadaptive = ft_getopt(cfg.openmeeg, 'nonadaptive', 'no');\n\n ndip = length(insideindx);\n numchunks = ceil(ndip/batchsize);\n if(numchunks > 1)\n if istrue(keepdsm)\n ft_warning('Keeping DSM output not supported when the computation is split into batches')\n end\n keepdsm = false;\n end\n\n try\n % DSM computation is computationally intensive:\n % As it can be reused with same voxel sourcemodel (i.e. if voxels are defined in\n % MRI coordinates rather than MEG coordinates), optionally save result.\n % Dense voxel grids may require several gigabytes of RAM, so optionally\n % split into smaller batches\n\n [h2sens,ds2sens] = ft_sensinterp_openmeeg(sourcemodel.pos(insideindx,:), headmodel, sens);\n\n % use pre-existing DSM if present\n if(~isempty(dsm))\n lf = ds2sens + h2sens*headmodel.mat*dsm;\n else\n lf = zeros(size(ds2sens)); % pre-allocate Msensors x Nvoxels\n\n for ii = 1:numchunks\n % select sourcemodel positions for this batch\n diprange = (((ii-1)*batchsize + 1):(min((ii)*batchsize,ndip)));\n % remap with 3 orientations per position\n diprangeori = [((ii-1)*3*batchsize + 1):(min((ii)*3*batchsize,3*ndip))];\n dsm = ft_sysmat_openmeeg(sourcemodel.pos(insideindx(diprange),:), headmodel, sens, nonadaptive);\n lf(:,diprangeori) = ds2sens(:,diprangeori) + h2sens*headmodel.mat*dsm;\n\n if istrue(keepdsm)\n % retain DSM in cfg if desired\n cfg.openmeeg.dsm = dsm;\n end\n\n dipindx = insideindx(diprange);\n end\n end\n catch\n me = lasterror;\n rethrow(me);\n end\n\n % apply montage, if applicable\n if isfield(sens, 'tra')\n lf = sens.tra * lf;\n end\n\n % lead field computation already done, but pass to ft_compute_leadfield so that\n % any post-computation options can be applied (e.g., normalization, etc.)\n lf = ft_compute_leadfield(sourcemodel.pos(diprange,:), sens, headmodel, 'lf', lf, 'reducerank', cfg.reducerank, 'normalize', cfg.normalize, 'normalizeparam', cfg.normalizeparam, 'backproject', cfg.backproject);\n\n % reshape result into sourcemodel.leadfield cell-array\n for i=1:ndip\n sourcemodel.leadfield{insideindx(i)} = lf(:,3*(i-1) + [1:3]);\n end\n clear lf\n\nelseif ft_headmodeltype(headmodel, 'singleshell')\n cfg.singleshell = ft_getopt(cfg, 'singleshell', []);\n batchsize = ft_getopt(cfg.singleshell, 'batchsize', 1);\n if ischar(batchsize) && strcmp(batchsize, 'all')\n batchsize = length(insideindx);\n end\n\n dippos = sourcemodel.pos(insideindx,:);\n ndip = length(insideindx);\n numchunks = ceil(ndip/batchsize);\n\n ft_progress('init', cfg.feedback, 'computing leadfield');\n for k = 1:numchunks\n ft_progress(k/numchunks, 'computing leadfield %d/%d\\n', k, numchunks);\n diprange = (((k-1)*batchsize + 1):(min(k*batchsize,ndip)));\n tmp = ft_compute_leadfield(dippos(diprange,:), sens, headmodel, 'reducerank', cfg.reducerank, 'normalize', cfg.normalize, 'normalizeparam', cfg.normalizeparam, 'backproject', cfg.backproject);\n for i=1:length(diprange)\n thisindx = insideindx(diprange(i));\n if istrue(cfg.backproject)\n sourcemodel.leadfield{thisindx} = tmp(:,(i-1)*3+(1:3));\n else\n sourcemodel.leadfield{thisindx} = tmp(:,(i-1)*cfg.reducerank+(1:cfg.reducerank));\n end\n\n if isfield(cfg, 'sourcemodel') && isfield(cfg.sourcemodel, 'mom')\n % multiply with the normalized dipole moment to get the leadfield in the desired orientation\n sourcemodel.leadfield{thisindx} = sourcemodel.leadfield{thisindx} * sourcemodel.mom(:,thisindx);\n end\n end\n end\n ft_progress('close');\n\nelse\n ft_progress('init', cfg.feedback, 'computing leadfield');\n for i=1:length(insideindx)\n % compute the leadfield on all sourcemodel positions inside the brain\n ft_progress(i/length(insideindx), 'computing leadfield %d/%d\\n', i, length(insideindx));\n thisindx = insideindx(i);\n sourcemodel.leadfield{thisindx} = ft_compute_leadfield(sourcemodel.pos(thisindx,:), sens, headmodel, 'reducerank', cfg.reducerank, 'normalize', cfg.normalize, 'normalizeparam', cfg.normalizeparam, 'backproject', cfg.backproject);\n\n if isfield(cfg, 'sourcemodel') && isfield(cfg.sourcemodel, 'mom')\n % multiply with the normalized dipole moment to get the leadfield in the desired orientation\n sourcemodel.leadfield{thisindx} = sourcemodel.leadfield{thisindx} * sourcemodel.mom(:,thisindx);\n end\n end % for all sourcemodel locations inside the brain\n ft_progress('close');\nend\n\n% represent the leadfield for positions outside the brain as empty array\nsourcemodel.leadfield(~sourcemodel.inside) = {[]};\n\n% add the label of the channels\nsourcemodel.label = sens.label;\nsourcemodel.leadfielddimord = '{pos}_chan_ori';\n\n% mollify the leadfields\nif ~strcmp(cfg.mollify, 'no')\n sourcemodel = mollify(cfg, sourcemodel);\nend\n\n% combine leadfields in patches and do an SVD on them\nif ~strcmp(cfg.patchsvd, 'no')\n sourcemodel = patchsvd(cfg, sourcemodel);\nend\n\n% compute the 50 percent channel selection subspace projection\nif ~strcmp(cfg.sel50p, 'no')\n sourcemodel = sel50p(cfg, sourcemodel, sens);\nend\n\n% compute the local basis function expansion (LBEX) subspace projection\nif ~strcmp(cfg.lbex, 'no')\n sourcemodel = lbex(cfg, sourcemodel);\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\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 sourcemodel\nft_postamble history sourcemodel\nft_postamble savevar sourcemodel\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_prepare_leadfield.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.554470450236115, "lm_q2_score": 0.2942149659744614, "lm_q1q2_score": 0.16313350465006285}} {"text": "function [im_th,TOAref,trgt,ijdim_ref,ul,bbox,zen,azi,zc,B1Satu,B2Satu,B3Satu,resolu]=nd2toarbt(path_top,filename)\n% convert DNs to TOA ref and BT\n% Revisions:\n% Add Landsat 9 (Shi 2/17/2022)\n% Cannot use the GRIDobj to read our band, because it may result in Nan data.\n% (Shi 2/26/2018)\n% Added a target image based on blue band, which will be helpfull to\n% resample and reproject the auxiliary data. (Shi 2/16/2018)\n% Use REF vs. DN instead of RAD vs. DN (Zhe 06/20/2013)\n% Combined the Earth-Sun distance table into the function (Zhe 04/09/2013)\n% Process Landsat 8 DN values (Zhe 04/04/2013)\n% Proces the new metadata for Landsat TM/ETM+ images (Zhe 09/28/2012)\n% Fixed bugs caused by earth-sun distance table (Zhe 01/15/2012)\n%\n% [im_th,TOAref,ijdim_ref,ul,zen,azi,zc,B1Satu,B2Satu,B3Satu,resolu]=nd2toarbt(filename)\n% Where:\n% Inputs:\n% filename='L*MTL.txt';\n% Outputs:\n% 1) im_th = Brightness Temperature (BT)\n% 2) TOAref = Top Of Atmoshpere (TOA) reflectance\n% 3) trgt = Target Grid Object\n% 4) ijdim = [nrows,ncols]; % dimension of optical bands\n% 5) ul = [upperleft_mapx upperleft_mapy];\n% 6) zen = solar zenith angle (degrees);\n% 7) azi = solar azimuth angle (degrees);\n% 8) zc = Zone Number\n% 9,10,11) Saturation (true) in the Visible bands\n% 12) resolution of Fmask results\n\n% % % fprintf('Read in header information & TIF images\\n');\n[Lmax,Lmin,Qcalmax,Qcalmin,Refmax,Refmin,ijdim_ref,ijdim_thm,reso_ref,...\n reso_thm,ul,bbox,zen,azi,zc,Lnum,doy]=lndhdrread(path_top,filename);\n\n\n% earth-sun distance see G. Chander et al. RSE 113 (2009) 893-903\nTab_ES_Dist = [\n 1 0.98331\n 2 0.98330\n 3 0.98330\n 4 0.98330\n 5 0.98330\n 6 0.98332\n 7 0.98333\n 8 0.98335\n 9 0.98338\n 10 0.98341\n 11 0.98345\n 12 0.98349\n 13 0.98354\n 14 0.98359\n 15 0.98365\n 16 0.98371\n 17 0.98378\n 18 0.98385\n 19 0.98393\n 20 0.98401\n 21 0.98410\n 22 0.98419\n 23 0.98428\n 24 0.98439\n 25 0.98449\n 26 0.98460\n 27 0.98472\n 28 0.98484\n 29 0.98496\n 30 0.98509\n 31 0.98523\n 32 0.98536\n 33 0.98551\n 34 0.98565\n 35 0.98580\n 36 0.98596\n 37 0.98612\n 38 0.98628\n 39 0.98645\n 40 0.98662\n 41 0.98680\n 42 0.98698\n 43 0.98717\n 44 0.98735\n 45 0.98755\n 46 0.98774\n 47 0.98794\n 48 0.98814\n 49 0.98835\n 50 0.98856\n 51 0.98877\n 52 0.98899\n 53 0.98921\n 54 0.98944\n 55 0.98966\n 56 0.98989\n 57 0.99012\n 58 0.99036\n 59 0.99060\n 60 0.99084\n 61 0.99108\n 62 0.99133\n 63 0.99158\n 64 0.99183\n 65 0.99208\n 66 0.99234\n 67 0.99260\n 68 0.99286\n 69 0.99312\n 70 0.99339\n 71 0.99365\n 72 0.99392\n 73 0.99419\n 74 0.99446\n 75 0.99474\n 76 0.99501\n 77 0.99529\n 78 0.99556\n 79 0.99584\n 80 0.99612\n 81 0.99640\n 82 0.99669\n 83 0.99697\n 84 0.99725\n 85 0.99754\n 86 0.99782\n 87 0.99811\n 88 0.99840\n 89 0.99868\n 90 0.99897\n 91 0.99926\n 92 0.99954\n 93 0.99983\n 94 1.00012\n 95 1.00041\n 96 1.00069\n 97 1.00098\n 98 1.00127\n 99 1.00155\n 100 1.00184\n 101 1.00212\n 102 1.00240\n 103 1.00269\n 104 1.00297\n 105 1.00325\n 106 1.00353\n 107 1.00381\n 108 1.00409\n 109 1.00437\n 110 1.00464\n 111 1.00492\n 112 1.00519\n 113 1.00546\n 114 1.00573\n 115 1.00600\n 116 1.00626\n 117 1.00653\n 118 1.00679\n 119 1.00705\n 120 1.00731\n 121 1.00756\n 122 1.00781\n 123 1.00806\n 124 1.00831\n 125 1.00856\n 126 1.00880\n 127 1.00904\n 128 1.00928\n 129 1.00952\n 130 1.00975\n 131 1.00998\n 132 1.01020\n 133 1.01043\n 134 1.01065\n 135 1.01087\n 136 1.01108\n 137 1.01129\n 138 1.01150\n 139 1.01170\n 140 1.01191\n 141 1.01210\n 142 1.01230\n 143 1.01249\n 144 1.01267\n 145 1.01286\n 146 1.01304\n 147 1.01321\n 148 1.01338\n 149 1.01355\n 150 1.01371\n 151 1.01387\n 152 1.01403\n 153 1.01418\n 154 1.01433\n 155 1.01447\n 156 1.01461\n 157 1.01475\n 158 1.01488\n 159 1.01500\n 160 1.01513\n 161 1.01524\n 162 1.01536\n 163 1.01547\n 164 1.01557\n 165 1.01567\n 166 1.01577\n 167 1.01586\n 168 1.01595\n 169 1.01603\n 170 1.01610\n 171 1.01618\n 172 1.01625\n 173 1.01631\n 174 1.01637\n 175 1.01642\n 176 1.01647\n 177 1.01652\n 178 1.01656\n 179 1.01659\n 180 1.01662\n 181 1.01665\n 182 1.01667\n 183 1.01668\n 184 1.01670\n 185 1.01670\n 186 1.01670\n 187 1.01670\n 188 1.01669\n 189 1.01668\n 190 1.01666\n 191 1.01664\n 192 1.01661\n 193 1.01658\n 194 1.01655\n 195 1.01650\n 196 1.01646\n 197 1.01641\n 198 1.01635\n 199 1.01629\n 200 1.01623\n 201 1.01616\n 202 1.01609\n 203 1.01601\n 204 1.01592\n 205 1.01584\n 206 1.01575\n 207 1.01565\n 208 1.01555\n 209 1.01544\n 210 1.01533\n 211 1.01522\n 212 1.01510\n 213 1.01497\n 214 1.01485\n 215 1.01471\n 216 1.01458\n 217 1.01444\n 218 1.01429\n 219 1.01414\n 220 1.01399\n 221 1.01383\n 222 1.01367\n 223 1.01351\n 224 1.01334\n 225 1.01317\n 226 1.01299\n 227 1.01281\n 228 1.01263\n 229 1.01244\n 230 1.01225\n 231 1.01205\n 232 1.01186\n 233 1.01165\n 234 1.01145\n 235 1.01124\n 236 1.01103\n 237 1.01081\n 238 1.01060\n 239 1.01037\n 240 1.01015\n 241 1.00992\n 242 1.00969\n 243 1.00946\n 244 1.00922\n 245 1.00898\n 246 1.00874\n 247 1.00850\n 248 1.00825\n 249 1.00800\n 250 1.00775\n 251 1.00750\n 252 1.00724\n 253 1.00698\n 254 1.00672\n 255 1.00646\n 256 1.00620\n 257 1.00593\n 258 1.00566\n 259 1.00539\n 260 1.00512\n 261 1.00485\n 262 1.00457\n 263 1.00430\n 264 1.00402\n 265 1.00374\n 266 1.00346\n 267 1.00318\n 268 1.00290\n 269 1.00262\n 270 1.00234\n 271 1.00205\n 272 1.00177\n 273 1.00148\n 274 1.00119\n 275 1.00091\n 276 1.00062\n 277 1.00033\n 278 1.00005\n 279 0.99976\n 280 0.99947\n 281 0.99918\n 282 0.99890\n 283 0.99861\n 284 0.99832\n 285 0.99804\n 286 0.99775\n 287 0.99747\n 288 0.99718\n 289 0.99690\n 290 0.99662\n 291 0.99634\n 292 0.99605\n 293 0.99577\n 294 0.99550\n 295 0.99522\n 296 0.99494\n 297 0.99467\n 298 0.99440\n 299 0.99412\n 300 0.99385\n 301 0.99359\n 302 0.99332\n 303 0.99306\n 304 0.99279\n 305 0.99253\n 306 0.99228\n 307 0.99202\n 308 0.99177\n 309 0.99152\n 310 0.99127\n 311 0.99102\n 312 0.99078\n 313 0.99054\n 314 0.99030\n 315 0.99007\n 316 0.98983\n 317 0.98961\n 318 0.98938\n 319 0.98916\n 320 0.98894\n 321 0.98872\n 322 0.98851\n 323 0.98830\n 324 0.98809\n 325 0.98789\n 326 0.98769\n 327 0.98750\n 328 0.98731\n 329 0.98712\n 330 0.98694\n 331 0.98676\n 332 0.98658\n 333 0.98641\n 334 0.98624\n 335 0.98608\n 336 0.98592\n 337 0.98577\n 338 0.98562\n 339 0.98547\n 340 0.98533\n 341 0.98519\n 342 0.98506\n 343 0.98493\n 344 0.98481\n 345 0.98469\n 346 0.98457\n 347 0.98446\n 348 0.98436\n 349 0.98426\n 350 0.98416\n 351 0.98407\n 352 0.98399\n 353 0.98391\n 354 0.98383\n 355 0.98376\n 356 0.98370\n 357 0.98363\n 358 0.98358\n 359 0.98353\n 360 0.98348\n 361 0.98344\n 362 0.98340\n 363 0.98337\n 364 0.98335\n 365 0.98333\n 366 0.98331];\n\nif Lnum >= 4 && Lnum <= 7\n % LPGS Upper lef corner alignment (see Landsat handbook for detail)\n ul(1)=ul(1)-15;\n ul(2)=ul(2)+15;\n resolu=[reso_ref,reso_ref];\n % Read in all bands\n % Band1\n n_B1=dir(fullfile(path_top,'L*B1*'));\n if isempty(n_B1)\n n_B1=dir(fullfile(path_top,'L*b1*'));\n end\n im_B1=single(imread(fullfile(path_top,n_B1.name)));\n % Band2\n % Also used to be target or referenced image when resampling and reprojecting to the image extent and resolution.\n n_B2=dir(fullfile(path_top,'L*B2*'));\n if isempty(n_B2)\n n_B2=dir(fullfile(path_top,'L*b2*'));\n end\n im_B2=single(imread(fullfile(path_top,n_B2.name)));\n trgt = GRIDobj(fullfile(path_top,n_B2.name));\n% im_B2=single(trgt.Z);\n trgt.Z=[];% remove non-used values to save memory.\n \n % Band3\n n_B3=dir(fullfile(path_top,'L*B3*'));\n if isempty(n_B3)\n n_B3=dir(fullfile(path_top,'L*b3*'));\n end\n im_B3=single(imread(fullfile(path_top,n_B3.name)));\n % Band4\n n_B4=dir(fullfile(path_top,'L*B4*'));\n if isempty(n_B4)\n n_B4=dir(fullfile(path_top,'L*b4*'));\n end\n im_B4=single(imread(fullfile(path_top,n_B4.name)));\n % Band5\n n_B5=dir(fullfile(path_top,'L*B5*'));\n if isempty(n_B5)\n n_B5=dir(fullfile(path_top,'L*b5*'));\n end\n im_B5=single(imread(fullfile(path_top,n_B5.name)));\n % Band6\n if Lnum==7\n n_B6=dir(fullfile(path_top,'L*B6*1*'));\n if isempty(n_B6)\n n_B6=dir(fullfile(path_top,'L*b6*1*'));\n end\n else\n n_B6=dir(fullfile(path_top,'L*B6*'));\n if isempty(n_B6)\n n_B6=dir(fullfile(path_top,'L*b6*'));\n end\n end\n im_th=single(imread(fullfile(path_top,n_B6.name)));\n % check to see whether need to resample thermal band\n if reso_ref~=reso_thm\n % resmaple thermal band\n im_th=pixel2pixv([ul(2),ul(1)],[ul(2),ul(1)],...\n resolu,[reso_thm,reso_thm],...\n im_th,[ijdim_ref(2),ijdim_ref(1)],[ijdim_thm(2),ijdim_thm(1)]);\n end\n % Band7\n n_B7=dir(fullfile(path_top,'L*B7*'));\n if isempty(n_B7)\n n_B7=dir(fullfile(path_top,'L*b7*'));\n end\n im_B7=single(imread(fullfile(path_top,n_B7.name)));\n % only processing pixesl where all bands have values (id_mssing)\n id_missing=im_B1==0|im_B2==0|im_B3==0|im_B4==0|im_B5==0|im_th==0|im_B7==0;\n % find pixels that are saturated in the visible bands\n B1Satu=im_B1==255;\n B2Satu=im_B2==255;\n B3Satu=im_B3==255;\n \n % ND to radiance first\n% % % fprintf('From DNs to TOA ref & BT\\n');\n im_B1=((Lmax(1)-Lmin(1))/(Qcalmax(1)-Qcalmin(1)))*(im_B1-Qcalmin(1))+Lmin(1);\n im_B2=((Lmax(2)-Lmin(2))/(Qcalmax(2)-Qcalmin(2)))*(im_B2-Qcalmin(2))+Lmin(2);\n im_B3=((Lmax(3)-Lmin(3))/(Qcalmax(3)-Qcalmin(3)))*(im_B3-Qcalmin(3))+Lmin(3);\n im_B4=((Lmax(4)-Lmin(4))/(Qcalmax(4)-Qcalmin(4)))*(im_B4-Qcalmin(4))+Lmin(4);\n im_B5=((Lmax(5)-Lmin(5))/(Qcalmax(5)-Qcalmin(5)))*(im_B5-Qcalmin(5))+Lmin(5);\n im_th=((Lmax(6)-Lmin(6))/(Qcalmax(6)-Qcalmin(6)))*(im_th-Qcalmin(6))+Lmin(6);\n im_B7=((Lmax(7)-Lmin(7))/(Qcalmax(7)-Qcalmin(7)))*(im_B7-Qcalmin(7))+Lmin(7);\n \n % Landsat 4, 5, and 7 solar spectral irradiance\n % see G. Chander et al. RSE 113 (2009) 893-903\n esun_L7=[1997.000, 1812.000, 1533.000, 1039.000, 230.800, -1.0, 84.90];\n esun_L5=[1983.0, 1796.0, 1536.0, 1031.0, 220.0, -1.0, 83.44];\n esun_L4=[1983.0, 1795.0, 1539.0, 1028.0, 219.8, -1.0, 83.49];\n \n if Lnum==7\n ESUN=esun_L7;\n elseif Lnum==5\n ESUN=esun_L5;\n elseif Lnum==4\n ESUN=esun_L4;\n end\n \n % earth-sun distance see G. Chander et al. RSE 113 (2009) 893-903 \n dsun_doy = Tab_ES_Dist(doy,2);\n \n % compute TOA reflectances\n % converted from degrees to radiance\n s_zen=deg2rad(zen);\n im_B1=10^4*pi*im_B1*dsun_doy^2/(ESUN(1)*cos(s_zen));\n im_B2=10^4*pi*im_B2*dsun_doy^2/(ESUN(2)*cos(s_zen));\n im_B3=10^4*pi*im_B3*dsun_doy^2/(ESUN(3)*cos(s_zen));\n im_B4=10^4*pi*im_B4*dsun_doy^2/(ESUN(4)*cos(s_zen));\n im_B5=10^4*pi*im_B5*dsun_doy^2/(ESUN(5)*cos(s_zen));\n im_B7=10^4*pi*im_B7*dsun_doy^2/(ESUN(7)*cos(s_zen));\n \n % convert Band6 from radiance to BT\n % fprintf('From Band 6 Radiance to Brightness Temperature\\n');\n % see G. Chander et al. RSE 113 (2009) 893-903\n K1_L4= 671.62;\n K2_L4= 1284.30;\n K1_L5= 607.76;\n K2_L5= 1260.56;\n K1_L7 = 666.09;\n K2_L7 = 1282.71;\n \n if Lnum==7\n K1=K1_L7;\n K2=K2_L7;\n elseif Lnum==5\n K1=K1_L5;\n K2=K2_L5;\n elseif Lnum==4\n K1=K1_L4;\n K2=K2_L4;\n end\n \n im_th=K2./log((K1./im_th)+1);\n % convert from Kelvin to Celcius with 0.01 scale_facor\n im_th=100*(im_th-273.15);\n % get data ready for Fmask\n im_B1(id_missing)=-9999;\n im_B2(id_missing)=-9999;\n im_B3(id_missing)=-9999;\n im_B4(id_missing)=-9999;\n im_B5(id_missing)=-9999;\n im_th(id_missing)=-9999;\n im_B7(id_missing)=-9999;\n clear id_missing;\n TOAref=zeros(ijdim_ref(1),ijdim_ref(2),6,'single');% Band1,2,3,4,5,&7\n TOAref(:,:,1)=im_B1;clear im_B1;\n TOAref(:,:,2)=im_B2;clear im_B2;\n TOAref(:,:,3)=im_B3;clear im_B3;\n TOAref(:,:,4)=im_B4;clear im_B4;\n TOAref(:,:,5)=im_B5;clear im_B5;\n TOAref(:,:,6)=im_B7;clear im_B7;\n \nelseif Lnum == 8 || Lnum == 9\n % LPGS Upper lef corner alignment (see Landsat handbook for detail)\n ul(1)=ul(1)-15;\n ul(2)=ul(2)+15;\n resolu=[reso_ref,reso_ref];\n % Read in all bands\n % Band2\n n_B2=dir(fullfile(path_top,'L*B2*'));\n if isempty(n_B2)\n n_B2=dir(fullfile(path_top,'L*b2*'));\n end\n im_B2=single(imread(fullfile(path_top,n_B2(1).name))); clear n_B2;\n % Band3\n % Also used to be target or referenced image when resampling and reprojecting to the image extent and resolution.\n n_B3=dir(fullfile(path_top,'L*B3*'));\n if isempty(n_B3)\n n_B3=dir(fullfile(path_top,'L*b3*'));\n end\n im_B3=single(imread(fullfile(path_top,n_B3(1).name)));\n trgt = GRIDobj(fullfile(path_top,n_B3.name)); clear n_B3;\n% im_B3=single(trgt.Z);\n trgt.Z=[];% remove non-used values to save memory.\n \n % Band4\n n_B4=dir(fullfile(path_top,'L*B4*'));\n if isempty(n_B4)\n n_B4=dir(fullfile(path_top,'L*b4*'));\n end\n im_B4=single(imread(fullfile(path_top,n_B4(1).name))); clear n_B4;\n % Band5\n n_B5=dir(fullfile(path_top,'L*B5*'));\n if isempty(n_B5)\n n_B5=dir(fullfile(path_top,'L*b5*'));\n end\n im_B5=single(imread(fullfile(path_top,n_B5(1).name))); clear n_B5;\n % Band6\n n_B6=dir(fullfile(path_top,'L*B6*'));\n if isempty(n_B6)\n n_B6=dir(fullfile(path_top,'L*b6*'));\n end\n im_B6=single(imread(fullfile(path_top,n_B6(1).name))); clear n_B6;\n % Band7\n n_B7=dir(fullfile(path_top,'L*B7*'));\n if isempty(n_B7)\n n_B7=dir(fullfile(path_top,'L*b7*'));\n end\n im_B7=single(imread(fullfile(path_top,n_B7(1).name))); clear n_B7;\n % Band9\n n_B9=dir(fullfile(path_top,'L*B9.*'));\n if isempty(n_B9)\n n_B9=dir(fullfile(path_top,'L*b9.*'));\n end\n im_B9=single(imread(fullfile(path_top,n_B9(1).name))); clear n_B9;\n % Band10\n n_B10=dir(fullfile(path_top,'L*B10*'));\n if isempty(n_B10)\n n_B10=dir(fullfile(path_top,'L*b10*'));\n end\n im_B10=single(imread(fullfile(path_top,n_B10(1).name))); clear n_B10 path_top;\n\n % check to see whether need to resample thermal band\n if reso_ref~=reso_thm\n % resmaple thermal band\n im_B10=pixel2pixv([ul(2),ul(1)],[ul(2),ul(1)],...\n resolu,[reso_thm,reso_thm],...\n im_B10,[ijdim_ref(2),ijdim_ref(1)],[ijdim_thm(2),ijdim_thm(1)]);\n end\n \n % only processing pixesl where all bands have values (id_mssing)\n id_missing=im_B2==0|im_B3==0|im_B4==0|im_B5==0|im_B6==0|im_B7==0|im_B9==0|im_B10==0;\n % find pixels that are saturated in the visible bands\n B1Satu=im_B2==65535;\n B2Satu=im_B3==65535;\n B3Satu=im_B4==65535;\n \n % ND to TOA reflectance with 0.0001 scale_facor\n% % % fprintf('From DNs to TOA ref & BT\\n');\n im_B2=((Refmax(1)-Refmin(1))/(Qcalmax(1)-Qcalmin(1)))*(im_B2-Qcalmin(1))+Refmin(1);\n im_B3=((Refmax(2)-Refmin(2))/(Qcalmax(2)-Qcalmin(2)))*(im_B3-Qcalmin(2))+Refmin(2);\n im_B4=((Refmax(3)-Refmin(3))/(Qcalmax(3)-Qcalmin(3)))*(im_B4-Qcalmin(3))+Refmin(3);\n im_B5=((Refmax(4)-Refmin(4))/(Qcalmax(4)-Qcalmin(4)))*(im_B5-Qcalmin(4))+Refmin(4);\n im_B6=((Refmax(5)-Refmin(5))/(Qcalmax(5)-Qcalmin(5)))*(im_B6-Qcalmin(5))+Refmin(5);\n im_B7=((Refmax(6)-Refmin(6))/(Qcalmax(6)-Qcalmin(6)))*(im_B7-Qcalmin(6))+Refmin(6);\n im_B9=((Refmax(7)-Refmin(7))/(Qcalmax(7)-Qcalmin(7)))*(im_B9-Qcalmin(7))+Refmin(7);\n im_B10=((Lmax(8)-Lmin(8))/(Qcalmax(8)-Qcalmin(8)))*(im_B10-Qcalmin(8))+Lmin(8);\n \n % compute TOA reflectances\n % with a correction for the sun angle\n s_zen=deg2rad(zen);\n im_B2=10^4*im_B2/cos(s_zen);\n im_B3=10^4*im_B3/cos(s_zen);\n im_B4=10^4*im_B4/cos(s_zen);\n im_B5=10^4*im_B5/cos(s_zen);\n im_B6=10^4*im_B6/cos(s_zen);\n im_B7=10^4*im_B7/cos(s_zen);\n im_B9=10^4*im_B9/cos(s_zen);\n \n % convert Band6 from radiance to BT\n % fprintf('From Band 6 Radiance to Brightness Temperature\\n');\n K1_B10 = 774.89;\n K2_B10 = 1321.08;\n \n im_B10=K2_B10./log((K1_B10./im_B10)+1);\n\n % convert from Kelvin to Celcius with 0.01 scale_facor\n im_B10=100*(im_B10-273.15);\n\n % get data ready for Fmask\n im_B2(id_missing)=-9999;\n im_B3(id_missing)=-9999;\n im_B4(id_missing)=-9999;\n im_B5(id_missing)=-9999;\n im_B6(id_missing)=-9999;\n im_B7(id_missing)=-9999;\n im_B9(id_missing)=-9999;\n im_B10(id_missing) = -9999;\n clear id_missing; % empty memory\n \n TOAref=zeros(ijdim_ref(1),ijdim_ref(2),7,'single');% Band 2,3,4,5,6,7,& 9\n TOAref(:,:,1)=im_B2; clear im_B2;\n TOAref(:,:,2)=im_B3; clear im_B3;\n TOAref(:,:,3)=im_B4; clear im_B4;\n TOAref(:,:,4)=im_B5; clear im_B5;\n TOAref(:,:,5)=im_B6; clear im_B6;\n TOAref(:,:,6)=im_B7; clear im_B7;\n TOAref(:,:,7)=im_B9; clear im_B9;\n \n im_th=zeros(ijdim_ref(1),ijdim_ref(2),'single');% Band 10 \n im_th(:,:) = im_B10; clear im_B10; \nelse\n fprintf('This sensor is not Landsat 4, 5, 7, or 8!\\n');\n return;\nend\n\nend\n\n", "meta": {"author": "GERSL", "repo": "Fmask", "sha": "e9e0e23af163ec55c60b7f93e6ab8e72617ee851", "save_path": "github-repos/MATLAB/GERSL-Fmask", "path": "github-repos/MATLAB/GERSL-Fmask/Fmask-e9e0e23af163ec55c60b7f93e6ab8e72617ee851/nd2toarbt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.2509127812837603, "lm_q1q2_score": 0.15893073095308685}} {"text": "function [growthOnMinimalMedium,essentialExchanges,modelPruned] = predictGrowthRequirements(model)\n% Predicts growth requirements for a genome-scale reconstruction.\n% The list of predicted essential exchanges as well as a model\n% constrained with these exchanges are returned.\n%\n% INPUT\n% model COBRA model structure\n% biomassReaction String listing the biomass reaction\n%\n% OUTPUT\n% growthOnMinimalMedium Bool if growth on defined medium yes or no\n% essentialExchanges Exchanges that need to be open to enable growth\n% constrainedModel Model constrained with predicted essential\n% exchanges\n%\n% Almut Heinken, November 2020\n\ntol=1e-6;\n\n% set \"unlimited\" constraints\nmodel = changeRxnBounds(model, model.rxns(strncmp('EX_', model.rxns, 3)), -1000, 'l');\nmodel = changeRxnBounds(model, model.rxns(strncmp('EX_', model.rxns, 3)), 1000, 'u');\n\n% remove positive values on lower bounds\nmodel.lb(find(model.lb>0))=0;\n% \n% % remove compounds that should not be essential for any organism\n% unlikelyRequirements={'EX_alaasp(e)';'EX_alagln(e)';'EX_alaglu(e)';'EX_alagly(e)';'EX_alahis(e)';'EX_alaleu(e)';'EX_alathr(e)';'EX_glygln(e)';'EX_glyglu(e)';'EX_glyleu(e)';'EX_glymet(e)';'EX_glyphe(e)';'EX_glypro(e)';'EX_glytyr(e)';'EX_metala(e)';'EX_glyasn(e)';'EX_glyasp(e)';'EX_dpcoa(e)';'EX_coa(e)';'EX_cmp(e)';'EX_dtmp(e)';'EX_ump(e)';'EX_gmp(e)';'EX_dgtp(e)';'EX_nadp(e)';'EX_nad(e)';'EX_thmmp(e)';'EX_malt(e)';'EX_stys(e)';'EX_raffin(e)';'EX_melib(e)';'EX_lcts(e)';'EX_gtp(e)';'EX_datp(e)';'EX_amp(e)';'EX_pppi(e)';'EX_r5p(e)';'EX_g1p(e)';'EX_glu_D(e)';'EX_agm(e)';'EX_glycys(e)';'EX_1hibup_S(e)';'EX_1hibupglu_S(e)';'EX_1hmdgluc(e)';'EX_1ohmdz(e)';'EX_2hatvacid(e)';'EX_2hatvacidgluc(e)';'EX_2hatvlac(e)';'EX_2hatvlacgluc(e)';'EX_2hibup_S(e)';'EX_2hibupglu_S(e)';'EX_2oh_cbz_glc(e)';'EX_2oh_cbz(e)';'EX_2oh_mtz_glc(e)';'EX_2oh_mtz(e)';'EX_34dhphe(e)';'EX_3hibup_S(e)';'EX_3hibupglu_S(e)';'EX_3meacmp(e)';'EX_3oh_cbz_glc(e)';'EX_3oh_cbz(e)';'EX_3oh_dlor_glc(e)';'EX_3oh_dlor(e)';'EX_3oh_mdea_glc(e)';'EX_3oh_mdea(e)';'EX_3oh_mxn_glc(e)';'EX_3oh_mxn(e)';'EX_4dh_tpno_1glc(e)';'EX_4dh_tpno(e)';'EX_4hmdgluc(e)';'EX_4hphac(e)';'EX_4oh_dcf_glc(e)';'EX_4oh_dcf(e)';'EX_4oh_kp_glc(e)';'EX_4oh_kp(e)';'EX_4oh_levole_glc(e)';'EX_4oh_levole(e)';'EX_4oh_meth_glc(e)';'EX_4oh_meth(e)';'EX_4oh_propl_glc(e)';'EX_4oh_propl(e)';'EX_4oh_trz_glc(e)';'EX_4oh_trz(e)';'EX_4oh_vcz_glc(e)';'EX_4oh_vcz(e)';'EX_4ohmdz(e)';'EX_5asa(e)';'EX_5fura(e)';'EX_5oh_sulfp_glc(e)';'EX_5oh_sulfp(e)';'EX_5ohfvs(e)';'EX_5ohfvsglu(e)';'EX_6bhglz(e)';'EX_6bhglzglc(e)';'EX_6ohfvs(e)';'EX_6ohfvsglu(e)';'EX_7a_czp(e)';'EX_7bhglz(e)';'EX_7bhglzglc(e)';'EX_7oh_efv_glc(e)';'EX_7oh_efv(e)';'EX_814dioh_efv_glc(e)';'EX_814dioh_efv(e)';'EX_8oh_efv_glc(e)';'EX_8oh_efv(e)';'EX_abz_ala_b(e)';'EX_ac_amn_b_gly_glc(e)';'EX_ac_amn_b_gly(e)';'EX_ac5asa(e)';'EX_acisnzd(e)';'EX_acmp_glc(e)';'EX_acmp(e)';'EX_acmpglu(e)';'EX_alpz_4oh_glc(e)';'EX_alpz_4oh(e)';'EX_alpz_aoh_glc(e)';'EX_alpz_aoh(e)';'EX_am14_glc(e)';'EX_am14(e)';'EX_am1ccs(e)';'EX_am1cglc(e)';'EX_am5_glc(e)';'EX_am5(e)';'EX_am6_glc(e)';'EX_am6(e)';'EX_amio_c_glc(e)';'EX_amio_c(e)';'EX_amio_glc(e)';'EX_amio(e)';'EX_amn_b_gly_glc(e)';'EX_amn_b_gly(e)';'EX_amntd_m6_glc(e)';'EX_amntd_m6(e)';'EX_anzp(e)';'EX_atvacid(e)';'EX_atvacylgluc(e)';'EX_atvethgluc(e)';'EX_atvlac(e)';'EX_atvlacgluc(e)';'EX_bhpm_glc(e)';'EX_bhpm(e)';'EX_bilr_355(e)';'EX_bilr_M10(e)';'EX_bilr_M12(e)';'EX_bilr_M14(e)';'EX_bilr_M15(e)';'EX_bilr_M16(e)';'EX_bilr_M7(e)';'EX_brv(e)';'EX_bsn_glc(e)';'EX_bsn(e)';'EX_bvu(e)';'EX_bz_glc(e)';'EX_bz(e)';'EX_bzd(e)';'EX_C02528(e)';'EX_caribup_s(e)';'EX_caribupglu_S(e)';'EX_cbz_glc(e)';'EX_cbz(e)';'EX_cd6168_glc(e)';'EX_cd6168(e)';'EX_chlphncl_glc(e)';'EX_chlphncl(e)';'EX_cholate(e)';'EX_clcxb_c_glc(e)';'EX_clcxb_c(e)';'EX_clcxb_glc(e)';'EX_clcxb(e)';'EX_clobi_c(e)';'EX_clobi_glc(e)';'EX_crvsm1(e)';'EX_crvsm23(e)';'EX_cvm1gluc(e)';'EX_cvm23gluc(e)';'EX_czp(e)';'EX_daa_glc(e)';'EX_daa(e)';'EX_dcf_glc(e)';'EX_dcf(e)';'EX_dchac(e)';'EX_ddea_glc(e)';'EX_ddea(e)';'EX_des_astzl_glc(e)';'EX_des_astzl(e)';'EX_dfdcytd(e)';'EX_dfduri(e)';'EX_dgchol(e)';'EX_dh5fura(e)';'EX_digitoxin(e)';'EX_digoxin_glc(e)';'EX_digoxin(e)';'EX_dihydro_digitoxin(e)';'EX_dihydro_digoxin(e)';'EX_dlb_glc(e)';'EX_dlb(e)';'EX_dnpz_5des(e)';'EX_dnpz_6des(e)';'EX_dnpz_m11(e)';'EX_dnpz_m12(e)';'EX_dnpz_m13(e)';'EX_dnpz_m14(e)';'EX_dnpz_m9(e)';'EX_doh_etr_glc(e)';'EX_doh_etr(e)';'EX_doh_vcz_glc(e)';'EX_doh_vcz(e)';'EX_dopa(e)';'EX_dxo_glc(e)';'EX_dxo(e)';'EX_efv_glc(e)';'EX_efv(e)';'EX_eltr_glc(e)';'EX_eltr_m3(e)';'EX_eltr_m4(e)';'EX_eltr(e)';'EX_estradiol(e)';'EX_estradiolglc(e)';'EX_estriol(e)';'EX_estriolglc(e)';'EX_estrone(e)';'EX_estroneglc(e)';'EX_eztmb_glc(e)';'EX_eztmb(e)';'EX_fcsn(e)';'EX_fvs(e)';'EX_fvsgluc(e)';'EX_fvstet(e)';'EX_fvstetglu(e)';'EX_gchola(e)';'EX_glc3meacp(e)';'EX_gltmn_glc(e)';'EX_gltmn(e)';'EX_gmfl_glc(e)';'EX_gmfl_mI_glc(e)';'EX_gmfl_mI(e)';'EX_gmfl_mII_glc(e)';'EX_gmfl_mII(e)';'EX_gmfl_mIII_glc(e)';'EX_gmfl_mIII(e)';'EX_gmfl(e)';'EX_gtacmp(e)';'EX_HC02191(e)';'EX_hst_3_glc(e)';'EX_hst_3_s(e)';'EX_hst_37_diglc(e)';'EX_hst_3glc_7s(e)';'EX_hst_7_glc(e)';'EX_hst_7_s(e)';'EX_hst_7glc_3s(e)';'EX_hst(e)';'EX_ibup_S(e)';'EX_ibupgluc(e)';'EX_imn_glc(e)';'EX_imn(e)';'EX_inv_m1(e)';'EX_inv(e)';'EX_isnzd(e)';'EX_isosorbide_5mn_glc(e)';'EX_isosorbide_5mn(e)';'EX_kprofen_glc(e)';'EX_kprofen(e)';'EX_lactl(e)';'EX_lst4exp(e)';'EX_lstn(e)';'EX_lstn1gluc(e)';'EX_lstnm4(e)';'EX_lstnm7(e)';'EX_mdz_glc(e)';'EX_mdz(e)';'EX_mdzglc(e)';'EX_miso_glc(e)';'EX_miso(e)';'EX_mrphn_3glc(e)';'EX_mrphn_6glc(e)';'EX_mrphn(e)';'EX_mtym(e)';'EX_mtz_glc(e)';'EX_mtz(e)';'EX_N_oh_phtn_glc(e)';'EX_N_oh_phtn(e)';'EX_nchlphncl(e)';'EX_neopront(e)';'EX_nsldp_m5_glc(e)';'EX_nsldp_m5(e)';'EX_nverp_glc(e)';'EX_nverp(e)';'EX_nzp(e)';'EX_odsm_egltmn_glc(e)';'EX_odsm_egltmn(e)';'EX_odsm_gltmn_glc(e)';'EX_odsm_gltmn(e)';'EX_oh_etr_glc(e)';'EX_oh_etr(e)';'EX_oh_pbl_glc(e)';'EX_oh_pbl(e)';'EX_olsa(e)';'EX_pcresol(e)';'EX_phppa_glc(e)';'EX_phppa(e)';'EX_phtn_glc(e)';'EX_prob_glc(e)';'EX_prob(e)';'EX_pront_glc(e)';'EX_pront(e)';'EX_propl_glc(e)';'EX_propl(e)';'EX_prx_mI_glc(e)';'EX_prx_mI(e)';'EX_prx_mII_glc(e)';'EX_prx_mII(e)';'EX_ptvst(e)';'EX_ptvstgluc(e)';'EX_pvs(e)';'EX_pvsgluc(e)';'EX_R_6oh_warf_glc(e)';'EX_R_6oh_warf(e)';'EX_R_7oh_warf_glc(e)';'EX_R_7oh_warf(e)';'EX_R_8oh_warf_glc(e)';'EX_R_8oh_warf(e)';'EX_r406_glc(e)';'EX_r406(e)';'EX_r529_glc(e)';'EX_r529(e)';'EX_r788(e)';'EX_regfnb_glc(e)';'EX_regfnb(e)';'EX_rep_glc(e)';'EX_rep(e)';'EX_rpn_104557_cb_glc(e)';'EX_rpn_104557(e)';'EX_rpn_96990_glc(e)';'EX_rpn_96990(e)';'EX_rpn_oh_glc(e)';'EX_rpn_oh(e)';'EX_rsv(e)';'EX_rsvgluc(e)';'EX_S_4oh_warf_glc(e)';'EX_S_4oh_warf(e)';'EX_S_6oh_warf_glc(e)';'EX_S_6oh_warf(e)';'EX_sanilamide(e)';'EX_sb_611855(e)';'EX_sb_y(e)';'EX_sch_488128(e)';'EX_sch_57871_glc(e)';'EX_sch_57871(e)';'EX_sfnd_1689_glc(e)';'EX_sfnd_1689(e)';'EX_sftz_glc(e)';'EX_sftz(e)';'EX_simvgluc(e)';'EX_smap_glc(e)';'EX_smap(e)';'EX_smvacid(e)';'EX_sn38(e)';'EX_sn38g(e)';'EX_spz_glc(e)';'EX_spz_sfn_glc(e)';'EX_spz_sfn(e)';'EX_spz(e)';'EX_srv(e)';'EX_ssz(e)';'EX_stg_m3(e)';'EX_stg_m4(e)';'EX_stg(e)';'EX_sulfp(e)';'EX_tab(e)';'EX_tat(e)';'EX_taur(e)';'EX_tchola(e)';'EX_tdchola(e)';'EX_tgz_glc(e)';'EX_tgz(e)';'EX_thsacmp(e)';'EX_tlf_a_1a(e)';'EX_tlf_a_1b(e)';'EX_tlf_a_1x(e)';'EX_tlf_a_2(e)';'EX_tlf_a_2a(e)';'EX_tlf_a_3(e)';'EX_tlf_a_4(e)';'EX_tlf_a_m1(e)';'EX_tlf_a_m2(e)';'EX_tlf_a_m3(e)';'EX_tlf_a_m4(e)';'EX_tlf_a_m4a(e)';'EX_tlf_a_m5(e)';'EX_tlf_a_m5a(e)';'EX_tlf_a_m5b(e)';'EX_tlf_a_m6(e)';'EX_tlf_a_m9(e)';'EX_tlf_a(e)';'EX_tlms_glc(e)';'EX_tlms(e)';'EX_tmacmp(e)';'EX_tolcp_ac_glc(e)';'EX_tolcp_ac(e)';'EX_tolcp_am_glc(e)';'EX_tolcp_am(e)';'EX_tolcp_glc(e)';'EX_tolcp(e)';'EX_tpno_1glc_4g(e)';'EX_tpno_4g(e)';'EX_tpno_4glc(e)';'EX_tpnoh(e)';'EX_tsacmgluc(e)';'EX_tym(e)'};\n% model=changeRxnBounds(model,unlikelyRequirements,0,'l');\n\n% set objective\nbiomassReaction=model.rxns{find(strncmp(model.rxns,'bio',3)),1};\nmodel = changeObjective(model, biomassReaction);\n\n[modelMin, modelPruned, essentialExchanges] = generateCompactExchModel(model,tol,biomassReaction,1,1);\nmodelMin = changeObjective(modelMin, biomassReaction);\nFBA=optimizeCbModel(modelMin,'max');\ngrowthOnMinimalMedium=FBA.f;\n\nend", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/src/reconstruction/demeter/src/properties/predictGrowthRequirements.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765155565327, "lm_q2_score": 0.2782567877172032, "lm_q1q2_score": 0.1564294313488111}} {"text": "%%*****************************************************************\n%% validate: validate data\n%%*****************************************************************\n%% SDPT3: version 4.0\n%% Copyright (c) 1997 by\n%% Kim-Chuan Toh, Michael J. Todd, Reha H. Tutuncu\n%% Last Modified: 16 Sep 2004\n%%*****************************************************************\n\n function [blk,At,C,b,dim,nnblk,parbarrier] = ...\n validate(blk,At,C,b,par,parbarrier);\n\n if (nargin >= 5)\n spdensity = par.spdensity; \n else\n spdensity = 0.4; \n end\n%%\n if ~iscell(blk); \n error('validate: blk must be a cell array'); end; \n if (size(blk,2) < 2)\n error('validate: blk must be a cell array with at least 2 columns');\n end \n if ~iscell(At) | ~iscell(C); \n error('validate: At, C must be cell arrays'); \n end\n if (size(At,1) ~= size(blk,1)) \n if (size(At,2) == size(blk,1)); \n At = At'; \n else \n error('validate: size of At is not compatible with blk'); \n end\n end \n if (size(C,1) ~= size(blk,1)) \n if (size(C,2) == size(blk,1)) \n C = C'; \n else\n error('validate: size of C is not compatible with blk'); \n end\n end \n if (min(size(b)) > 1); error('validate: b must be a vector'); end\n if (size(b,1) < size(b,2)); b = b'; end\n m = length(b);\n%%\n%%-----------------------------------------\n%% validate blk, At, C\n%%-----------------------------------------\n%%\n for p = 1:size(blk,1)\n if (size(blk{p,2},1) > size(blk{p,2},2)) \n blk{p,2} = blk{p,2}'; \n end\n pblk = blk(p,:); \n n = sum(pblk{2}); \n numblk = length(pblk{2});\n if strcmp(pblk{1},'s');\n m1 = size(At{p,1},2); \n n2 = sum(pblk{2}.*pblk{2}); n22 = sum(pblk{2}.*(pblk{2}+1))/2; \n ntotal(p) = n22; \n if ~all(size(C{p}) == n) \n error('validate: blk and C are not compatible'); \n end \n if (norm(C{p}-C{p}',inf) > 1e-13*norm(C{p},inf)); \n error('validate: C is not symmetric'); \n end\n if (size(At{p,1}) == [m1, n22] & m1~=n22); \n At{p,1} = At{p,1}'; \n end\n if (~isempty(At{p,1})) & (size(At{p,1},1) ~= n22)\n error('validate: blk and At not compatible'); \n end \n if (nnz(At{p,1}) < spdensity*n22*m1)\n if ~issparse(At{p,1}); At{p,1} = sparse(At{p,1}); end \n end\n if (length(pblk) > 2) %% for low rank constraints\n len = sum(pblk{3});\n if (size(pblk{1,3},2) < size(pblk{1,3},1))\n blk{p,3} = blk{p,3}'; \n end\n if any(size(At{p,2})- [n,len])\n error(' low rank structure specified in blk and At not compatible') \n end\n if (length(At(p,:)) > 2) & ~isempty(At{p,3})\n if all(size(At{p,3},2)-[1,4])\n error(' low rank structure in At{p,3} not specified correctly')\n end\n if (size(At{p,3},2) == 1)\n if (size(At{p,3},1) < size(At{p,3},2)); At{p,3} = At{p,3}'; end\n lenn = length(At{p,3});\n constrnum = mexexpand(pblk{3},[1:length(pblk{3})]');\n At{p,3} = [constrnum, [1:lenn]', [1:lenn]', At{p,3}];\n elseif (size(At{p,3},2) == 4)\n dd = At{p,3};\n [dummy,idxsort] = sort(dd(:,1)); \n dd = dd(idxsort,:); \n lenn = size(dd,1);\n idxD = [0; find(diff(dd(:,1))); lenn];\n ii = zeros(lenn,1); jj = zeros(lenn,1);\n ss = [0,cumsum(pblk{3})];\n for k = 1:length(pblk{3})\n idx = [idxD(k)+1 : idxD(k+1)];\n ii(idx) = dd(idx,2)+ss(k); %% convert to cumulative indexing\n jj(idx) = dd(idx,3)+ss(k);\n end\n At{p,3} = [dd(:,1),ii,jj,dd(:,4)];\n end\n else\n constrnum = mexexpand(pblk{3},[1:length(pblk{3})]');\n At{p,3} = [constrnum, [1:len]', [1:len]', ones(len,1)]; \n end\n end\n if (nnz(C{p}) < spdensity*n2) | (numblk > 1); \n if ~issparse(C{p}); C{p} = sparse(C{p}); end;\n else\n if issparse(C{p}); C{p} = full(C{p}); end; \n end\n elseif strcmp(pblk{1},'q') | strcmp(pblk{1},'l') | strcmp(pblk{1},'u'); \n ntotal(p) = n; \n if (min(size(C{p})) ~= 1 | max(size(C{p})) ~= n); \n error(['validate: blk and C are not compatible']); \n end; \n if (size(C{p},1) < size(C{p},2)); C{p} = C{p}'; end\n if (size(At{p,1}) == [m, n] & m~=n); \n At{p,1} = At{p,1}'; \n end\n if ~all(size(At{p,1}) == [n,m]);\n error('validate: blk and At not compatible'); \n end\n if ~issparse(At{p,1}); \n At{p,1} = sparse(At{p,1}); \n end \n if (nnz(C{p}) < spdensity*n); \n if ~issparse(C{p}); C{p} = sparse(C{p}); end; \n else\n if issparse(C{p}); C{p} = full(C{p}); end;\n end;\n else\n error(' blk: some fields are not specified correctly'); \n end\n end\n if (sum(ntotal) < m) \n error(' total dimension of C should be > length(b)'); \n end\n%%\n%%-----------------------------------------\n%% problem dimension\n%%-----------------------------------------\n%%\n dim = zeros(1,4); nnblk = zeros(1,2); \n for p = 1:size(blk,1)\n pblk = blk(p,:);\n if strcmp(pblk{1},'s')\n dim(1) = dim(1) + sum(pblk{2}); \n nnblk(1) = nnblk(1) + length(pblk{2});\n nn(p) = sum(pblk{2}); \n elseif strcmp(pblk{1},'q')\n dim(2) = dim(2) + sum(pblk{2}); \n nnblk(2) = nnblk(2) + length(pblk{2});\n nn(p) = length(pblk{2}); \n elseif strcmp(pblk{1},'l')\n dim(3) = dim(3) + sum(pblk{2}); \n nn(p) = sum(pblk{2}); \n elseif strcmp(pblk{1},'u')\n dim(4) = dim(4) + sum(pblk{2}); \n nn(p) = sum(pblk{2}); \n end\n end\n%%\n%%-----------------------------------------\n%% validate parbarrier\n%%-----------------------------------------\n%% \n if (nargin == 6)\n if ~iscell(parbarrier); \n\t if (length(parbarrier) == size(blk,1))\n\t tmp = parbarrier; \n clear parbarrier;\n\t parbarrier = cell(size(blk,1),1);\n\t for p = 1:size(blk,1)\n\t\tparbarrier{p} = tmp(p); \n end\n end\n end \n if (size(parbarrier,2) > size(parbarrier,1))\n parbarrier = parbarrier'; \n end\n for p = 1:size(blk,1)\n pblk = blk(p,:); \n if (size(parbarrier{p},1) > size(parbarrier{p},2))\n parbarrier{p} = parbarrier{p}'; \n end\n len = length(parbarrier{p}); \n if strcmp(pblk{1},'s') | strcmp(pblk{1},'q')\n if (len == 1)\n parbarrier{p} = parbarrier{p}*ones(1,length(pblk{2})); \n\t elseif (len == 0)\n parbarrier{p} = zeros(1,length(pblk{2})); \n\t elseif (len ~= length(pblk{2}))\n error('blk and parbarrier not compatible');\n end\n elseif strcmp(pblk{1},'l')\n if (len == 1)\n parbarrier{p} = parbarrier{p}*ones(1,sum(pblk{2})); \n\t elseif (len == 0)\n\t\tparbarrier{p} = zeros(1,sum(pblk{2})); \n elseif (len ~= sum(pblk{2}))\n error('blk and parbarrier not compatible'); \n end\n elseif strcmp(pblk{1},'u')\n parbarrier{p}= zeros(1,sum(pblk{2})); \n end \n end\n end\n%%***********************************************************************\n", "meta": {"author": "yu-jiang", "repo": "radpbook", "sha": "88b9fa7d0a541099cdd1ac29383c89e087d1d895", "save_path": "github-repos/MATLAB/yu-jiang-radpbook", "path": "github-repos/MATLAB/yu-jiang-radpbook/radpbook-88b9fa7d0a541099cdd1ac29383c89e087d1d895/tools/SDPT3-4.0/SDPT3-4.0/Solver/validate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.3040416812727289, "lm_q1q2_score": 0.15558317682942682}} {"text": "function spm_reslice(P,flags)\n% Rigid body reslicing of images\n% FORMAT spm_reslice(P,flags)\n%\n% P - matrix or cell array of filenames {one string per row}\n% All operations are performed relative to the first image.\n% ie. Coregistration is to the first image, and resampling\n% of images is into the space of the first image.\n%\n% flags - a structure containing various options. The fields are:\n%\n% mask - mask output images (true/false) [default: true]\n% To avoid artifactual movement-related variance the\n% realigned set of images can be internally masked, within\n% the set (i.e. if any image has a zero value at a voxel\n% than all images have zero values at that voxel). Zero\n% values occur when regions 'outside' the image are moved\n% 'inside' the image during realignment.\n%\n% mean - write mean image (true/false) [default: true]\n% The average of all the realigned scans is written to\n% an image file with 'mean' prefix.\n%\n% interp - the B-spline interpolation method [default: 1]\n% Non-finite values result in Fourier interpolation. Note\n% that Fourier interpolation only works for purely rigid\n% body transformations. Voxel sizes must all be identical\n% and isotropic.\n%\n% which - values of 0, 1 or 2 are allowed [default: 2]\n% 0 - don't create any resliced images.\n% Useful if you only want a mean resliced image.\n% 1 - don't reslice the first image.\n% The first image is not actually moved, so it may\n% not be necessary to resample it.\n% 2 - reslice all the images.\n% If which is a 2-element vector, flags.mean will be set\n% to flags.which(2).\n%\n% wrap - three values of either 0 or 1, representing wrapping in\n% each of the dimensions. For fMRI, [1 1 0] would be used.\n% For PET, it would be [0 0 0]. [default: [0 0 0]]\n%\n% prefix - prefix for resliced images [default: 'r']\n%\n%__________________________________________________________________________\n%\n% The spatially realigned images are written to the original subdirectory\n% with the same (prefixed) filename. They are all aligned with the first.\n%\n% Inputs:\n% A series of images conforming to SPM data format (see 'Data Format'). The\n% relative displacement of the images is stored in their header.\n%\n% Outputs:\n% The routine uses information in their headers and writes the realigned \n% image files to the same subdirectory with a prefix.\n%__________________________________________________________________________\n% Copyright (C) 1999-2017 Wellcome Trust Centre for Neuroimaging\n\n% John Ashburner\n% $Id: spm_reslice.m 7141 2017-07-26 09:05:05Z guillaume $\n\n%__________________________________________________________________________\n%\n% The headers of the images contain a 4x4 affine transformation matrix 'M',\n% usually affected by the `realignment' and `coregistration' modules.\n% What these matrices contain is a mapping from the voxel coordinates\n% (x0,y0,z0) (where the first voxel is at coordinate (1,1,1)), to \n% coordinates in millimeters (x1,y1,z1).\n%\n% x1 = M(1,1)*x0 + M(1,2)*y0 + M(1,3)*z0 + M(1,4)\n% y1 = M(2,1)*x0 + M(2,2)*y0 + M(2,3)*z0 + M(2,4)\n% z1 = M(3,1)*x0 + M(3,2)*y0 + M(3,3)*z0 + M(3,4)\n%\n% Assuming that image1 has a transformation matrix M1, and image2 has a\n% transformation matrix M2, the mapping from image1 to image2 is: M2\\M1\n% (ie. from the coordinate system of image1 into millimeters, followed\n% by a mapping from millimeters into the space of image2).\n%\n% Several spatial transformations (realignment, coregistration,\n% normalisation) can be combined into a single operation (without the\n% necessity of resampling the images several times).\n%__________________________________________________________________________\n%\n% Refs:\n%\n% Friston KJ, Williams SR, Howard R Frackowiak RSJ and Turner R (1995)\n% Movement-related effect in fMRI time-series. Mag. Res. Med. 35:346-355\n%\n% W. F. Eddy, M. Fitzgerald and D. C. Noll (1996) Improved Image\n% Registration by Using Fourier Interpolation. Mag. Res. Med. 36(6):923-931\n%\n% R. W. Cox and A. Jesmanowicz (1999) Real-Time 3D Image Registration\n% for Functional MRI. Mag. Res. Med. 42(6):1014-1018\n%__________________________________________________________________________\n\n\nSVNid = '$Rev: 7141 $';\n \n%-Say hello\n%--------------------------------------------------------------------------\nSPMid = spm('FnBanner',mfilename,SVNid);\n\n%-Parameters\n%--------------------------------------------------------------------------\nif ~nargin, P = spm_select([1 Inf],'image'); end\nif iscellstr(P), P = char(P); end\nif ischar(P), P = spm_vol(P); end\n\ndef_flags = spm_get_defaults('realign.write');\ndef_flags.prefix = 'r';\nif nargin < 2\n flags = def_flags;\nelse\n fnms = fieldnames(def_flags);\n for i=1:length(fnms)\n if ~isfield(flags,fnms{i})\n flags.(fnms{i}) = def_flags.(fnms{i});\n end\n end\nend\n\nif numel(flags.which) == 2\n flags.mean = flags.which(2);\n flags.which = flags.which(1);\nelseif ~isfield(flags,'mean')\n flags.mean = 1; \nend\n\n%-Reslice\n%--------------------------------------------------------------------------\nif isempty(P)\n warning('Nothing to do.');\nelse\n reslice_images(P,flags);\nend\n\nfprintf('%-40s: %30s\\n','Completed',spm('time')) %-#\n\n\n%==========================================================================\n%-function reslice_images(P,flags)\n%==========================================================================\nfunction reslice_images(P,flags)\n% Reslice images volume by volume\n% FORMAT reslice_images(P,flags)\n% See main function for a description of the input parameters\n\nif ~isfinite(flags.interp) % Use Fourier method\n % Check for non-rigid transformations in the matrixes\n for i=1:numel(P)\n pp = P(1).mat\\P(i).mat;\n if any(abs(svd(pp(1:3,1:3))-1)>1e-7)\n fprintf('\\n Zooms or shears appear to be needed');\n fprintf('\\n (probably due to non-isotropic voxels).');\n fprintf('\\n These can not yet be done using the');\n fprintf('\\n Fourier reslicing method. Switching to');\n fprintf('\\n 7th degree B-spline interpolation instead.\\n\\n');\n flags.interp = 7;\n break\n end\n end\nend\n\nif flags.mask || flags.mean\n spm_progress_bar('Init',P(1).dim(3),'Computing available voxels','planes completed');\n x1 = repmat((1:P(1).dim(1))',1,P(1).dim(2));\n x2 = repmat( 1:P(1).dim(2) ,P(1).dim(1),1);\n if flags.mean\n Count = zeros(P(1).dim(1:3));\n Integral = zeros(P(1).dim(1:3));\n end\n if flags.mask, msk = cell(P(1).dim(3),1); end\n for x3 = 1:P(1).dim(3)\n tmp = zeros(P(1).dim(1:2));\n for i = 1:numel(P)\n tmp = tmp + getmask(inv(P(1).mat\\P(i).mat),x1,x2,x3,P(i).dim(1:3),flags.wrap);\n end\n if flags.mask, msk{x3} = find(tmp ~= numel(P)); end\n if flags.mean, Count(:,:,x3) = tmp; end\n spm_progress_bar('Set',x3);\n end\nend\n\nnread = numel(P);\nif ~flags.mean\n if flags.which == 1, nread = nread - 1; end\n if flags.which == 0, nread = 0; end\nend\nspm_progress_bar('Init',nread,'Reslicing','volumes completed');\n\n[x1,x2] = ndgrid(1:P(1).dim(1),1:P(1).dim(2));\nnread = 0;\nd = [flags.interp*[1 1 1]' flags.wrap(:)];\n\nfor i = 1:numel(P)\n\n if (i>1 && flags.which==1) || flags.which==2\n write_vol = 1;\n else\n write_vol = 0;\n end\n if write_vol || flags.mean\n read_vol = 1;\n else\n read_vol = 0;\n end\n\n if read_vol\n if ~isfinite(flags.interp)\n v = abs(kspace3d(spm_bsplinc(P(i),[0 0 0 ; 0 0 0]'),P(1).mat\\P(i).mat));\n for x3 = 1:P(1).dim(3)\n if flags.mean\n Integral(:,:,x3) = ...\n Integral(:,:,x3) + ...\n nan2zero(v(:,:,x3) .* ...\n getmask(inv(P(1).mat\\P(i).mat),x1,x2,x3,P(i).dim(1:3),flags.wrap));\n end\n if flags.mask\n tmp = v(:,:,x3); tmp(msk{x3}) = NaN; v(:,:,x3) = tmp;\n end\n end\n else\n C = spm_bsplinc(P(i), d);\n v = zeros(P(1).dim);\n for x3 = 1:P(1).dim(3)\n [tmp,y1,y2,y3] = getmask(inv(P(1).mat\\P(i).mat),x1,x2,x3,P(i).dim(1:3),flags.wrap);\n v(:,:,x3) = spm_bsplins(C, y1,y2,y3, d);\n % v(~tmp) = 0;\n\n if flags.mean\n Integral(:,:,x3) = Integral(:,:,x3) + nan2zero(v(:,:,x3));\n end\n if flags.mask\n tmp = v(:,:,x3); tmp(msk{x3}) = NaN; v(:,:,x3) = tmp;\n end\n end\n end\n if write_vol\n VO = P(i);\n VO.fname = spm_file(P(i).fname, 'prefix',flags.prefix);\n VO.dim = P(1).dim(1:3);\n VO.dt = P(i).dt;\n VO.pinfo = P(i).pinfo;\n VO.mat = P(1).mat;\n VO.descrip = 'spm - realigned';\n VO = spm_write_vol(VO,v);\n end\n\n nread = nread + 1;\n end\n spm_progress_bar('Set',nread);\nend\n\nif flags.mean\n % Write integral image (16 bit signed)\n %----------------------------------------------------------------------\n Integral = Integral./Count;\n PO = P(1);\n PO.fname = spm_file(P(1).fname, 'prefix','mean');\n PO = rmfield(PO,'pinfo');\n PO.pinfo = [max(max(max(Integral)))/32767 0 0]';\n PO.n = [1 1];\n PO.descrip = 'spm - mean image';\n PO.dt = [spm_type('int16') spm_platform('bigend')];\n spm_write_vol(PO,Integral);\nend\n\nspm_progress_bar('Clear');\n\n\n%==========================================================================\n%-function v = kspace3d(v,M)\n%==========================================================================\nfunction v = kspace3d(v,M)\n% 3D rigid body transformation performed as shears in 1D Fourier space\n% FORMAT v = kspace3d(v,M)\n% v - image stored as a 3D array\n% M - rigid body transformation matrix\n%\n% v - transformed image\n%\n% References:\n% R. W. Cox and A. Jesmanowicz (1999)\n% Real-Time 3D Image Registration for Functional MRI\n% Magnetic Resonance in Medicine 42(6):1014-1018\n%\n% W. F. Eddy, M. Fitzgerald and D. C. Noll (1996)\n% Improved Image Registration by Using Fourier Interpolation\n% Magnetic Resonance in Medicine 36(6):923-931\n\n[S0,S1,S2,S3] = shear_decomp(M);\n\nd = [size(v) 1 1 1];\ng = 2.^ceil(log2(d));\nif any(g~=d)\n tmp = v;\n v = zeros(g);\n v(1:d(1),1:d(2),1:d(3)) = tmp;\n clear tmp;\nend\n\n% XY-shear\ntmp1 = -sqrt(-1)*2*pi*([0:((g(3)-1)/2) 0 (-g(3)/2+1):-1])/g(3);\nfor j=1:g(2)\n t = reshape( exp((j*S3(3,2) + S3(3,1)*(1:g(1)) + S3(3,4)).'*tmp1) ,[g(1) 1 g(3)]);\n v(:,j,:) = real(ifft(fft(v(:,j,:),[],3).*t,[],3));\nend\n\n% XZ-shear\ntmp1 = -sqrt(-1)*2*pi*([0:((g(2)-1)/2) 0 (-g(2)/2+1):-1])/g(2);\nfor k=1:g(3)\n t = exp( (k*S2(2,3) + S2(2,1)*(1:g(1)) + S2(2,4)).'*tmp1);\n v(:,:,k) = real(ifft(fft(v(:,:,k),[],2).*t,[],2));\nend\n\n% YZ-shear\ntmp1 = -sqrt(-1)*2*pi*([0:((g(1)-1)/2) 0 (-g(1)/2+1):-1])/g(1);\nfor k=1:g(3)\n t = exp( tmp1.'*(k*S1(1,3) + S1(1,2)*(1:g(2)) + S1(1,4)));\n v(:,:,k) = real(ifft(fft(v(:,:,k),[],1).*t,[],1));\nend\n\n% XY-shear\ntmp1 = -sqrt(-1)*2*pi*([0:((g(3)-1)/2) 0 (-g(3)/2+1):-1])/g(3);\nfor j=1:g(2)\n t = reshape( exp( (j*S0(3,2) + S0(3,1)*(1:g(1)) + S0(3,4)).'*tmp1) ,[g(1) 1 g(3)]);\n v(:,j,:) = real(ifft(fft(v(:,j,:),[],3).*t,[],3));\nend\n\nif any(g~=d), v = v(1:d(1),1:d(2),1:d(3)); end\n\n\n%==========================================================================\n%-function [S0,S1,S2,S3] = shear_decomp(A)\n%==========================================================================\nfunction [S0,S1,S2,S3] = shear_decomp(A)\n% Decompose rotation and translation matrix A into shears S0, S1, S2 and\n% S3, such that A = S0*S1*S2*S3. The original procedure is documented in:\n% R. W. Cox and A. Jesmanowicz (1999)\n% Real-Time 3D Image Registration for Functional MRI\n% Magnetic Resonance in Medicine 42(6):1014-1018\n\nA0 = A(1:3,1:3);\nif any(abs(svd(A0)-1)>1e-7), error('Cannot decompose matrix.'); end\n\nt = A0(2,3); if t==0, t=eps; end\na0 = pinv(A0([1 2],[2 3])')*[(A0(3,2)-(A0(2,2)-1)/t) (A0(3,3)-1)]';\nS0 = [1 0 0; 0 1 0; a0(1) a0(2) 1];\nA1 = S0\\A0; a1 = pinv(A1([2 3],[2 3])')*A1(1,[2 3])'; S1 = [1 a1(1) a1(2); 0 1 0; 0 0 1];\nA2 = S1\\A1; a2 = pinv(A2([1 3],[1 3])')*A2(2,[1 3])'; S2 = [1 0 0; a2(1) 1 a2(2); 0 0 1];\nA3 = S2\\A2; a3 = pinv(A3([1 2],[1 2])')*A3(3,[1 2])'; S3 = [1 0 0; 0 1 0; a3(1) a3(2) 1];\n\ns3 = A(3,4)-a0(1)*A(1,4)-a0(2)*A(2,4);\ns1 = A(1,4)-a1(1)*A(2,4);\ns2 = A(2,4);\nS0 = [[S0 [0 0 s3]'];[0 0 0 1]];\nS1 = [[S1 [s1 0 0]'];[0 0 0 1]];\nS2 = [[S2 [0 s2 0]'];[0 0 0 1]];\nS3 = [[S3 [0 0 0]'];[0 0 0 1]];\n\n\n%==========================================================================\n%-function [Mask,y1,y2,y3] = getmask(M,x1,x2,x3,dim,wrp)\n%==========================================================================\nfunction [Mask,y1,y2,y3] = getmask(M,x1,x2,x3,dim,wrp)\ntiny = 5e-2; % From spm_vol_utils.c\ny1 = M(1,1)*x1+M(1,2)*x2+(M(1,3)*x3+M(1,4));\ny2 = M(2,1)*x1+M(2,2)*x2+(M(2,3)*x3+M(2,4));\ny3 = M(3,1)*x1+M(3,2)*x2+(M(3,3)*x3+M(3,4));\nMask = true(size(y1));\nif ~wrp(1), Mask = Mask & (y1 >= (1-tiny) & y1 <= (dim(1)+tiny)); end\nif ~wrp(2), Mask = Mask & (y2 >= (1-tiny) & y2 <= (dim(2)+tiny)); end\nif ~wrp(3), Mask = Mask & (y3 >= (1-tiny) & y3 <= (dim(3)+tiny)); end\n\n\n%==========================================================================\n%-function vo = nan2zero(vi)\n%==========================================================================\nfunction vo = nan2zero(vi)\nvo = vi;\nvo(~isfinite(vo)) = 0;\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/spm_reslice.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.29421498454004374, "lm_q1q2_score": 0.15514442277382895}}